How to resolve the algorithm Display a linear combination step by step in the Lua programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Display a linear combination step by step in the Lua 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 Lua programming language
Source code in the lua programming language
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()
You may also check:How to resolve the algorithm Leonardo numbers step by step in the Scala programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the Batch File programming language
You may also check:How to resolve the algorithm Fraction reduction step by step in the Raku programming language
You may also check:How to resolve the algorithm FizzBuzz step by step in the Ursa programming language
You may also check:How to resolve the algorithm Greatest element of a list step by step in the Octave programming language