I make a "genetic calculator", it must "cross" each letter of each element gens[[],[]]
with another element.
There is a code that creates code that then executes:
for (var u in gens) { var estr = ""; for (var i = 0; i < gens[u].length; i++) { var na = gens[u][i].charAt(0).toUpperCase(); estr += 'for(var ' + na + '=0;' + na + '<=1;' + na + '++){\n'; } estr += 'var res=cross(['; for (var i = 0; i < gens[u].length; i++) { var na = gens[u][i].charAt(0).toUpperCase(); estr += 'gens[' + u + '][' + i + '].charAt(' + na + '),'; } estr = estr.substring(0, estr.length - 1); estr += ']);\nif(!test(gomets[' + u + '],res,true)){gomets[' + u + '].push(res);}\n'; for (var i = 0; i < gens[u].length; i++) { estr += '}\n'; } alert(estr); //eval(estr); }
The bottom line is that he with gens=[['AA','Bb'],['aa','BB']];
creates the code first:
for (var A = 0; A <= 1; A++) { for (var B = 0; B <= 1; B++) { var res = cross([gens[0][0].charAt(A), gens[0][1].charAt(B)]); if (!test(gomets[0], res, true)) { gomets[0].push(res); } } }
And then
for (var A = 0; A <= 1; A++) { for (var B = 0; B <= 1; B++) { var res = cross([gens[1][0].charAt(A), gens[1][1].charAt(B)]); if (!test(gomets[1], res, true)) { gomets[1].push(res); } } }
The point is that the code creates as many nested loops as there are elements in gens[u]
, for example, gens[0]
.
Each cycle should count from 0 to 1 (so the length of the string is "AA", "bb" and so on 2 characters) and record the result in a variable whose name corresponds to gens[u].[Π½ΠΎΠΌΠ΅Ρ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠ°/ΡΠΈΠΊΠ»Π°].charAt(0);
in the body of the nested loop, the function is executed, the array with the elements gens[u][0].charAt(ΠΈΠΌΡ ΡΡΡΡΡΠΈΠΊΠ° ΡΠΈΠΊΠ»Π°)
must fall into its parameters, since the index ranges from 0 to 1, then the loop takes each letter. I thought about the algorithm, I couldnβt think of anything better, because the number of elements in gens[u]
fluctuates and all letters of all elements need to be passed functions in turn, and for this you need as many cycles as there are elements in gens[u]
.
Actually the question is: can this be organized without eval'a
?
ps If something is not clear in the question, ask, I will explain.
UPD: for gens=[['AA','Bb','Cc'],['aa','BB','Cc']];
generated code:
for (var A = 0; A <= 1; A++) { for (var B = 0; B <= 1; B++) { for (var C = 0; C <= 1; C++) { var res = cross([gens[0][0].charAt(A), gens[0][1].charAt(B), gens[0][2].charAt(C)]); if (!test(gomets[0], res, true)) { gomets[0].push(res); } } } }