So guys, I have a problem developing an algorithm that takes a finite list of real numbers that are sorted in increasing order and a real number N, and
-If there exists two indices i
and j
, such that 1 <= i <j <= numel(L)
and L(i)+L(j)=N
, then then algorithm returns the pair sumToN = [L(i) L(j)]
; in the case that multiple pairs of indices exist with the required property, the function returns one of the valid pairs,
-If the equality L(i)+L(j)=N
is not satisfied for any indices i
and j
, such that 1 <= i < j <= numel(L)
, the function return the empty pair Ret
.
L = [1 2 2 3];
N = 3;
sumToN = 0;
for i=1:numel(L);
for j=1:numel(L);
if i<j;
if L(i) + L(j) == N;
sumToN = [L(i) L(j)];
display(sumToN);
else
Ret = [0 0];
display(Ret);
end
end
end
end
Now, in this code that I've written in Matlab R2014, independently of the if conditions, I get a strange output: the command window displays two times the vector sumToN
and four times the vector Ret
. Any suggestion about how to solve this problem? I think that the algorithm is correct...