Display a linear combination: Difference between revisions

Applesoft BASIC
(Applesoft BASIC)
 
(41 intermediate revisions by 25 users not shown)
Line 1:
{{draft task}}
 
;Task:
Line 38:
=={{header|11l}}==
{{trans|Python}}
<langsyntaxhighlight lang="11l">F linear(x)
V a = enumerate(x).filter2((i, v) -> v != 0).mapmap2((i, v) -> ‘#.e(#.0)’.format(I v == -1 {‘-’} E I v == 1 {‘’} E String(v)‘*’, i + 1))
R (I !a.empty {a} E [String(‘0’)]).join(‘ + ’).replace(‘ + -’, ‘ - ’)
 
L(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]]
print(linear(x))</langsyntaxhighlight>
{{out}}
<pre>
Line 57:
-e(1)
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Text_Io;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
 
procedure Display_Linear is
 
subtype Position is Positive;
type Coefficient is new Integer;
type Combination is array (Position range <>) of Coefficient;
 
function Linear_Combination (Comb : Combination) return String is
use Ada.Strings.Unbounded;
use Ada.Strings;
Accu : Unbounded_String;
begin
for Pos in Comb'Range loop
case Comb (Pos) is
when Coefficient'First .. -1 =>
Append (Accu, (if Accu = "" then "-" else " - "));
when 0 => null;
when 1 .. Coefficient'Last =>
Append (Accu, (if Accu /= "" then " + " else ""));
end case;
 
