# A faster way to make a loop that takes as input previous iteration values

As mention in other answers, I know that there are faster ways to construct loop in Mathematica, using Fold or ListTable. In my code, all the variables change in every iteration of the loop. Coming from an older school of programing languages, it is hard to convert my code into one more efficient. I would really appreciate some insight here, hoping that my case is representative of a common problem for new users in Mathematica. I paste here a representative self consistent piece of a much larger code.

My code propose a Boolean expression a. Then look for the truth table of this expression b, and the amount of variables in it mdl. Then look for the position of b in the array concepts, this is pos. Then check for the $current$ value in position pos in array minimalong, this is min. Finally, if mdl is smaller than min, aggregate the expression a to winnerx in position pos and update minimalong.

concepts = Tuples[{0, 1}, 16];
minimalong = ConstantArray[1000, Length[concepts]];
winnerx = ConstantArray[0, Length[concepts]];
letters = List["p", "q", "y", "s", "!p", "!q", "!y", "!s"];
combx1 = Subsets[letters, {2}]

For[i=1,i<(Length[combx1]+1),i++,
a=And[Part[Part[combx1,i],1],Part[Part[combx1,i],2]];
b=Boole[BooleanTable[a,{p,q,y,s}]];
mdl=  1 * (StringCount[ToString[a],{"p","q","y","s"}] );
pos=Sum[Part[b,h]*(2^(16-h)),{h,16}]+1;
min=Part[minimalong,pos];
If[mdl<min,Part[minimalong,pos]=mdl;Part[winnerx,pos]= a];
];


EDIT

I tried this, but it is in fact taking MORE time that the for loop..

ands[wo_, i_] := (Module[{a, b, min, mdl, pos},
a = And[Part[Part[combx1, i], 1], Part[Part[combx1, i], 2]];
b = Boole[BooleanTable[a, {p, q, y, s}]];
pos = Sum[Part[b, h]*(2^(16 - h)), {h, 16}] + 1;
min = Part[minimalong, pos];
mdl  = var * (StringCount[ToString[a], {"p", "q", "y", "s"}] );
If[mdl < min, Part[winnerx, pos] = a];
If[mdl < min, Part[minimalong, pos] = mdl];
winnerx]);

lon = ConstantArray[0, Length[concepts]];
Fold[ands, lon, Range[Length[combx1]]];


Any Help?

• Could you explain what do exactly your code – cyrille.piatecki Sep 24 '16 at 15:54
• I edited the question :) – user41667 Sep 24 '16 at 16:02
• What is var ? – corey979 Sep 24 '16 at 18:03
• Sorry, var is 1 – user41667 Sep 24 '16 at 18:42