Bigraph from a message with 428 characters
3 次查看(过去 30 天)
显示 更早的评论
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1562544/image.png)
alphabets = [' ','A':'Z'];
Map(alphabets) = 0:numel(alphabets)-1;
ciphertext = ['PUOSP MQUPO AUQYD LEGXC UJXFG ODGXP OQPOC RHPDY ' ...
'CLCZV RVSUB OXPEX IWGEB BJVEN SCVNB AOXPX PQUDG ' ...
'AOVDA MWQJS AOZTW SEDDT CJUAV AKEWN VSDUC JAIVR ' ...
'NOPUO SPMQU POKZQ TBUXP ZMDIZ TLKOC CAAVV DXPWG ' ...
'UTWGU ZABOA PEOQU PDSJC EJXCC ZDTCJ ZVOCH KPGWJ ' ...
'CLCZN BRWPS DEBMC LPVNS EVQTP OUHSU VECBE NVDEN ' ...
'DWZAX NQUDQ UTCUU JXPHC QIETD HCFXI YKWSU MEDCF ' ...
'DXAFX PJGUH BJVEU FNMBU NKXPN OOEWG JCWNN AUFDT ' ...
'CJZJU YUPDR CJABH LDIUT CXNAW JKZXP WUMMW GENGK ' ...
'DQCJY XWSKR MWUIS UNCWA CJUAV DPSVE XGDGC JAFVH ' ...
'NKYKD IXZWU ZSDQC JEGYR WSXPN OZQ'];
messageNumeric = Map(ciphertext);
textdata = split(ciphertext,alphabets,2);
tabulate(messageNumeric);
0 个评论
回答(1 个)
Ravi
2023-12-21
Hi Martin,
I understand that you need a table representing bigrams, their frequency, and percentage for the given cipher text.
To begin with, a bigram is a two-character string. When counting the bigrams in a text, we can consider the characters at the “ith” place and “(i+1)th” place.
Create a map that stores bigrams as keys and the corresponding counts as values. Iterate over the cipher text to form bigrams and check if they already exist in the map. If they already exist in the map, then increase the count of the bigram, else add bigram to the map and initialize count to one.
Since, we are interested in printing the bigraph in descending order of the counts, sort the counts in descending order and find the respective keys from the sort order. In a loop of desired number of ranks (here 10), print the rank (index), key, count, and the corresponding percentage.
% Initialize a map to hold bigram counts
bigramCounts = containers.Map('KeyType', 'char', 'ValueType', 'double');
% Calculate bigram counts
for i = 1:length(ciphertext)-1
bigram = ciphertext(i:i+1);
if isKey(bigramCounts, bigram)
bigramCounts(bigram) = bigramCounts(bigram) + 1;
else
bigramCounts(bigram) = 1;
end
end
% Calculate total number of bigrams
totalBigrams = length(ciphertext) - 1;
% Sort the bigrams by count in descending order
[sortedCounts, sortOrder] = sort(cell2mat(values(bigramCounts)), 'descend');
keys = bigramCounts.keys;
sortedBigramKeys = keys(sortOrder);
fprintf("Rank\tBigram\tCount\tPercentage\n");
for i = 1:10
key = sortedBigramKeys{i};
cnt = sortedCounts(i);
percent = (cnt / totalBigrams) * 100;
fprintf("%d\t%s\t%d\t%.2f\n", i, key, cnt, percent);
end
Hope this answer resolves the issue you are facing.
Thanks,
Ravi Chandra
0 个评论
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!