Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --task? create an algorithm capaple of solving triangular linear equation sets.
- --arguments are n(size of the matrix), matrix(the matrix containing the values) and results(the results of each line of the matrix)
- --for example, the linear equation set{x+y+z=-1, y+z=2,z=3} would be represented as 3,{{1,1,1},{0,1,1},{0,0,1}},{1,2,3} and the solution {-1,-1,3}
- function solve(n,matrix,results)
- --n is pretty much redundant and can be replaced with #matrix, but the assignment nazis still require it
- --you can probably uncomment this and maybe remove n from arguments.
- --n=#matrix
- local vars={}
- --initializing vars
- for i=1,n do
- vars[i]=0
- end
- --get
- if matrix[#matrix][1]==0 then
- --normal triangular matrix
- for i=1,n do
- --removing through substitution already known values
- for j=1,n do
- results[i]=(results[i]-(vars[j]*matrix[i][j]))
- end
- vars[i]=(results[i]/matrix[i][j])
- end
- else
- --inverted triangular matrix
- for i=n,1,-1 do
- --i could do this by passing different args for the for loop, but i'm too lazy for that atm
- for j=1,n do
- results[i]=(results[i]-(vars[j]*matrix[i][j]))
- end
- vars[i]=(results[i]/matrix[i][j])
- end
- end
- return vars
- end
- --example test case
- local a,b,c=3,{{1,1,1},{0,1,1},{0,0,1}},{1,2,3}
- print(unpack(solve(a,b,c)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement