I am trying to make pairs of letters from two different input strings. This is my code so far:
clear all
signal = input('Please enter text to be scrambled:\n ', 's');
signal = signal(randperm(numel(signal)))
noise = input ('Please enter text of the same length:\n ','s');
noise = noise(randperm(numel(noise)))
This is some kind of a game I am trying to develop, and I was investigating the math involved. Imagine the game of Reversi, where one has to flip and move coins around in order to "match colors". I was thinking it would be great if we tried to "match letters" instead, for the purpose of recreating the original message, in this case, the Signal.
- Let's say, you have 100 coins, and you place them randomly on a table (either head or tail, it doesn't matter).
- Then, you write a message on the coins, one letter for each coin. This is the Signal.
- Then, you flip all the coins to the other side, and move them around a bit.
- Then, you insert "the noise" following the same procedure.
- We now have 100 coins, but 200 letters in the game, one letter for each side of the coins. If we flip and move coins around in order to insert the "noise", we don't know what's on the other side of each coin.
- The purpose of the game is to flip and move coins around until the original message (the Signal) is recreated. This is some kind of an encrypting technique that no computer algorithm should be able to crack.
So, please help me understand how to make pairs of letters from the two input strings.
CodePudding user response:
There are lots of ways you could do this, but here's one. For two character vectors as input, the output is a cell array of two-letter character vectors in which each pair contains one letter from each input, no letter is used twice, and the pairs are reversed at random.
% 'signal' and 'noise' are two character vectors of equal length
numChars = strlength(signal);
% randomly permute signal and noise
left = signal(randperm(numChars));
right = noise(randperm(numChars));
% make a cell array of 2-letter pairs
pairs = arrayfun(@strcat, left, right, 'UniformOutput', false);
% select half of the pairs at random and reverse them
sel = logical(randi([0, 1], 1, numChars));
pairs(sel) = cellfun(@fliplr, pairs(sel), 'UniformOutput', false);
Now pairs{1}
will contain the first pair, pairs{2}
the second, and so on.