How to resolve the algorithm Display a linear combination step by step in the ALGOL 68 programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Display a linear combination step by step in the ALGOL 68 programming language
Table of Contents
Problem Statement
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: where
α
i
k
≠ 0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
Show here output for the following lists of scalars:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Display a linear combination step by step in the ALGOL 68 programming language
Source code in the algol programming language
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
You may also check:How to resolve the algorithm Formatted numeric output step by step in the Free Pascal programming language
You may also check:How to resolve the algorithm Elementary cellular automaton step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Zeckendorf number representation step by step in the Factor programming language
You may also check:How to resolve the algorithm Hofstadter Q sequence step by step in the Ruby programming language
You may also check:How to resolve the algorithm Partial function application step by step in the Julia programming language