Provided a 1D array of integers, find all combinations of 3 values from this set such that: a+b+c=0
古いコメントを表示
Ok, I can't figure out where I what I am doing wrong in my code. I have tried debugging but without knowing what they are asking me to fix it's kind of hard to just go from that. Any advice on how to correct this would be greatly appreciated.
function [S] = ThreeSum(i, j, k)
for i=0;
i < S;
for j = i + 1;
j < S;
for k = j + 1;
k < S;
if a(i) + a(j) + a(k) == 0;
end
end
end
end
end
採用された回答
その他の回答 (2 件)
John D'Errico
2012 年 2 月 22 日
What exactly is the purpose of statements like this:
i < s;
What do you think they do?
Next, what do you think MATLAB does when it sees a loop like this:
for i = 0;
end
How many times does it execute that loop?
I think you need to look at the help for for. Read the documentation. Look at the examples. Don't just write code as you might imagine it will work, perhaps what might work in some other language, because your imagination will probably be wrong.
And, oh, by the way, matlab indexing starts at 1, NOT at 0. You cannot try to find the vector element a(0) and not expect to get an error.
Finally, some think that it is poor programming practice to use i and j as loop variables, as i and j are already defined in MATLAB as the imaginary unit for complex numbers, sqrt(-1). Personally, I like to use i and j for that purpose myself, and I tend not to work in the complex domain, so it it not an issue for me.
Walter Roberson
2012 年 2 月 22 日
Your code uses "S" and "a" without defining them.
Your line
i < S;
will compare i to the non-existent S, causing an error. But if S had been defined, whatever the result of the comparison was, it would just throw away the result because of the semi-colon at the end of the line.
Your line
for i=0;
runs a loop with "i" set only to the value 0, and no other value.
I would suggest you need to review the syntax for MATLAB "for" loops: it is not the same as the syntax for C.
1 件のコメント
Jan
2012 年 2 月 22 日
Let me mention, that "for i=0; i<S; <LoopBody>" is even not valid C.
カテゴリ
ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!