1
$\begingroup$

I am writing a simple if clause, but keep getting wrong answers, so I ended up writing 2 almost the same if clauses, one giving back correct answer, and the other giving back wrong answer. Can't figure out the problem.

1.(giving wrong answer)

InsertIndex2[x_, list_] := 
   Module[{length, compareResult, middleIndex, newList, newResult, 
    whichResult}, 
    length = Length[list];
   middleIndex = Floor[(length + 1)/2];
   #Print[middleIndex];
   Print["length=", length];
  If [length == 0,  1, 2]]

Input:

 c = {}
 d = InsertIndex2[1, c]

Output:

length = 0
0 
  1. (giving correct answer)

    f = Module[{a}, a = 0; If[a == 0, 1, 2]]

input:

e=f

output:

1
$\endgroup$
  • 2
    $\begingroup$ you have a problem with the semicolon after middleIndex. it does not look like a semicolon. $\endgroup$ – Ali Hashmi Apr 3 '17 at 15:47
  • 1
    $\begingroup$ Also, what is #Print intended to be? $\endgroup$ – Bob Hanlon Apr 3 '17 at 15:54
  • $\begingroup$ @bob a comment, apparently. $\endgroup$ – LLlAMnYP Apr 3 '17 at 17:25
1
$\begingroup$

If I remove the syntax errors and irrelevancies from your code

InsertIndex2[x_, list_] :=
  Module[{length, middleIndex},
    length = Length[list];
    middleIndex = Floor[(length + 1)/2];
    Print[middleIndex];
    Print["length=", length];
    If[length == 0, 1, 2]]

then

InsertIndex2[1, {}]

gives

results

which is exactly what you wanted.

| improve this answer | |
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.