if Comb (Pos) /= 0 then
declare
Abs_Coeff : constant Coefficient := abs Comb (Pos);
Coeff_Image : constant String := Fixed.Trim (Coefficient'Image (Abs_Coeff), Left);
Exp_Image : constant String := Fixed.Trim (Position'Image (Pos), Left);
begin
if Abs_Coeff /= 1 then
Append (Accu, Coeff_Image & "*");
end if;
Append (Accu, "e(" & Exp_Image & ")");
end;
end if;
end loop;
 
return (if Accu = "" then "0" else To_String (Accu));
end Linear_Combination;
 
use Ada.Text_Io;
begin
Put_Line (Linear_Combination ((1, 2, 3)));
Put_Line (Linear_Combination ((0, 1, 2, 3)));
Put_Line (Linear_Combination ((1, 0, 3, 4)));
Put_Line (Linear_Combination ((1, 2, 0)));
Put_Line (Linear_Combination ((0, 0, 0)));
Put_Line (Linear_Combination ((1 => 0)));
Put_Line (Linear_Combination ((1, 1, 1)));
Put_Line (Linear_Combination ((-1, -1, -1)));
Put_Line (Linear_Combination ((-1, -2, 0, -3)));
Put_Line (Linear_Combination ((1 => -1)));
end Display_Linear;</syntaxhighlight>
{{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>
 
=={{header|ALGOL 68}}==
Using implicit multiplication operators, as in the C and Mathematica samples.
<syntaxhighlight lang="algol68">
BEGIN # display a string representation of some linear combinations #
# returns a string representing the sum of the terms of a linear combination #
# whose coefficients are the elements of coeffs #
PROC linear combination = ( []INT coeffs )STRING:
BEGIN
[]INT cf = coeffs[ AT 1 ]; # ensure the lower bound is 1 #
STRING result := "";
BOOL first term := TRUE;
FOR i FROM LWB cf TO UPB cf DO
IF INT c = cf[ i ];
c /= 0
THEN # non-null element #
IF first term THEN
# first term - only add the operator if it is "-" #
IF c < 0 THEN result +:= "-" FI;
first term := FALSE
ELSE
# second or subsequent term - separate from the previous #
# and always add the operator #
result +:= " " + IF c < 0 THEN "-" ELSE "+" FI + " "
FI;
# add the coefficient, unless it is one #
IF ABS c /= 1 THEN
result +:= whole( ABS c, 0 )
FI;
# add the vector #
result +:= "e(" + whole( i, 0 ) + ")"
FI
OD;
IF result = "" THEN "0" ELSE result FI
END # linear combination # ;
 
# test cases #
[][]INT 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 FROM LWB tests TO UPB tests DO
print( ( linear combination( tests[ i ] ), newline ) )
OD
END
</syntaxhighlight>
{{out}}
<pre>
e(1) + 2e(2) + 3e(3)
e(2) + 2e(3) + 3e(4)
e(1) + 3e(3) + 4e(4)
e(1) + 2e(2)
0
0
e(1) + e(2) + e(3)
-e(1) - e(2) - e(3)
-e(1) - 2e(2) - 3e(4)
-e(1)
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl"> lincomb←{
fmtco←{
mul←(⍵≠1)/(⍕|⍵),'*'
mul,'e(',(⍕⍺),')'
}
 
co←⊃¨fmtco/¨(⍵≠0)/(⍳⍴,⍵),¨|⍵
sgn←'-+'[1+(×⍵)/×⍵]
lc←(('+'=⊃)↓⊢)∊sgn,¨co
0=⍴lc:'0' ⋄ lc
}</syntaxhighlight>
{{out}}
<pre> ↑lincomb¨(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)
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>
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">linearCombination: function [coeffs][
combo: new []
loop.with:'i coeffs 'x [
case [x]
when? [=0] []
when? [=1] -> 'combo ++ ~"e(|i+1|)"
when? [= neg 1] -> 'combo ++ ~"-e(|i+1|)"
else -> 'combo ++ ~"|x|*e(|i+1|)"
]
join.with: " + " 'combo
replace 'combo {/\+ -/} "- "
(empty? combo)? -> "0" -> combo
]
 
loop @[
[1 2 3]
[0 1 2 3]
[1 0 3 4]
[1 2 0]
[0 0 0]
[0]
[1 1 1]
@[neg 1 neg 1 neg 1]
@[neg 1 neg 2 0 neg 3]
@[neg 1]
] => [print linearCombination &]
</syntaxhighlight>
 
{{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>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
{{trans|Chipmunk Basic}} The Spanish word "cadena" means "string" in English.
<syntaxhighlight lang="basic"> 100 READ UX,UY
110 DIM SCALARS(UX,UY)
120 FOR N = 1 TO UX
130 FOR M = 1 TO UY
140 READ SCALARS(N,M)
150 NEXT M,N
160 DATA10,4
170 DATA1,2,3,0,0,1,2,3
180 DATA1,0,3,4,1,2,0,0
190 DATA0,0,0,0,0,0,0,0
200 DATA1,1,1,0,-1,-1,-1,0
210 DATA-1,-2,0,-3,-1,0,0,0
220 FOR N = 1 TO UX
230 CADENA$ = ""
240 FOR M = 1 TO UY
250 SCALAR = SCALARS(N,M)
260 IF SCALAR THEN CADENA$ = CADENA$ + CHR$ (44 - SGN (SCALAR)) + MID$ ( STR$ ( ABS (SCALAR)) + "*",1,255 * ( ABS (SCALAR) < > 1)) + "E" + STR$ (M)
270 NEXT M
280 IF CADENA$ = "" THEN CADENA$ = "0"
290 IF LEFT$ (CADENA$,1) = "+" THEN CADENA$ = RIGHT$ (CADENA$, LEN (CADENA$) - 1)
300 PRINT CADENA$
310 NEXT N</syntaxhighlight>
==={{header|Chipmunk Basic}}===
{{trans|FreeBASIC}}
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="vbnet">100 dim scalars(10,4)
110 scalars(1,1) = 1 : scalars(1,2) = 2 : scalars(1,3) = 3
120 scalars(2,1) = 0 : scalars(2,2) = 1 : scalars(2,3) = 2 : scalars(2,4) = 3
130 scalars(3,1) = 1 : scalars(3,2) = 0 : scalars(3,3) = 3 : scalars(3,4) = 4
140 scalars(4,1) = 1 : scalars(4,2) = 2 : scalars(4,3) = 0
150 scalars(5,1) = 0 : scalars(5,2) = 0 : scalars(5,3) = 0
160 scalars(6,1) = 0
170 scalars(7,1) = 1 : scalars(7,2) = 1 : scalars(7,3) = 1
180 scalars(8,1) = -1 : scalars(8,2) = -1 : scalars(8,3) = -1
190 scalars(9,1) = -1 : scalars(9,2) = -2 : scalars(9,3) = 0 : scalars(9,4) = -3
200 scalars(10,1) = -1
210 cls
220 for n = 1 to ubound(scalars)
230 cadena$ = ""
240 scalar = 0
250 for m = 1 to ubound(scalars,2)
260 scalar = scalars(n,m)
270 if scalar <> 0 then
280 if scalar = 1 then
290 cadena$ = cadena$+"+e"+str$(m)
300 else
310 if scalar = -1 then
320 cadena$ = cadena$+"-e"+str$(m)
330 else
340 if scalar > 0 then
350 cadena$ = cadena$+chr$(43)+str$(scalar)+"*e"+str$(m)
360 else
370 cadena$ = cadena$+str$(scalar)+"*e"+str$(m)
380 endif
390 endif
400 endif
410 endif
420 next m
430 if cadena$ = "" then cadena$ = "0"
440 if left$(cadena$,1) = "+" then cadena$ = right$(cadena$,len(cadena$)-1)
450 print cadena$
460 next n
470 end</syntaxhighlight>
 
==={{header|FreeBASIC}}===
{{trans|Ring}}
<syntaxhighlight lang="freebasic">Dim scalars(1 To 10, 1 To 4) As Integer => {{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 As Integer = 1 To Ubound(scalars)
Dim As String cadena = ""
Dim As Integer scalar
For m As Integer = 1 To Ubound(scalars,2)
scalar = scalars(n, m)
If scalar <> 0 Then
If scalar = 1 Then
cadena &= "+e" & m
Elseif scalar = -1 Then
cadena &= "-e" & m
Else
If scalar > 0 Then
cadena &= Chr(43) & scalar & "*e" & m
Else
cadena &= scalar & "*e" & m
End If
End If
End If
Next m
If cadena = "" Then cadena = "0"
If Left(cadena, 1) = "+" Then cadena = Right(cadena, Len(cadena)-1)
Print cadena
Next n
Sleep</syntaxhighlight>
{{out}}
<pre>Same as Ring entry.</pre>
 
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|QBasic}}
{{works with|MSX BASIC}}
<syntaxhighlight lang="qbasic">100 DIM SKLS(10, 4)
110 SKLS(1, 1) = 1: SKLS(1, 2) = 2: SKLS(1, 3) = 3
120 SKLS(2, 1) = 0: SKLS(2, 2) = 1: SKLS(2, 3) = 2: SKLS(2, 4) = 3
130 SKLS(3, 1) = 1: SKLS(3, 2) = 0: SKLS(3, 3) = 3: SKLS(3, 4) = 4
140 SKLS(4, 1) = 1: SKLS(4, 2) = 2: SKLS(4, 3) = 0
150 SKLS(5, 1) = 0: SKLS(5, 2) = 0: SKLS(5, 3) = 0
160 SKLS(6, 1) = 0
170 SKLS(7, 1) = 1: SKLS(7, 2) = 1: SKLS(7, 3) = 1
180 SKLS(8, 1) = -1: SKLS(8, 2) = -1: SKLS(8, 3) = -1
190 SKLS(9, 1) = -1: SKLS(9, 2) = -2: SKLS(9, 3) = 0: SKLS(9, 4) = -3
200 SKLS(10, 1) = -1
210 CLS
220 FOR N = 1 TO 10
230 CAD$ = ""
240 SCL = 0
250 FOR M = 1 TO 4
260 SCL = SKLS(N, M)
270 IF SCL <> 0 THEN IF SCL = 1 THEN CAD$ = CAD$ + "+e" + STR$(M) ELSE IF SCL = -1 THEN CAD$ = CAD$ + "-e" + STR$(M) ELSE IF SCL > 0 THEN CAD$ = CAD$ + CHR$(43) + STR$(SCL) + "*e" + STR$(M) ELSE CAD$ = CAD$ + STR$(SCL) + "*e" + STR$(M)
280 NEXT M
290 IF CAD$ = "" THEN CAD$ = "0"
300 IF LEFT$(CAD$, 1) = "+" THEN CAD$ = RIGHT$(CAD$, LEN(CAD$) - 1)
310 PRINT CAD$
320 NEXT N
330 END</syntaxhighlight>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.ht>
 
==={{header|QBasic}}===
{{trans|FreeBASIC}}
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{works with|QB64}}
<syntaxhighlight lang="qbasic">DIM scalars(1 TO 10, 1 TO 4)
scalars(1, 1) = 1: scalars(1, 2) = 2: scalars(1, 3) = 3
scalars(2, 1) = 0: scalars(2, 2) = 1: scalars(2, 3) = 2: scalars(2, 4) = 3
scalars(3, 1) = 1: scalars(3, 2) = 0: scalars(3, 3) = 3: scalars(3, 4) = 4
scalars(4, 1) = 1: scalars(4, 2) = 2: scalars(4, 3) = 0
scalars(5, 1) = 0: scalars(5, 2) = 0: scalars(5, 3) = 0
scalars(6, 1) = 0
scalars(7, 1) = 1: scalars(7, 2) = 1: scalars(7, 3) = 1
scalars(8, 1) = -1: scalars(8, 2) = -1: scalars(8, 3) = -1
scalars(9, 1) = -1: scalars(9, 2) = -2: scalars(9, 3) = 0: scalars(9, 4) = -3
scalars(10, 1) = -1
 
CLS
FOR n = 1 TO UBOUND(scalars)
cadena$ = ""
scalar = 0
FOR m = 1 TO UBOUND(scalars, 2)
scalar = scalars(n, m)
IF scalar <> 0 THEN
IF scalar = 1 THEN
cadena$ = cadena$ + "+e" + STR$(m)
ELSEIF scalar = -1 THEN
cadena$ = cadena$ + "-e" + STR$(m)
ELSE
IF scalar > 0 THEN
cadena$ = cadena$ + CHR$(43) + STR$(scalar) + "*e" + STR$(m)
ELSE
cadena$ = cadena$ + STR$(scalar) + "*e" + STR$(m)
END IF
END IF
END IF
NEXT m
IF cadena$ = "" THEN cadena$ = "0"
IF LEFT$(cadena$, 1) = "+" THEN cadena$ = RIGHT$(cadena$, LEN(cadena$) - 1)
PRINT cadena$
NEXT n
END</syntaxhighlight>
 
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vb">dim scalars(10,4)
scalars(1,1) = 1: scalars(1,2) = 2: scalars(1,3) = 3
scalars(2,1) = 0: scalars(2,2) = 1: scalars(2,3) = 2: scalars(2,4) = 3
scalars(3,1) = 1: scalars(3,2) = 0: scalars(3,3) = 3: scalars(3,4) = 4
scalars(4,1) = 1: scalars(4,2) = 2: scalars(4,3) = 0
scalars(5,1) = 0: scalars(5,2) = 0: scalars(5,3) = 0
scalars(6,1) = 0
scalars(7,1) = 1: scalars(7,2) = 1: scalars(7,3) = 1
scalars(8,1) = -1: scalars(8,2) = -1: scalars(8,3) = -1
scalars(9,1) = -1: scalars(9,2) = -2: scalars(9,3) = 0: scalars(9,4) = -3
scalars(10,1) = -1
 
for n = 1 to arraysize(scalars(),1)
cadena$ = ""
for m = 1 to arraysize(scalars(),2)
scalar = scalars(n, m)
if scalar <> 0 then
if scalar = 1 then
cadena$ = cadena$ + "+e" + str$(m)
else
if scalar = -1 then
cadena$ = cadena$ + "-e" + str$(m)
else
if scalar > 0 then
cadena$ = cadena$ + chr$(43) + str$(scalar) + "*e" + str$(m)
else
cadena$ = cadena$ + str$(scalar) + "*e" + str$(m)
fi
fi
fi
fi
next m
if cadena$ = "" cadena$ = "0"
if left$(cadena$, 1) = "+" cadena$ = right$(cadena$, len(cadena$)-1)
print cadena$
next n
end</syntaxhighlight>
 
=={{header|C}}==
Accepts vector coefficients from the command line, prints usage syntax if invoked with no arguments. This implementation can handle floating point values but displays integer values as integers. All test case results shown with invocation. A multiplication sign is not shown between a coefficient and the unit vector when a vector is written out by hand ( i.e. human readable) and is thus not shown here as well.
<syntaxhighlight lang="c">
<lang C>
 
#include<stdlib.h>
Line 127 ⟶ 547:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 153 ⟶ 573:
Vector for [-1] -> - e1
</pre>
 
=={{header|C sharp|C#}}==
{{trans|D}}
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Text;
 
namespace DisplayLinearCombination {
class Program {
static string LinearCombo(List<int> c) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < c.Count; i++) {
int n = c[i];
if (n < 0) {
if (sb.Length == 0) {
sb.Append('-');
} else {
sb.Append(" - ");
}
} else if (n > 0) {
if (sb.Length != 0) {
sb.Append(" + ");
}
} else {
continue;
}
 
int av = Math.Abs(n);
if (av != 1) {
sb.AppendFormat("{0}*", av);
}
sb.AppendFormat("e({0})", i + 1);
}
if (sb.Length == 0) {
sb.Append('0');
}
return sb.ToString();
}
 
static void Main(string[] args) {
List<List<int>> combos = new List<List<int>>{
new List<int> { 1, 2, 3},
new List<int> { 0, 1, 2, 3},
new List<int> { 1, 0, 3, 4},
new List<int> { 1, 2, 0},
new List<int> { 0, 0, 0},
new List<int> { 0},
new List<int> { 1, 1, 1},
new List<int> { -1, -1, -1},
new List<int> { -1, -2, 0, -3},
new List<int> { -1},
};
 
foreach (List<int> c in combos) {
var arr = "[" + string.Join(", ", c) + "]";
Console.WriteLine("{0,15} -> {1}", arr, LinearCombo(c));
}
}
}
}</syntaxhighlight>
{{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|C++}}==
{{trans|D}}
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <sstream>
Line 236 ⟶ 727:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre> [1, 2, 3] -> e(1) + 2*e(2) + 3*e(3)
Line 249 ⟶ 740:
[-1] -> -e(1)</pre>
 
=={{header|C#Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
{{trans|D}}
<lang csharp>using System;
using System.Collections.Generic;
using System.Text;
 
sub abs(n: int32): (r: uint32) is
namespace DisplayLinearCombination {
classif Programn {< 0
staticthen stringr LinearCombo(List<int>:= c(-n) {as uint32;
else r := n StringBuilder sb = newas StringBuilder()uint32;
end if;
for (int i = 0; i < c.Count; i++) {
end sub;
int n = c[i];
if (n < 0) {
if (sb.Length == 0) {
sb.Append('-');
} else {
sb.Append(" - ");
}
} else if (n > 0) {
if (sb.Length != 0) {
sb.Append(" + ");
}
} else {
continue;
}
 
sub lincomb(scalar: [int32], size: intptr) is
int av = Math.Abs(n);
var first: uint8 if (av !:= 1) {;
var item: uint8 := 1;
sb.AppendFormat("{0}*", av);
}
sb.AppendFormat("e({0})", i + 1);
}
if (sb.Length == 0) {
sb.Append('0');
}
return sb.ToString();
}
 
sub print_sign() is
static void Main(string[] args) {
if first List<List<int>> combos == new1 List<List<int>>{then
if [scalar] < 0 new List<int> {then 1,print("-"); 2,end 3},if;
else
new List<int> { 0, 1, 2, 3},
if [scalar] new List<int> { 1, 0, 3, 4},
newthen List<int>print(" {- 1, 2, 0},");
newelse List<int>print(" {+ 0, 0, 0},");
end new List<int> { 0},if;
end new List<int> { 1, 1, 1},if;
end sub;
new List<int> { -1, -1, -1},
 
new List<int> { -1, -2, 0, -3},
sub print_term() is
new List<int> { -1},
if [scalar] == 0 }then return; end if;
print_sign();
if abs([scalar]) > 1 then
print_i32(abs([scalar]));
print("*");
end if;
print("e(");
print_i8(item);
print(")");
first := 0;
end sub;
 
while size > 0 loop
foreach (List<int> c in combos) {
print_term();
var arr = "[" + string.Join(", ", c) + "]";
scalar := @next scalar;
Console.WriteLine("{0,15} -> {1}", arr, LinearCombo(c));
size := size - }1;
}item := item + 1;
}end loop;
 
}</lang>
if first == 1 then
print("0");
end if;
print_nl();
end sub;
 
var a1: int32[] := {1, 2, 3}; lincomb(&a1[0], @sizeof a1);
var a2: int32[] := {0, 1, 2, 3}; lincomb(&a2[0], @sizeof a2);
var a3: int32[] := {1, 0, 3, 4}; lincomb(&a3[0], @sizeof a3);
var a4: int32[] := {1, 2, 0}; lincomb(&a4[0], @sizeof a4);
var a5: int32[] := {0, 0, 0}; lincomb(&a5[0], @sizeof a5);
var a6: int32[] := {0}; lincomb(&a6[0], @sizeof a6);
var a7: int32[] := {1, 1, 1}; lincomb(&a7[0], @sizeof a7);
var a8: int32[] := {-1, -1, -1}; lincomb(&a8[0], @sizeof a8);
var a9: int32[] := {-1, -2, 0, 3}; lincomb(&a9[0], @sizeof a9);
var a10: int32[] := {-1}; lincomb(&a10[0], @sizeof a10);</syntaxhighlight>
{{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
[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|D}}==
{{trans|Kotlin}}
<langsyntaxhighlight Dlang="d">import std.array;
import std.conv;
import std.format;
Line 374 ⟶ 867:
writefln("%-15s -> %s", arr, linearCombo(c));
}
}</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 3] -> e(1) + 2*e(2) + 3*e(3)
Line 386 ⟶ 879:
[-1, -2, 0, -3] -> -e(1) - 2*e(2) - 3*e(4)
[-1] -> -e(1)</pre>
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc abs(int n) int: if n<0 then -n else n fi corp
 
proc write_term(word index; int scalar; bool first) void:
if first then
if scalar<0 then write("-") fi
else
write(if scalar<0 then " - " else " + " fi)
fi;
if abs(scalar)>1 then
write(abs(scalar), '*')
fi;
write("e(",index,")")
corp
 
proc lincomb([*]int terms) void:
bool first;
word index;
first := true;
 
for index from 0 upto dim(terms,1)-1 do
if terms[index] /= 0 then
write_term(index+1, terms[index], first);
first := false
fi
od;
 
writeln(if first then "0" else "" fi)
corp
 
proc main() void:
[3]int a1 = (1,2,3);
[4]int a2 = (0,1,2,3);
[4]int a3 = (1,0,3,4);
[3]int a4 = (1,2,0);
[3]int a5 = (0,0,0);
[1]int a6 = (0);
[3]int a7 = (1,1,1);
[3]int a8 = (-1,-1,-1);
[4]int a9 = (-1,-2,0,3);
[1]int a10 = (-1);
lincomb(a1); lincomb(a2); lincomb(a3); lincomb(a4);
lincomb(a5); lincomb(a6); lincomb(a7); lincomb(a8);
lincomb(a9); lincomb(a10)
corp</syntaxhighlight>
{{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>
=={{header|EasyLang}}==
{{trans|Ring}}
<syntaxhighlight>
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$ &= "+e" & m
elif scalar = -1
str$ &= "-e" & m
else
if scalar > 0
str$ &= strchar 43 & scalar & "*e" & m
else
str$ = scalar & "*e" & m
.
.
.
.
if str$ = ""
str$ = 0
.
if substr str$ 1 1 = "+"
str$ = substr str$ 2 (len str$ - 1)
.
print str$
.
</syntaxhighlight>
{{out}}
<pre>
e1+2*e2+3*e3
e2+2*e3+3*e4
e1+3*e3+4*e4
e1+2*e2
0
0
e1+e2+e3
-e1-e2-e3
-3*e4
-e1
</pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; build an html string from list of coeffs
 
Line 421 ⟶ 1,015:
(for/string ((linear linears))
(format "%a -> <span style='color:blue'>%a</span> <br>" linear (linear->html linear)))))
</syntaxhighlight>
</lang>
{{out}}
(1 2 3) -> <span style='color:blue'> e<sub>1</sub> + 2*e<sub>2</sub> + 3*e<sub>3</sub> </span> <br>(0 1 2 3) -> <span style='color:blue'> e<sub>2</sub> + 2*e<sub>3</sub> + 3*e<sub>4</sub> </span> <br>(1 0 3 4) -> <span style='color:blue'> e<sub>1</sub> + 3*e<sub>3</sub> + 4*e<sub>4</sub> </span> <br>(1 2 0) -> <span style='color:blue'> e<sub>1</sub> + 2*e<sub>2</sub> </span> <br>(0 0 0) -> <span style='color:blue'>0</span> <br>(0) -> <span style='color:blue'>0</span> <br>(1 1 1) -> <span style='color:blue'> e<sub>1</sub> + e<sub>2</sub> + e<sub>3</sub> </span> <br>(-1 -1 -1) -> <span style='color:blue'>- e<sub>1</sub> - e<sub>2</sub> - e<sub>3</sub> </span> <br>(-1 -2 0 -3) -> <span style='color:blue'>- e<sub>1</sub> - 2*e<sub>2</sub> - 3*e<sub>4</sub> </span> <br>(-1) -> <span style='color:blue'>- e<sub>1</sub> </span> <br>
Line 427 ⟶ 1,021:
=={{header|Elixir}}==
{{works with|Elixir|1.3}}
<langsyntaxhighlight lang="elixir">defmodule Linear_combination do
def display(coeff) do
Enum.with_index(coeff)
Line 458 ⟶ 1,052:
[-1]
]
Enum.each(coeffs, &Linear_combination.display(&1))</langsyntaxhighlight>
 
{{out}}
Line 476 ⟶ 1,070:
=={{header|F_Sharp|F#}}==
===The function===
<langsyntaxhighlight lang="fsharp">
// Display a linear combination. Nigel Galloway: March 28th., 2018
let fN g =
Line 492 ⟶ 1,086:
|_ -> printfn "0"
fN 1 g
</syntaxhighlight>
</lang>
 
===The Task===
<langsyntaxhighlight lang="fsharp">
fN [1;2;3]
</syntaxhighlight>
</lang>
{{out}}
<pre>
e(1)+2e(2)+3e(3)
</pre>
<langsyntaxhighlight lang="fsharp">
fN [0;1;2;3]
</syntaxhighlight>
</lang>
{{out}}
<pre>
e(2)+2e(3)+3e(4)
</pre>
<langsyntaxhighlight lang="fsharp">
fN[1;0;3;4]
</syntaxhighlight>
</lang>
{{out}}
<pre>
e(1)+3e(3)+4e(4)
</pre>
<langsyntaxhighlight lang="fsharp">
fN[1;2;0]
</syntaxhighlight>
</lang>
{{out}}
<pre>
e(1)+2e(2)
</pre>
<langsyntaxhighlight lang="fsharp">
fN[0;0;0]
</syntaxhighlight>
</lang>
{{out}}
<pre>
0
</pre>
<langsyntaxhighlight lang="fsharp">
fN[0]
</syntaxhighlight>
</lang>
{{out}}
<pre>
0
</pre>
<langsyntaxhighlight lang="fsharp">
fN[1;1;1]
</syntaxhighlight>
</lang>
{{out}}
<pre>
e(1)+e(2)+e(3)
</pre>
<langsyntaxhighlight lang="fsharp">
fN[-1;-1;-1]
</syntaxhighlight>
</lang>
{{out}}
<pre>
-e(1)-e(2)-e(3)
</pre>
<langsyntaxhighlight lang="fsharp">
fN[-1;-2;0;-3]
</syntaxhighlight>
</lang>
{{out}}
<pre>
-e(1)-2e(2)-3e(4)
</pre>
<langsyntaxhighlight lang="fsharp">
fN[1]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 567 ⟶ 1,161:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting kernel match math pair-rocket regexp sequences ;
 
MATCH-VARS: ?a ?b ;
Line 585 ⟶ 1,179:
{ { 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 } }
[ dup linear-combo "%-14u -> %s\n" printf ] each</langsyntaxhighlight>
{{out}}
<pre>{ 1 2 3 } -> e(1) + 2*e(2) + 3*e(3)
<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)
Line 597 ⟶ 1,190:
{ -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>
</pre>
 
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 660 ⟶ 1,252:
fmt.Printf("%-15s -> %s\n", t, linearCombo(c))
}
}</langsyntaxhighlight>
 
{{out}}
Line 675 ⟶ 1,267:
[-1] -> -e(1)
</pre>
 
=={{header|Groovy}}==
{{trans|Java}}
<syntaxhighlight lang="groovy">class LinearCombination {
private static String linearCombo(int[] c) {
StringBuilder sb = new StringBuilder()
for (int i = 0; i < c.length; ++i) {
if (c[i] == 0) continue
String op
if (c[i] < 0 && sb.length() == 0) {
op = "-"
} else if (c[i] < 0) {
op = " - "
} else if (c[i] > 0 && sb.length() == 0) {
op = ""
} else {
op = " + "
}
int av = Math.abs(c[i])
String coeff = av == 1 ? "" : "" + av + "*"
sb.append(op).append(coeff).append("e(").append(i + 1).append(')')
}
if (sb.length() == 0) {
return "0"
}
return sb.toString()
}
 
static void main(String[] args) {
int[][] 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 (int[] c : combos) {
printf("%-15s -> %s\n", Arrays.toString(c), linearCombo(c))
}
}
}</syntaxhighlight>
{{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|Haskell}}==
<syntaxhighlight lang="haskell">import Text.Printf (printf)
 
linearForm :: [Int] -> String
linearForm = strip . concat . zipWith term [1..]
where
term :: Int -> Int -> String
term i c = case c of
0 -> mempty
1 -> printf "+e(%d)" i
-1 -> printf "-e(%d)" i
c -> printf "%+d*e(%d)" c i
 
strip str = case str of
'+':s -> s
"" -> "0"
s -> s</syntaxhighlight>
 
Testing
 
<syntaxhighlight lang="haskell">coeffs :: [[Int]]
coeffs = [ [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] ]</syntaxhighlight>
 
<pre>λ> mapM_ (print . linearForm) coeffs
"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>
 
=={{header|J}}==
Line 680 ⟶ 1,374:
Implementation:
 
<langsyntaxhighlight Jlang="j">fourbanger=:3 :0
e=. ('e(',')',~])@":&.> 1+i.#y
firstpos=. 0< {.y-.0
Line 693 ⟶ 1,387:
case. do. pfx,(":|x),'*',y
end.
)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> fourbanger 1 2 3
e(1)+2*e(2)+3*e(3)
fourbanger 0 1 2 3
Line 714 ⟶ 1,408:
-e(1)-2*e(2)-3*e(4)
fourbanger _1
-e(1)</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|Kotlin}}
<langsyntaxhighlight Javalang="java">import java.util.Arrays;
 
public class LinearCombination {
Line 762 ⟶ 1,456:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 3] -> e(1) + 2*e(2) + 3*e(3)
Line 775 ⟶ 1,469:
[-1] -> -e(1)</pre>
 
=={{header|jq}}==
<syntaxhighlight lang="jq">def linearCombo:
reduce to_entries[] as {key: $k,value: $v} ("";
if $v == 0 then .
else
(if $v < 0 and length==0 then "-"
elif $v < 0 then " - "
elif $v > 0 and length==0 then ""
else " + "
end) as $sign
| ($v|fabs) as $av
| (if ($av == 1) then "" else "\($av)*" end) as $coeff
| . + "\($sign)\($coeff)e\($k)"
end)
| if length==0 then "0" else . end ;
 
# The exercise
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
 
[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]
| "\(lpad(15)) => \(linearCombo)"
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="sh"> [1,2,3] => e0 + 2*e1 + 3*e2
[0,1,2,3] => e1 + 2*e2 + 3*e3
[1,0,3,4] => e0 + 3*e2 + 4*e3
[1,2,0] => e0 + 2*e1
[0,0,0] => 0
[0] => 0
[1,1,1] => e0 + e1 + e2
[-1,-1,-1] => -e0 - e1 - e2
[-1,-2,0,-3] => -e0 - 2*e1 - 3*e3
[-1] => -e0</syntaxhighlight>
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># v0.6
 
linearcombination(coef::Array) = join(collect("$c * e($i)" for (i, c) in enumerate(coef) if c != 0), " + ")
Line 783 ⟶ 1,519:
[-1, -1, -1], [-1, -2, 0, -3], [-1]]
@printf("%20s -> %s\n", c, linearcombination(c))
end</langsyntaxhighlight>
 
