I wrote a program that is supposed to take a list (of arbitrary length) of pairs of the digits of binary numbers (e.g. list = {{{1,1,0,0},{0,0,1,1}},{{1,0,1,0},{0,1,0,1}}}
and swap the elements to the left of a random position between the pairs via RandomInteger
. For example, the program is supposed to take the first element of list
, {{1,1,0,0},{0,0,1,1}}
, produce a random integer between 1 and the length of the first or second sub-element in the list (let's say this random integer is 3) and swap the elements of each list of binary digits to the left of the third position to produce {{0,0,1,1},{1,1,0,0}}
. The program then is supposed to continue with the second element in list
, {{1,0,1,0},{0,1,0,1}}
, produce another (potentially same) random number which will serve as the position where the elements to the left of each pair gets swapped.
From there, the program should finish off by producing the pairs with swapped elements in a list (i.e. {{{0,0,1,1},{1,1,0,0}}, ...}
. When I ran it, it initially produced only the first pair of swapped binary digits. Then, after several attempts at fixing it, it wouldn't evaluate anything or produce Null
. Needless to say, I'm stuck. Here's the program I wrote. I must admit that I only recently took up Mathematica programming as a hobby and I am not very experienced, so my program is likely not as streamlined as it could be. I have made attempts at learning of different Mathematica functions to make the code better, but thus far, this is what I've come up with. I don't mean to waste anyone's time due to my naiveté.
BinarySwitch[a_] := Module[{},
SetOfNewBinary = {};
For[x = 1, x <= Length[a], x++,
NewBinarySet = {};
NewBinary1 = {};
NewBinary2 = {};
pos1 = a[[x]][[1]];
pos2 = a[[x]][[2]];
ri = RandomInteger[{1, Length[pos1] - 1}];
Print[ri];
For[y = 1, y < ri, y++,
rp1 = ReplacePart[pos1, i -> pos2[[y]]];
rp2 = ReplacePart[pos2, i -> pos1[[y]]];
position1 = rp1[[y]];
position2 = rp2[[y]];
NewBinary1 = Append[NewBinary1, position1];
NewBinary2 = Append[NewBinary2, position2];
];
For[z = ri, z <= Length[pos1], z++,
NewBinary1 = Append[NewBinary1, pos1[[z]]];
NewBinary2 = Append[NewBinary2, pos2[[z]]];
];
NewBinarySet = Append[NewBinarySet, NewBinary1];
NewBinarySet = Append[NewBinarySet, NewBinary2];
Print[NewBinarySet];
];
SetOfNewBinary = Append[SetOfNewBinary, NewBinarySet];
Print[SetOfNewBinary];
];
Many thanks in advance.
{a,b,c,d}
and{e,f,g,h}
.RandomInteger
will produce an integer between 1 and the length of either of those two lists. This number will pertain to a position. Let's say that it produces 4. Then it will take the elements to the left ofd
in{a,b,c,d}
and the elements to the left ofh
in{e,f,g,h}
and put them at the front of the other list to produce{e,f,g,d}
and{a,b,c,h}
in that order. Now, I want to be able to put in a list of pairs and have the program do this for every pair in the list. $\endgroup$