0

I have a matrix A with numbers A[1],A[2]...,A[n] and a matrix B (nxn) that i want to save all the possible sums. A simple algorithm that computes the B matrix is:

for i=1,2,...,n
    for j=i+1,i+2,...,n
        add the number from A[i] to A[j]
        save the results to B[i][j]
    endfor
endfor

I want to change this algorithm to be better(to have better runtime). I changed the first for i=1,2,...n to i=1 and i increase this in the end of the second for. I also think that i made more calculates that is needed.To compute B[1][5] i must compute A[1][2]+A[1][3]+A[1][4] but this sum is also in B[1][4]. So i can also compute this with less computation (B[1][4]+A[1][5]). Can anyone help me improving this algorithm?

Lee Yaan
  • 547
  • 7
  • 26
  • Is `A` a vector or a matrix then? Can you write down in plain English or an equation what the definition of `B[i][j]` is? – biziclop Mar 23 '16 at 11:57
  • 1
    Your second solution is efficient and simple as it gets, it's just a small number of arithmetic operations for each value needed in the output. It runs in O(n^2), which is the size of the output, you will not get better than that in terms of asymptotic complexity. – amit Mar 23 '16 at 11:59
  • B[1][5] does not contain A[1][2]+A[1][3]+A[1][4]. It contains A[1][4]+A[1][5]. It's difficult to show this in a comment. Here's a small R script for the first row with the output: [code]local ({ A=1:5; B=rep(NA,4); for (j in 2:5) { B[j] = A[j-1] + A[j] }; rbind(A=A,B=B) })[/code][code]A 1 2 3 4 5[/code][code]B NA 3 5 7 9[/code] – DAV Mar 23 '16 at 12:14

1 Answers1

0
for i=1,2,...,n
    for j=i,i+1,i+2,...,n
        if i == j then B[i][j] = A[j]
        else B[i][j] = B[i][j - 1] + A[j]
    endfor
endfor
Sorin
  • 11,863
  • 22
  • 26