{{out}}
Line 798 ⟶ 1,534:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun linearCombo(c: IntArray): String {
Line 833 ⟶ 1,569:
println("${c.contentToString().padEnd(15)} -> ${linearCombo(c)}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 848 ⟶ 1,584:
[-1] -> -e(1)
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
 
{def linearcomb
{def linearcomb.r
{lambda {:a :n :i}
{if {= :i :n}
then
else {let { {:e e({+ :i 1})}
{:v {abs {A.get :i :a}}}
{:s {if {< {A.get :i :a} 0} then - else +}}
} {if {= :v 0} then else
{if {= :v 1} then :s :e else :s :v*:e}}}
{linearcomb.r :a :n {+ :i 1}} }}}
{lambda {:a}
{S.replace _LAMB_[^\s]+ by 0 in
{let { {:r {linearcomb.r {A.new :a} {S.length :a} 0}}
} {if {W.equal? {S.first :r} +} then {S.rest :r} else :r} }}}}
-> linearcomb
 
{linearcomb 1 2 3} -> e(1) + 2*e(2) + 3*e(3)
{linearcomb -1 -2 0 -3} -> - e(1) - 2*e(2) - 3*e(4)
{linearcomb 0 1 2 3} -> e(2) + 2*e(3) + 3*e(4)
{linearcomb 1 0 3 4} -> e(1) + 3*e(3) + 4*e(4)
{linearcomb 1 2 0} -> e(1) + 2*e(2)
{linearcomb 0 0 0} -> 0
{linearcomb 0} -> 0
{linearcomb 1 1 1} -> e(1) + e(2) + e(3)
{linearcomb -1 -1 -1} -> - e(1) - e(2) - e(3)
{linearcomb -1} -> - e(1)
 
</syntaxhighlight>
 
=={{header|Lua}}==
{{trans|C#}}
<syntaxhighlight lang="lua">function t2s(t)
local s = "["
for i,v in pairs(t) do
if i > 1 then
s = s .. ", " .. v
else
s = s .. v
end
end
return s .. "]"
end
 
function linearCombo(c)
local sb = ""
for i,n in pairs(c) do
local skip = false
 
if n < 0 then
if sb:len() == 0 then
sb = sb .. "-"
else
sb = sb .. " - "
end
elseif n > 0 then
if sb:len() ~= 0 then
sb = sb .. " + "
end
else
skip = true
end
 
if not skip then
local av = math.abs(n)
if av ~= 1 then
sb = sb .. av .. "*"
end
sb = sb .. "e(" .. i .. ")"
end
end
if sb:len() == 0 then
sb = "0"
end
return sb
end
 
function main()
local 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 i,c in pairs(combos) do
local arr = t2s(c)
print(string.format("%15s -> %s", arr, linearCombo(c)))
end
end
 
main()</syntaxhighlight>
{{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|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">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}};
Column[TraditionalForm[Total[MapIndexed[#1 e[#2[[1]]] &, #]]] & /@ tests]</syntaxhighlight>
{{out}}
<pre>e(1)+2e(2)+3e(3)
e(2)+2e(3)+3e(4)
e(1)+3e(3)+4e(4)
e(1)+2e(2)
0
0
e(1)+e(2)+e(3)
-e(1)-e(2)-e(3)
-e(1)-2e(2)-3e(4)
-e(1)</pre>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Linear;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 916 ⟶ 1,781:
 
ReadChar
END Linear.</langsyntaxhighlight>
 
=={{header|PerlNim}}==
{{trans|Kotlin}}
<lang perl>sub linear_combination {
<syntaxhighlight lang="nim">import strformat
my(@coef) = @$_;
 
my $e;
proc linearCombo(c: openArray[int]): string =
for my $c (1..+@coef) { $e .= "$coef[$c-1]*e($c) + " if $coef[$c-1] }
 
$e =~ s/ \+ $//;
for i, $en =~in s/1\*//g;c:
$eif =~n s/\+== -/-0: /g;continue
$elet //op = if n < 0;:
if result.len == 0: "-" else: " - "
}
else:
if n > 0 and result.len == 0: "" else: " + "
let av = abs(n)
let coeff = if av == 1: "" else: $av & '*'
result &= fmt"{op}{coeff}e({i + 1})"
if result.len == 0:
result = "0"
 
const 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:
echo fmt"{($c)[1..^1]:15} → {linearCombo(c)}"</syntaxhighlight>
 
print linear_combination($_), "\n" 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>[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|OCaml}}==
<syntaxhighlight lang="ocaml">let fmt_linear_comb =
let rec head e = function
| 0 :: t -> head (succ e) t
| 1 :: t -> Printf.sprintf "e(%u)%s" e (tail (succ e) t)
| -1 :: t -> Printf.sprintf "-e(%u)%s" e (tail (succ e) t)
| a :: t -> Printf.sprintf "%d*e(%u)%s" a e (tail (succ e) t)
| _ -> "0"
and tail e = function
| 0 :: t -> tail (succ e) t
| 1 :: t -> Printf.sprintf " + e(%u)%s" e (tail (succ e) t)
| -1 :: t -> Printf.sprintf " - e(%u)%s" e (tail (succ e) t)
| a :: t when a < 0 -> Printf.sprintf " - %u*e(%u)%s" (-a) e (tail (succ e) t)
| a :: t -> Printf.sprintf " + %u*e(%u)%s" a e (tail (succ e) t)
| _ -> ""
in
head 1
 
let () =
List.iter (fun v -> print_endline (fmt_linear_comb v)) [
[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]]</syntaxhighlight>
{{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)
Line 941 ⟶ 1,868:
-e(1) - e(2) - e(3)
-e(1) - 2*e(2) - 3*e(4)
-e(1)</pre>
</pre>
 
=={{header|Perl 6}}==
<syntaxhighlight lang="perl">use strict;
<lang perl6>sub linear-combination(@coeff) {
use warnings;
(@coeff Z=> map { "e($_)" }, 1 .. *)
use feature 'say';
.grep(+*.key)
 
.map({ .key ~ '*' ~ .value })
sub linear_combination {
.join(' + ')
.substmy('+@coef) -',= '- ', :g)@$_;
.subst(/<|w>1\*/,my $e = '', :g);
for my $c (1..+@coef) { $e .= "$coef[$c-1]*e($c) + " if $coef[$c-1] }
|| '0'
$e =~ s/ \+ $//;
$e =~ s/1\*//g;
$e =~ s/\+ -/- /g;
$e or 0;
}
 
say linear-combinationlinear_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 ]</syntaxhighlight>
[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)
Line 980 ⟶ 1,902:
=={{header|Phix}}==
{{trans|Tcl}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function linear_combination(sequence f)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
string res = ""
<span style="color: #008080;">function</span> <span style="color: #000000;">linear_combination</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">)</span>
for e=1 to length(f) do
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
integer fe = f[e]
<span style="color: #008080;">for</span> <span style="color: #000000;">e</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if fe!=0 then
<span style="color: #004080;">integer</span> <span style="color: #000000;">fe</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">[</span><span style="color: #000000;">e</span><span style="color: #0000FF;">]</span>
if fe=1 then
<span style="color: #008080;">if</span> <span style="color: #000000;">fe</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
if length(res) then res &= "+" end if
<span style="color: #008080;">if</span> <span style="color: #000000;">fe</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
elsif fe=-1 then
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">"+"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
res &= "-"
<span style="color: #008080;">elsif</span> <span style="color: #000000;">fe</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
elsif fe>0 and length(res) then
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">"-"</span>
res &= sprintf("+%d*",fe)
<span style="color: #008080;">elsif</span> <span style="color: #000000;">fe</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
else
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"+%d*"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fe</span><span style="color: #0000FF;">)</span>
res &= sprintf("%d*",fe)
end if<span style="color: #008080;">else</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d*"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fe</span><span style="color: #0000FF;">)</span>
res &= sprintf("e(%d)",e)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"e(%d)"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if res="" then res = "0" end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return res
<span style="color: #008080;">if</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">=</span><span style="color: #008000;">""</span> <span style="color: #008080;">then</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"0"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
constant tests = {{1,2,3},
{0,1,2,3},
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},</span>
{1,0,3,4},
<span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},</span>
{1,2,0},
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">},</span>
{0,0,0},
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
{0},
<span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
{1,1,1},
<span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
{-1,-1,-1},
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
{-1,-2,0,-3},
<span style="color: #0000FF;">{-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
{-1}}
<span style="color: #0000FF;">{-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},</span>
for i=1 to length(tests) do
<span style="color: #0000FF;">{-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}}</span>
sequence ti = tests[i]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
printf(1,"%12s -> %s\n",{sprint(ti), linear_combination(ti)})
<span style="color: #004080;">sequence</span> <span style="color: #000000;">ti</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
end for</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%12s -&gt; %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">sprint</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">linear_combination</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,027 ⟶ 1,952:
{-1,-2,0,-3} -> -e(1)-2*e(2)-3*e(4)
{-1} -> -e(1)
</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="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</syntaxhighlight>
{{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}}==
<langsyntaxhighlight lang="python">
def linear(x):
return ' + '.join(['{}e({})'.format('-' if v == -1 else '' if v == 1 else str(v) + '*', i + 1)
Line 1,037 ⟶ 2,083:
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]]))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,053 ⟶ 2,099:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket/base
(require racket/match racket/string)
 
Line 1,086 ⟶ 2,132:
(-1 -2 0 -3)
(-1)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,098 ⟶ 2,144:
-e(1)-e(2)-e(3)
-e(1)-2*e(2)-3*e(4)
-e(1)</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>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 ]
;</syntaxhighlight>
{{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>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program displays a finite liner combination in an infinite vector basis. */
@.= .; @.1 = ' 1, 2, 3 @.1 = ' 1, 2,/*define a 3specific test case for 'build*/
@.2 = ' 0, 1, 2, 3 ' @.2 =/* '" 0, " 1, 2, 3" ' " " " " */
@.3 = ' 1, 0, 3, 4 ' @.3 =/* '" 1, " 0, 3, 4" ' " " " " */
@.4 = ' 1, 2, 0 @.4' = /* ' 1," 2, " 0 " ' " " " " */
@.5 = ' 0, 0, 0 @.5' = /* ' 0," 0, " 0 " ' " " " " */
@.6 = 0 @.6 = 0 /* " " " " " " " */
@.7 = ' 1, 1, 1 @.7' = /* ' 1," 1, " 1 " ' " " " " */
@.8 = ' -1, -1, -1 ' @.8 /* = " ' -1, -1," -1 " ' " " " " */
@.9 = ' -1, -2, 0, -3 ' /* @.9 =" '" -1, -2, 0, -3" ' " " " " */
@.10 = -1 @.10 = -1 /* " " " " " " " */
do j=1 while @.j\==.; n= 0 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= '+- ' ; if #<0 then s= "- " /*define the sign: plus(+) or minus (-). */
n= n + 1; if n==1 thenelse s= strip(s)'+ ' /*if the 1st element" " " used, remove plus (+). */
if a\=n= n + 1 then s= s || a'*' /*ifbump multiplierthe isnumber unity,of thenelements ignorein #vector*/
$ if n==1 $ then s'e= strip('k"s)" /*if the 1st element used, remove /*construct a liner combination elementblank*/
if a\==1 then s= s || a'*' /*if multiplier is unity, then ignore #*/
end /*k*/
$= $ 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. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 1,142 ⟶ 2,225:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Display a linear combination
 
Line 1,172 ⟶ 2,255:
see str + nl
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,186 ⟶ 2,269:
-e1
</pre>
 
=={{header|RPL}}==
RPL can handle both stack-based program flows and algebraic expressions, which is quite useful for tasks such as this one.
{{works with|Halcyon Calc|4.2.7}}
===Straightforward approach===
This version has the disadvantage of sometimes interchanging some terms when simplifying the expression by the COLCT function.
≪ → scalars
≪ '0' 1 scalars SIZE FOR j
scalars j GET
"e" j →STR + STR→ * +
NEXT
COLCT COLCT
≫ ≫
'COMB→' STO
===Full-compliant version===
The constant π is here simply used to facilitate the construction of the algebraic expression; it is then eliminated during the conversion into a string.
≪ → scalars
≪ "" 1 scalars SIZE FOR j
'π' scalars j GET "e" j →STR + STR→ * + →STR
OVER SIZE NOT OVER 3 3 SUB "+" AND 4 3 IFTE
OVER SIZE 1 - SUB +
NEXT
IF DUP "" == THEN DROP "0" END
'COMB→' STO
 
≪ { { 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 } }
{ } 1 3 PICK SIZE FOR j
OVER j GET COMB→ +
NEXT
SWAP DROP
≫ EVAL
{{out}}
<pre>
1: { "e1+2*e2+3*e3" "e2+2*e3+3*e4" "e1+3*e3+4*e4" "e1+2*e2" "0" "0" "e1+e2+e3" "-e1-e2-e3" "-e1-2*e2-3*e4" "-e1" }
</pre>
 
=={{header|Ruby}}==
{{trans|D}}
<syntaxhighlight lang="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()</syntaxhighlight>
{{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|Rust}}==
<syntaxhighlight lang="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));
}
</syntaxhighlight>
{{out}}
<pre>
1 2 3 -> e(1) + 2*e(2) + 3*e(3)
</pre>
 
=={{header|Scala}}==
<syntaxhighlight lang="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")
}
}</syntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Tcl}}
<langsyntaxhighlight lang="ruby">func linear_combination(coeffs) {
var res = ""
for e,f in (coeffs.kv) {
Line 1,226 ⟶ 2,539:
tests.each { |t|
printf("%10s -> %-10s\n", t.join(' '), linear_combination(t))
}</langsyntaxhighlight>
{{out}}
<pre> 1 2 3 -> e(1)+2*e(2)+3*e(3)
<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)
Line 1,238 ⟶ 2,550:
-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>
</pre>
 
=={{header|Tcl}}==
This solution strives for legibility rather than golf.
 
<langsyntaxhighlight Tcllang="tcl">proc lincom {factors} {
set exp 0
set res ""
Line 1,279 ⟶ 2,590:
} {
puts [format "%10s -> %-10s" $test [lincom $test]]
}</langsyntaxhighlight>
 
{{out}}
Line 1,292 ⟶ 2,603:
-1 -2 0 -3 -> -e(1)-2*e(2)-3*e(4)
-1 -> -e(1) </pre>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">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</syntaxhighlight>
{{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|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import strings
 
fn linear_combo(c []int) string {
mut sb := strings.new_builder(128)
for i, n in c {
if n == 0 {
continue
}
mut op := ''
match true {
n < 0 && sb.len == 0 {
op = "-"
}
n < 0{
op = " - "
}
n > 0 && sb.len == 0 {
op = ""
}
else{
op = " + "
}
}
mut av := n
if av < 0 {
av = -av
}
mut coeff := "$av*"
if av == 1 {
coeff = ""
}
sb.write_string("$op${coeff}e(${i+1})")
}
if sb.len == 0 {
return "0"
} else {
return sb.str()
}
}
fn 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 {
println("${c:-15} -> ${linear_combo(c)}")
}
}</syntaxhighlight>
 
{{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|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
 
var linearCombo = Fn.new { |c|
var sb = ""
var i = 0
for (n in c) {
if (n != 0) {
var op = (n < 0 && sb == "") ? "-" :
(n < 0) ? " - " :
(n > 0 && sb == "") ? "" : " + "
var av = n.abs
var coeff = (av == 1) ? "" : "%(av)*"
sb = sb + "%(op)%(coeff)e(%(i + 1))"
}
i = i + 1
}
return (sb == "") ? "0" : sb
}
 
var 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) {
Fmt.print("$-15s -> $s", c.toString, linearCombo.call(c))
}</syntaxhighlight>
 
{{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|zkl}}==
{{trans|Perl 6Raku}}
<langsyntaxhighlight lang="zkl">fcn linearCombination(coeffs){
[1..].zipWith(fcn(n,c){ if(c==0) "" else "%s*e(%s)".fmt(c,n) },coeffs)
.filter().concat("+").replace("+-","-").replace("1*","")
or 0
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">T(T(1,2,3),T(0,1,2,3),T(1,0,3,4),T(1,2,0),T(0,0,0),T(0),T(1,1,1),T(-1,-1,-1),
T(-1,-2,0,-3),T(-1),T)
.pump(Console.println,linearCombination);</langsyntaxhighlight>
{{out}}
<pre>
413

edits