Inside a procedure or user-defined function, If doesn't do as it should. Long ago, I found out that I should use === instead of == in a procedure in order to make the decision appear at real time. But what should I do with If? Thanks a lot.
=== edit ====
This is my program to generate sequences of "1", "2" and "3" with no equal consecutive pairs. "If" doesn't seem to work properly, or I really miss something. (allow at most 3 copies of each number.)
add[seq_, n1_, n2_, n3_] :=
Do[
Block[{nn1, nn2, nn3, vn, vv = Sort[{seq[[i]], seq[[i + 1]]}]},
Print["between ", vv];
If[vv == {2, 3}, If[n1 >= 3, Goto[next], nn1 = n1 + 1; vn = 1],
If[vv == {1, 3}, If[n2 >= 3, Goto[next], nn2 = n2 + 1; vn = 2],
If[vv == {1, 2}, If[n3 >= 3, Goto[next], nn3 = n3 + 1; vn = 3],
Print["error"]]]];
Print["Insert ", vn, " to ", seq];
add[Insert[seq, vn, i + 1], nn1, nn2, nn3];
Label[next]], {i, Length[seq] - 1}]
add[{1, 2, 3}, 1, 1, 1]
At first step, it inserts 3 but the next step it couldn't say vn=2
between {1,2} Insert 3 to {1,2,3} between {1,3} Insert vn to {1,3,2,3}
Strange! Replace "==" by "===" make it better but still error.
(ps. At first, "Switch" didn't work)
==== edit to be better but same error =====
Replace Goto&Label by Continue and sequential If by Switch.
add[seq_, n1_, n2_, n3_] :=
Do[
Block[{nn1, nn2, nn3, vn, vv = Sort[{seq[[i]], seq[[i + 1]]}]},
Print["Between ", vv];
Switch[vv,
{2, 3}, If[n1 >= 3, Continue[], nn1 = n1 + 1; vn = 1],
{1, 3}, If[n2 >= 3, Continue[], nn2 = n2 + 1; vn = 2],
{1, 2}, If[n3 >= 3, Continue[], nn3 = n3 + 1; vn = 3],
_, Print["error"]];
Print["insert ", vn, " to ", seq];
add[Insert[seq, vn, i + 1], nn1, nn2, nn3]]
, {i, Length[seq] - 1}]
add[{1, 2, 3}, 1, 1, 1]
I expect the following output.
Between {1,2}
insert 3 to {1,2,3}
Between {1,3}
insert 2 to {1,3,2,3}
Ifshould behave the same way inside a Module or outside. If you find thatIfdoes not do so, this would qualify as a huge bug and should be submitted to supprt@wolfram.com for more investigation. But again, you should provide an example of what you mean as this could be a user error. – Nasser Mar 3 at 1:24lst = {1, 2, 3}; Permutations[#] & /@ Subsets[lst]This gives !Mathematica graphics if this is not what you want, then may be give small example of input/output needed. (ps. not good idea to use procedural coding in M, no goto, etc...) – Nasser Mar 3 at 5:00f[n_] := RandomChoice[{1, 2, 3}, n] //. {a___, x_, x_, b___} -> {a, x, b}– belisarius Mar 3 at 7:12Switchyou give at most one ofnn1,nn2, ornn3a value, but then you recursively calladdusing these undefined values, so your procedure breaks down. The first instance of this with your input is after you have inserted3to{1, 2, 3}: onlynn3is set at this point, and you have not handled the subsequentadd[{1,3,2,3}, nn1, nn2, 2]correctly. Voting to close as Too Localized. – Oleksandr R. Mar 3 at 13:58