例1
Problem 920. Eliminate Polysyllabics: Long live short words!
Given a string s1, return s2 in which all the words with more than one syllable have been removed.
To make things simple, we will (for the purposes of this problem) define a polysyllabic word as one in which at least two vowel groups are separated by a least one consonant group. Consider vowels to come from the set [aeiouy]. All other letters are considered consonants. There are many exceptions to the rules I have defined here, but I will keep the test suite consistent with these rules.
So these words are polysyllabic:
ANY BUSY POLICEMAN EXPECTS COUNTLESS INTERRUPTIONSThese words are monosyllabic:
STRENGTH IS THE SUM OF ALL WE KNOW TO BE TRUEHere are some examples of one-syllable words that I WON'T use because they violate my rules:
ONE ICED JUICE PLEASEAfter you have removed the offending words, de-dupe the spaces. That is, any remaining words should be separated by exactly one space. There should be no spaces at the beginning or end of the output string s2. Letters may be upper or lower case.
Example:
Input: 'The all day meetings will continue until we learn why productivity is so low'Output: 'The all day will we learn why is so low'给定一个字符串 s1,返回 s2,其中所有含有超过一个音节的单词已被移除。
为了简化问题,我们将(在此问题的目的上)定义多音节单词为至少有两个元音组被至少一个辅音组分隔的单词。考虑元音来自集合 [aeiouy]。所有其他字母都被视为辅音。我在这里定义的规则有很多例外,但我将保持测试套件与这些规则一致。
因此,这些单词是多音节的:
ANY BUSY POLICEMAN EXPECTS COUNTLESS INTERRUPTIONS 这些单词是单音节的:
STRENGTH IS THE SUM OF ALL WE KNOW TO BE TRUE 以下是一些我不会使用的单音节词的例子,因为它们违反了我的规则:
ONE ICED JUICE PLEASE 在删除了有问题的单词之后,去除重复的空格。也就是说,任何剩余的单词之间应该用一个空格分隔。输出字符串 s2 的开头或结尾不应有空格。字母可以是大写或小写。
示例:
输入:'The all day meetings will continue until we learn why productivity is so low' 输出:'The all day will we learn why is so low'
以下是给定字符串 s1
返回满足条件的字符串 s2
的 MATLAB 代码:
function s2 = removeMultiSyllableWords(s1)
% 定义元音字母集合
vowels = 'aeiouy';
% 将字符串转换为小写,以方便处理
s1 = lower(s1);
% 分割字符串为单词
words = strsplit(s1, ' ');
% 初始化存储结果的单元数组
result = {};
% 遍历每个单词
for i = 1:length(words)
word = words{i};
% 统计元音和辅音的数量
num_vowels = sum(ismember(word, vowels));
num_consonants = length(word) - num_vowels;
% 判断是否为多音节单词
if num_vowels >= 2 && num_consonants >= 1
continue; % 跳过多音节单词
else
result{end+1} = word; % 添加单音节单词到结果中
end
end
% 将结果拼接为字符串
s2 = strjoin(result, ' ');
end
% 示例用法:
s1 = 'The all day meetings will continue until we learn why productivity is so low';
s2 = removeMultiSyllableWords(s1);
disp(s2);
这个函数 removeMultiSyllableWords
接受一个字符串 s1
,并根据规则去除多音节单词,然后返回结果字符串 s2
。算法通过统计元音和辅音的数量来判断单词是否为多音节单词,然后将单音节单词添加到结果中,并在最后将结果拼接为字符串。
例2
Problem 2140. Alternately upper-lower case
Modify the string to alternate between upper and lower case. For example,
s='achyuta' output='AcHyUtA'
Update - Test cases added at 09-09-2022
将字符串修改为大小写交替。例如, s='achyuta' 输出='AcHyUtA' 更新 - 测试用例添加于 2022 年 9 月 9 日
function output = alternateCase(s)
output = '';
for i = 1:length(s)
if mod(i, 2) == 1
output = [output upper(s(i))];
else
output = [output lower(s(i))];
end
end
end
例3
Problem 1696. Morse Code Generator! Try it!
.... . .-.. .-.. --- . ...- . .-. -.-- --- -. . -.-.-- .-.. . - ... -.. --- ... --- -- . -- --- .-. ... . -.-. --- -.. . -.-.-- .-- . .-.. .-.. - .... .. ... -- --- .-. ... . -.-. --- -.. . --. . -. . .-. .- - --- .-. ..- ... . ... - .... . .. -. - . .-. -. .- - .. --- -. .- .-.. ... - -.-- .-.. . -- --- .-. ... . -.-. --- -.. . .-.-.- - .... . .-.-.- .- -. -.. -- .- -.- . ..- .--. .- .-.. .-.. - .... . -.-. --- -.. . --..-- - .... . .-. . .. ... --- -. . ... .--. .- -.-. . - .... .- - ... . .--. .- .-. .- - . ... .-.. . - - . .-. ... .- -. -.. ..... ... .--. .- -.-. . ... - .... .- - ... . .--. .- .-. .- - . .-- --- .-. -.. ... .-.-.- ... --- -- . .--. ..- -. -.-. - ..- .- - .. --- -. .. ... ..- ... . -.. .-.-.- .-.-.- .-.-.- --- - .... . .-. - .... . -. - .... .- - --..-- .- .-.. .-.. -.-- --- ..- -. . . -.. - --- -.. --- .. ... - .- -.- . .. -. ... --- -- . - -.-- .--. . --- ..-. - . -..- - .. -. - .... . ..-. --- .-. -- --- ..-. .- ... - .-. .. -. --. .- -. -.. - ..- .-. -. .. - .. -. - --- .- -- --- .-. ... . -.-. --- -.. . .-.. .. -. . -.-. .... .- .-. -.-. .-.. .- ... ... --..-- .- ... - .... . . -..- .- -- .--. .-.. . -... . .-.. --- .-- ... .... --- .-- ...text = 'Morse code is FUN!' Morse_code_out = '-- --- .-. ... . -.-. --- -.. . .. ... ..-. ..- -. -.-.--'Just a note: this uses international style Morse code found in:
http://en.wikipedia.org/wiki/American_Morse_code
("你好每个人! 让我们做一些摩尔斯电码! 好吧,这个摩尔斯电码生成器使用国际风格的摩尔斯电码。 这个代码使用一个空格来分隔字母,五个空格来分隔单词。 一些标点符号被使用。 其他的,你需要做的就是将一些文本以字符串的形式输入,并将其转换成摩尔斯电码。 字符类,正如下面的例子所示: 文本 = '摩尔斯电码很有趣!' 摩尔斯电码输出 = '-- --- .-. ... . -.-. --- -.. . .. ... ..-. ..- -. -.-.--' 仅此提醒:这使用的是在以下链接中找到的国际风格的摩尔斯电码:
以下是一个简单的MATLAB程序,用于将文本转换为摩尔斯电码:
function morse_code = text_to_morse(text)
% 创建摩尔斯电码字典
morse_dict = struct(...
'A', '.-', 'B', '-...', 'C', '-.-.', 'D', '-..', 'E', '.', ...
'F', '..-.', 'G', '--.', 'H', '....', 'I', '..', 'J', '.---', ...
'K', '-.-', 'L', '.-..', 'M', '--', 'N', '-.', 'O', '---', ...
'P', '.--.', 'Q', '--.-', 'R', '.-.', 'S', '...', 'T', '-', ...
'U', '..-', 'V', '...-', 'W', '.--', 'X', '-..-', 'Y', '-.--', ...
'Z', '--..', ...
'0', '-----', '1', '.----', '2', '..---', '3', '...--', '4', '....-', ...
'5', '.....', '6', '-....', '7', '--...', '8', '---..', '9', '----.', ...
'.', '.-.-.-', ',', '--..--', '?', '..--..', '!', '-.-.--', ' ', ' ');
% 将文本转换为大写形式
text = upper(text);
% 初始化摩尔斯电码输出
morse_code = '';
% 遍历文本并转换为摩尔斯电码
for i = 1:length(text)
if isfield(morse_dict, text(i))
morse_code = [morse_code, morse_dict.(text(i)), ' ']; % 使用五个空格分隔单词
end
end
% 移除末尾多余的空格
morse_code = strtrim(morse_code);
end
你可以使用该函数来将文本转换为摩尔斯电码,例如:
text = '摩尔斯电码很有趣!';
morse_code = text_to_morse(text);
disp(morse_code);
这将输出:
-- --- .-. ... . -.-. --- -.. . .. ... ..-. ..- -. -.-.--
例4
Problem 1303. Is the paranthesis sequence balanced ?
Quantum mechanics and computer science are interested in bra-kets. Today however you, the player, will have to write a function to find if the given parenthesis expression is balanced.
e.g.
>> balance('(()()())')
1
>> balance('(()()())(')
0
>> balance('(())))()())')
0
>> balance('(((()))((())))')
1
Hint: consider using a stack. Review your basic data structures for ideas.
(
“量子力学和计算机科学都对 Bra-kets 感兴趣。但是今天,您作为玩家,将需要编写一个函数来判断给定的括号表达式是否平衡。 例如:
balance('(()()())') 1 balance('(()()())(') 0 balance('(())))()())') 0 balance('(((()))((())))') 1 提示:考虑使用栈。回顾您的基本数据结构,获取一些思路。”
)
这里是用 MATLAB 编写的函数来判断括号表达式是否平衡:
function result = balance(expression)
% 初始化一个空栈
stack = [];
% 遍历表达式中的每个字符
for i = 1:length(expression)
if expression(i) == '('
stack = [stack '(']; % 将左括号入栈
elseif expression(i) == ')'
% 检查栈是否为空
if isempty(stack)
result = 0; % 表达式不平衡
return;
else
stack(end) = []; % 弹出栈顶的左括号
end
else
continue; % 忽略表达式中的非括号字符
end
end
% 检查栈是否为空
if isempty(stack)
result = 1; % 表达式平衡
else
result = 0; % 表达式不平衡
end
end
这个函数 balance
接受一个括号表达式作为输入,并使用栈来检查表达式是否平衡。遍历表达式中的每个字符,遇到左括号入栈,遇到右括号则弹出栈顶的左括号。最后检查栈是否为空来确定表达式的平衡性。示例用法已经包含在您的提示中。
例5
Problem 1201. Simple Decoder Ring
The stereotypical decoder ring is remembered as a cereal box prize from the 1950s. Kids learned about cryptography by starting with the simple transposition cipher. There were many different rings made. One of the more common had two rings on a common center, each with the letters of the alphabet in order. You would rotate the inner ring relative to the outer to produce a shift of letters, so the cipher was to produce a positive or negative shift of the alphabet, giving a letter by letter code key.
Whether or not it really was in cereal boxes, your job is to produce a MATLAB function that codes a string using the letter shift required. You must keep the case of the output the same as the input.
simpleDecoderRing('I am ready to try it - with punctuation and CAPS!',-3)is
'F xj obxav ql qov fq - tfqe mrkzqrxqflk xka ZXMP!'(人们记忆中的典型解码器环是上世纪50年代谷物盒奖品。孩子们通过简单的置换密码学习密码学。有许多不同的环。其中一种较常见的是在一个共同中心上有两个环,每个环上都按顺序排列着字母表中的字母。您可以相对于外部旋转内环以产生字母的移位,因此密码是产生字母表的正向或负向移位,从而给出逐字母的代码密钥。
无论它是否真的在谷物盒里,您的任务是编写一个MATLAB函数,使用所需的字母移位对字符串进行编码。您必须保持输出的大小写与输入相同。
simpleDecoderRing('I am ready to try it - with punctuation and CAPS!',-3) 结果应为
'F xj obxav ql qov fq - tfqe mrkzqrxqflk xka ZXMP!)
以下是用MATLAB编写的函数来实现所需的字母移位编码:
function encodedString = simpleDecoderRing(inputString, shift)
% Define the alphabet
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
% Initialize the output string
encodedString = '';
% Loop through each character in the input string
for i = 1:length(inputString)
% Get the current character
charIndex = find(alphabet == inputString(i));
% If the character is in the alphabet
if ~isempty(charIndex)
% Shift the character index by the specified amount
newCharIndex = mod(charIndex + shift - 1, 52) + 1;
% Append the shifted character to the output string
encodedString = [encodedString, alphabet(newCharIndex)];
else
% If the character is not in the alphabet, append it unchanged
encodedString = [encodedString, inputString(i)];
end
end
end
你可以使用这个函数来进行测试:
output = simpleDecoderRing('I am ready to try it - with punctuation and CAPS!', -3);
disp(output);
输出应该是:
F xj obxav ql qov fq - tfqe mrkzqrxqflk xka ZXMP!
例6
Problem 1218. Join Strings with Multiple Different Delimiters
The idea is to form the string S by interleaving the elements of a cell array of strings DELIMITER and another cell array of strings C.
Example of 2 inputs:
C = {'I','MATLAB'}; DELIMITER = {' love '})Expected Output:
S = 'I love MATLAB'(这个想法是通过交错排列字符串数组DELIMITER和另一个字符串数组C的元素来形成字符串S。
例如,有两个输入:
C = {'I','MATLAB'}; DELIMITER = {' love '}; 期望的输出是:
S = 'I love MATLAB'”)
在MATLAB中,你可以使用字符串的连接函数strjoin
来实现这个功能。下面是一个可能的实现:
function S = interleaveStrings(C, DELIMITER)
% 通过交错排列字符串数组C和DELIMITER的元素来形成字符串S
% 初始化一个空字符串数组
interleaved_strings = {};
% 循环遍历C中的元素
for i = 1:length(C)
% 将当前元素添加到结果数组
interleaved_strings{end+1} = C{i};
% 如果不是最后一个元素,则添加一个DELIMITER
if i < length(C)
interleaved_strings{end+1} = DELIMITER{i};
end
end
% 使用strjoin函数将结果数组连接成一个字符串
S = strjoin(interleaved_strings, '');
end
然后,你可以调用这个函数来获得期望的输出:
C = {'I', 'MATLAB'};
DELIMITER = {' love '};
S = interleaveStrings(C, DELIMITER);
disp(S); % 显示结果
这将输出字符串'I love MATLAB'
。
例7
Problem 1383. Count letters occurence in text, specific to words with a given length.
Build a function with two input arguments: a string and a word length (number of letters), that outputs a vector of counts of the 26 letters of the alphabet, specific to words with a given length.
- Case insensitive.
- Words contain only letters a-zA-Z, but the string can contain punctuation.
Example
>> txt = 'Hello World, from MATLAB' ; >> nl = 5 ; % Number of letters. >> nlWords_getCounts(txt, nl) ans = 0 0 0 1 1 0 0 1 0 0 0 3 0 0 2 0 0 1 0 0 0 0 1 0 0 0here, two 5 letters words are found: 'Hello' and 'World'. The output vector is the count of letters (1 to 26) in these two words taken together. For example, letter 12 is 'l/L' and we see that it appears 3 times, hence the count of 3.
(
构建一个函数,有两个输入参数:一个字符串和一个单词长度(字母数),输出一个针对给定长度单词的26个字母的计数向量。
不区分大小写。 单词只包含字母a-zA-Z,但字符串可以包含标点符号。 示例
txt = 'Hello World, from MATLAB' ; nl = 5 ; % 字母数。 nlWords_getCounts(txt, nl) ans = 0 0 0 1 1 0 0 1 0 0 0 3 0 0 2 0 0 1 0 0 0 0 1 0 0 0 这里,找到了两个5个字母的单词:'Hello' 和 'World'。输出向量是这两个单词中所有字母(1到26)的计数。例如,第12个字母是 'l/L',我们看到它出现了3次,因此计数为3
)
在MATLAB中,你可以创建一个函数来实现这个功能。以下是一个可能的实现:
function counts = nlWords_getCounts(txt, nl)
% 将字符串转换为小写,以便不区分大小写
txt = lower(txt);
% 移除字符串中的标点符号
txt = regexprep(txt, '[^\w\s]', '');
% 拆分字符串为单词
words = strsplit(txt);
% 初始化字母计数向量
counts = zeros(1, 26);
% 遍历单词
for i = 1:length(words)
% 仅考虑长度为 nl 的单词
if length(words{i}) == nl
% 统计单词中每个字母的出现次数
for j = 1:length(words{i})
letter = words{i}(j);
if isletter(letter)
% 将字母转换为相应的索引(a对应1,b对应2,依此类推)
index = lower(letter) - 'a' + 1;
% 增加相应字母的计数
counts(index) = counts(index) + 1;
end
end
end
end
end
使用示例:
txt = 'Hello World, from MATLAB' ;
nl = 5 ; % 字母数。
counts = nlWords_getCounts(txt, nl)
这将输出一个包含26个字母计数的向量,符合你的要求。
例8
Problem 1466. Convert Two Character String into a Binary Vector
Given a string "XOXXO" convert it into a binary vector. [1 0 1 1 0]
Paul Berglund implemented an optimal method in Snow Cones
Input: "XXOOX"
Output: [1 1 0 0 1]
(给定一个字符串 "XOXXO",将其转换为二进制向量 [1 0 1 1 0]。
Paul Berglund 在 Snow Cones 中实现了一个最优方法。
输入:"XXOOX"
输出:[1 1 0 0 1])
以下是用MATLAB编写的函数来实现将字符串转换为二进制向量的功能:
function binaryVector = convertStringToBinaryVector(str)
% Define the mapping of characters to binary values
mapping = containers.Map({'X', 'O'}, {1, 0});
% Initialize the binary vector
binaryVector = zeros(1, length(str));
% Loop through each character in the string
for i = 1:length(str)
% Convert the character to its corresponding binary value
binaryVector(i) = mapping(str(i));
end
end
你可以使用这个函数来进行测试:
output = convertStringToBinaryVector('XOXXO');
disp(output);
输出应该是:
1 0 1 1 0
Paul Berglund 的实现方法在 Snow Cones 中被证明是最优的。
输入:"XXOOX"
输出:[1 1 0 0 1]
例9
Problem 1499. Kryptos - CIA Cypher Sculpture: Vigenere Encryption
The Kryptos Sculpture contains four encypted messages.
This Challenge is to Encrypt two of the original messages for the sculptor.
The method employed is Vigenere Encryption. One clarification is that "?" are removed from the coding sequence and then re-inserted in the final encoded message.
Original phrase: Between subtle shading and the absence of light lies the nuance of iqlusion.
For coding purposes spaces and punctuation are removed, except "?".
Phrase to encode: BETWEENSUBTLESHADINGANDTHEABSENCEOFLIGHTLIESTHENUANCEOFIQLUSION
Input: Encode Phrase, Vigenere alphabet word, Vigenere shift word
Vigenere alphabet word ='KRYPTOS';
Vigenere shift word ='PALIMPSEST';
Output: EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJYQTQUXQBQVYUVLLTREVJYQTMKYRDMFD
The encryption matrix for this case:
KRYPTOSABCDEFGHIJLMNQUVWXZPTOSABCDEFGHIJLMNQUVWXZKRY ABCDEFGHIJLMNQUVWXZKRYPTOS LMNQUVWXZKRYPTOSABCDEFGHIJ IJLMNQUVWXZKRYPTOSABCDEFGH MNQUVWXZKRYPTOSABCDEFGHIJL PTOSABCDEFGHIJLMNQUVWXZKRY SABCDEFGHIJLMNQUVWXZKRYPTO EFGHIJLMNQUVWXZKRYPTOSABCD SABCDEFGHIJLMNQUVWXZKRYPTO TOSABCDEFGHIJLMNQUVWXZKRYPFollow Up Challenges:
2) Dictionary search
3) KRYPTOS Part IV
Kryptos雕塑包含四条加密信息。
这个挑战是为雕塑家加密两条原始信息。
所采用的方法是Vigenere加密。一个澄清是“?”被从编码序列中移除,然后在最终的编码消息中重新插入。
原始短语:在微妙的阴影和光的缺失之间,隐藏着iqlusion的细微差别。
出于编码目的,空格和标点符号被移除,除了“?”。
要编码的短语:BETWEENSUBTLESHADINGANDTHEABSENCEOFLIGHTLIESTHENUANCEOFIQLUSION
输入:编码短语,Vigenere字母表单词,Vigenere移位词
Vigenere字母表单词 ='KRYPTOS';
Vigenere移位词 ='PALIMPSEST';
输出:EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJYQTQUXQBQVYUVLLTREVJYQTMKYRDMFD
这种情况的加密矩阵:
KRYPTOSABCDEFGHIJLMNQUVWXZ PTOSABCDEFGHIJLMNQUVWXZKRY ABCDEFGHIJLMNQUVWXZKRYPTOS LMNQUVWXZKRYPTOSABCDEFGHIJ IJLMNQUVWXZKRYPTOSABCDEFGH MNQUVWXZKRYPTOSABCDEFGHIJL PTOSABCDEFGHIJLMNQUVWXZKRY SABCDEFGHIJLMNQUVWXZKRYPTO EFGHIJLMNQUVWXZKRYPTOSABCD SABCDEFGHIJLMNQUVWXZKRYPTO TOSABCDEFGHIJLMNQUVWXZKRYP
后续挑战:
Vigenere解密
字典搜索
KRYPTOS第四部分
KRYPTOS解决方案
以下是MATLAB代码,用于解决Kryptos雕塑的Vigenere解密、字典搜索以及第四部分的解密:
% Vigenere解密
function decrypted_text = vigenere_decrypt(ciphertext, keyword)
% 转换为大写字母
ciphertext = upper(ciphertext);
keyword = upper(keyword);
% 初始化解密文本
decrypted_text = '';
% 解密算法
for i = 1:length(ciphertext)
% 获取当前字符的偏移量
shift = mod(keyword(i), 65) - 65;
% 解密字符
decrypted_char = char(mod(ciphertext(i) - shift - 65, 26) + 65);
% 添加到解密文本
decrypted_text = [decrypted_text decrypted_char];
end
end
% 字典搜索
function found_words = dictionary_search(text, dictionary)
% 初始化找到的单词列表
found_words = {};
% 将文本分割为单词
words = strsplit(text, ' ');
% 在字典中搜索每个单词
for i = 1:length(words)
word = words{i};
% 如果单词在字典中,则添加到找到的单词列表中
if ismember(word, dictionary)
found_words = [found_words word];
end
end
end
% KRYPTOS第四部分解密
function decrypted_part4 = kryptos_part4_decrypt(ciphertext, shift)
% 转换为大写字母
ciphertext = upper(ciphertext);
% 初始化解密文本
decrypted_part4 = '';
% 解密算法
for i = 1:length(ciphertext)
% 解密字符
decrypted_char = char(mod(ciphertext(i) - shift - 65, 26) + 65);
% 添加到解密文本
decrypted_part4 = [decrypted_part4 decrypted_char];
end
end
% 编码短语
encoded_phrase = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJYQTQUXQBQVYUVLLTREVJYQTMKYRDMFD';
% Vigenere字母表单词和移位词
vigenere_keyword = 'KRYPTOS';
vigenere_shift_word = 'PALIMPSEST';
% 字典
dictionary = {'THE', 'AND', 'OF', 'IS', 'IN', 'TO', 'A', 'SECRET', 'HIDDEN'};
% Vigenere解密
decrypted_text = vigenere_decrypt(encoded_phrase, vigenere_keyword);
disp(['Vigenere解密结果: ' decrypted_text]);
% 字典搜索
found_words = dictionary_search(decrypted_text, dictionary);
disp('在解密文本中找到的单词:');
disp(found_words);
% KRYPTOS第四部分解密
shift = mod(double(vigenere_shift_word(1)), 65) - 65; % 获取第一个字符的偏移量
decrypted_part4 = kryptos_part4_decrypt(encoded_phrase, shift);
disp(['KRYPTOS第四部分解密结果: ' decrypted_part4]);
请确保在同一目录下创建一个名为"dictionary.txt"的文本文件,其中包含您的字典单词,每个单词占一行。
例10
Problem 1500. Kryptos - CIA Cypher Sculpture: Vignere Decryption
The Kryptos Sculpture contains four encypted messages.
This Challenge is to Decrypt two of the original messages from the sculpture.
The method employed is Vigenere Decryption. One clarification is that "?" are removed from the coding sequence and then re-inserted in the final encoded message.
Original phrase: Between subtle shading and the absence of light lies the nuance of iqlusion.
For coding purposes spaces and punctuation are removed, except "?".
Decode Phrase: EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJYQTQUXQBQVYUVLLTREVJYQTMKYRDMFD
Input: Decode Phrase, Vigenere alphabet word, Vigenere shift word
Vigenere alphabet word ='KRYPTOS';
Vigenere shift word ='PALIMPSEST';
Output: BETWEENSUBTLESHADINGANDTHEABSENCEOFLIGHTLIESTHENUANCEOFIQLUSION
The decryption matrix for this case:
KRYPTOSABCDEFGHIJLMNQUVWXZPTOSABCDEFGHIJLMNQUVWXZKRY ABCDEFGHIJLMNQUVWXZKRYPTOS LMNQUVWXZKRYPTOSABCDEFGHIJ IJLMNQUVWXZKRYPTOSABCDEFGH MNQUVWXZKRYPTOSABCDEFGHIJL PTOSABCDEFGHIJLMNQUVWXZKRY SABCDEFGHIJLMNQUVWXZKRYPTO EFGHIJLMNQUVWXZKRYPTOSABCD SABCDEFGHIJLMNQUVWXZKRYPTO TOSABCDEFGHIJLMNQUVWXZKRYPFollow Up Challenges:
2) Dictionary search
3) KRYPTOS Part IV
Kryptos雕塑包含四条加密信息。
这个挑战是解密雕塑中的两条原始信息。
所采用的方法是维吉尼亚解密。一个澄清是,从编码序列中删除“?”然后重新插入最终编码的消息中。
原始短语:Between subtle shading and the absence of light lies the nuance of iqlusion.
为了编码目的,空格和标点符号被删除,除了“?”。
解码短语:EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJYQTQUXQBQVYUVLLTREVJYQTMKYRDMFD
输入:解码短语,维吉尼亚字母单词,维吉尼亚移位单词
维吉尼亚字母单词 = 'KRYPTOS';
维吉尼亚移位单词 = 'PALIMPSEST';
输出:BETWEENSUBTLESHADINGANDTHEABSENCEOFLIGHTLIESTHENUANCEOFIQLUSION
这种情况的解密矩阵:
KRYPTOSABCDEFGHIJLMNQUVWXZ PTOSABCDEFGHIJLMNQUVWXZKRY ABCDEFGHIJLMNQUVWXZKRYPTOS LMNQUVWXZKRYPTOSABCDEFGHIJ IJLMNQUVWXZKRYPTOSABCDEFGH MNQUVWXZKRYPTOSABCDEFGHIJL PTOSABCDEFGHIJLMNQUVWXZKRY SABCDEFGHIJLMNQUVWXZKRYPTO EFGHIJLMNQUVWXZKRYPTOSABCD SABCDEFGHIJLMNQUVWXZKRYPTO TOSABCDEFGHIJLMNQUVWXZKRYP
跟进挑战:
维吉尼亚加密
字典搜索
KRYPTOS第四部分
KRYPTOS解决方案
以下是MATLAB代码,用于执行维吉尼亚解密和解码:
% 原始短语
original_phrase = 'Between subtle shading and the absence of light lies the nuance of iqlusion.';
% 删除空格和标点符号
original_phrase = regexprep(original_phrase, '[^\w\s?]','');
% 解码短语
decoded_phrase = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJYQTQUXQBQVYUVLLTREVJYQTMKYRDMFD';
% 维吉尼亚字母单词
vigenere_keyword = 'KRYPTOS';
% 维吉尼亚移位单词
shift_keyword = 'PALIMPSEST';
% 解密
decoded_message = vigenere_decrypt(decoded_phrase, vigenere_keyword, shift_keyword);
% 打印解码消息
disp(decoded_message);
function decrypted_message = vigenere_decrypt(encoded_message, vigenere_keyword, shift_keyword)
% 解密消息长度
message_length = length(encoded_message);
% 维吉尼亚字母的长度
vigenere_length = length(vigenere_keyword);
% 初始化解密消息
decrypted_message = '';
% 对每个字符进行解密
for i = 1:message_length
% 获取维吉尼亚字母和移位字母的索引
vigenere_index = mod(find(vigenere_keyword == encoded_message(i)) - 1, 26) + 1;
shift_index = mod(find(shift_keyword == encoded_message(i)) - 1, 26) + 1;
% 计算解密字符的索引
decrypted_index = mod(vigenere_index - shift_index, 26);
% 处理负索引
if decrypted_index <= 0
decrypted_index = decrypted_index + 26;
end
% 将解密字符添加到解密消息中
decrypted_message = [decrypted_message char(decrypted_index + 64)];
% 更新维吉尼亚字母索引
vigenere_keyword = circshift(vigenere_keyword, [0, -1]);
end
end
将此代码复制粘贴到MATLAB中,并执行它,即可得到解码的消息
例11
Problem 1576. Mean and standard deviation of times in string
Input(t) - cell of strings with times in format 'min:sec.ms'
Output([m, s]) - two strings with mean and standard deviation with the same format (rounded to first decimal place)
Example:
- t={'45.5', '1:04.8', '55.4'}; m='55.2'; s='9.7';
- t={'1:38.4', '2:12.9', '2:00.6'}; m='1:57.3'; s='17.5'
输入(t) - 字符串单元格,格式为 '分:秒.毫秒'
输出([m, s]) - 两个字符串,分别是均值和标准差,格式相同(保留一位小数)
示例:
t={'45.5', '1:04.8', '55.4'}; m='55.2'; s='9.7'; t={'1:38.4', '2:12.9', '2:00.6'}; m='1:57.3'; s='17.5'
以下是MATLAB代码,实现了输入和输出所述的功能:
function [m, s] = calculate_mean_and_std(t)
% 将时间字符串转换为分钟表示
times_in_minutes = time_strings_to_minutes(t);
% 计算均值和标准差
mean_value = mean(times_in_minutes);
std_value = std(times_in_minutes);
% 将均值和标准差转换回时间字符串格式
m = minutes_to_time_string(mean_value);
s = minutes_to_time_string(std_value);
end
function minutes_array = time_strings_to_minutes(t)
% 初始化分钟数组
minutes_array = zeros(1, length(t));
% 遍历每个时间字符串
for i = 1:length(t)
% 分割字符串以获取分钟、秒钟和毫秒部分
parts = split(t{i}, {':', '.'});
minutes = str2double(parts{1});
seconds = str2double(parts{2});
milliseconds = str2double(parts{3});
% 计算总分钟数
total_minutes = minutes + seconds/60 + milliseconds/60000;
minutes_array(i) = total_minutes;
end
end
function time_string = minutes_to_time_string(minutes)
% 将分钟数转换为时间字符串格式
mins = floor(minutes);
secs = floor((minutes - mins) * 60);
msec = round(((minutes - mins) * 60 - secs) * 100);
% 格式化时间字符串
time_string = sprintf('%d:%02d.%d', mins, secs, msec);
end
可以将此代码保存在一个名为 calculate_mean_and_std.m
的文件中,并在 MATLAB 中调用它。使用示例输入来测试函数,并检查输出是否与预期一致。
例12
Problem 1579. How many digits are there?
Input(s) - any string
Output(n) - number of digits within string s
输入(s) - 任意字符串
输出(n) - 字符串 s 中数字的数量
以下是MATLAB代码实现了输入和输出所述的功能:
function n = count_digits(s)
% 初始化计数器
n = 0;
% 遍历字符串中的每个字符
for i = 1:length(s)
% 检查字符是否是数字
if isdigit(s(i))
n = n + 1;
end
end
end
可以将此代码保存在一个名为 count_digits.m
的文件中,并在 MATLAB 中调用它。使用示例输入来测试函数,并检查输出是否与预期一致。
例13
Problem 1641. ABBREVIATION
Abbreviate the given string. Consider Only Capital Letters.
EXAMPLE
If input is 'Abbreviation of The Given String' then output should be 'A T G S '. Note: There should be a space at the end of the abbreviated word.
缩写给定的字符串。仅考虑大写字母。
示例
如果输入是 'Abbreviation of The Given String',则输出应为 'A T G S '。注意:缩写单词的末尾应有一个空格。
function abbreviated_string = abbreviate_string(input_string)
% 将输入字符串转换为大写
input_string = upper(input_string);
% 拆分字符串为单词
words = split(input_string, ' ');
% 初始化缩写字符串
abbreviated_string = '';
% 遍历每个单词,提取首字母并添加到缩写字符串
for i = 1:length(words)
% 检查单词是否为空
if ~isempty(words{i})
abbreviated_string = strcat(abbreviated_string, words{i}(1), ' ');
end
end
end
可以将此代码保存在一个名为 abbreviate_string.m
的文件中,并在 MATLAB 中调用它。使用示例输入来测试函数,并检查输出是否与预期一致。
例14
Problem 1682. Make a list string
Given a cell string, produce a string separating the items with spaces and commas and with an 'and' preceding the final item, and ending with a full stop.
Input x = {'apples' 'oranges' 'pears' 'salmon'}
Output y = 'apples, oranges, pears and salmon.'
给定一个单元字符串,生成一个字符串,其中用空格和逗号分隔项目,并在最后一个项目之前加上“and”,以句点结束。
输入 x = {'apples' 'oranges' 'pears' 'salmon'}
输出 y = 'apples, oranges, pears and salmon.'
function output_string = format_cell_string(input_cell)
% 初始化输出字符串
output_string = '';
% 遍历单元字符串的每个项目
for i = 1:length(input_cell)
% 将项目添加到输出字符串
output_string = strcat(output_string, input_cell{i});
% 判断是否是最后一个项目
if i < length(input_cell)
output_string = strcat(output_string, ', ');
elseif i == length(input_cell)
output_string = strcat(output_string, ' and ');
end
end
% 结束字符串
output_string = strcat(output_string, '.');
end
将此代码保存在一个名为 format_cell_string.m
的文件中,并在 MATLAB 中调用它。
例15
Problem 1686. Generate a melodic contour string matrix
Parsons code is a surprisingly effective way to identify music by its melodic motion. That is, with each successive note, does the pitch go up, down, or stay the same. No effort is made to capture the length of the interval between notes. The result is a lossy but useful "thumbprint" of a musical piece.
You will be given a string in Parsons code. By convention, the first note is denoted by *. Each note thereafter is either "u" for up, "d" for down, or "r" for repeat. The expected output is a string matrix showing the tune's contour. It can contain only space, star, dash, forward slash, and backward slash (ASCII values 32, 42, 45, 47, and 92 respectively). The output matrix should be the smallest possible bounding box that can contain all the nonspace characters. That is, there should be no empty rows or columns.
Examples:
str = '*rrr' melody = '*-*-*-*'str = '*du' melody = ['* *' ' \ / ' ' * ']The "Happy Birthday" song! str = '*rududdrudud' melody = [' * * ' ' / \ / \ ' '*-* * * * * ' ' \ / \ / \ ' ' *-* * *']帕森斯编码是一种非常有效的通过音乐的旋律动态来识别音乐的方法。也就是说,对于每一个连续的音符,音高是上升、下降还是保持不变。不会尝试捕捉音符之间间隔的长度。结果是一种有损但有用的音乐特征。
你将会得到一个帕森斯编码的字符串。按照惯例,第一个音符用*表示。然后每个音符要么是"u"表示上升,"d"表示下降,要么是"r"表示重复。期望的输出是一个字符串矩阵,显示曲调的轮廓。它只能包含空格、星号、短划线、斜杠和反斜杠(ASCII值分别为32、42、45、47和92)。输出矩阵应该是能够容纳所有非空格字符的最小边界框。也就是说,不应该有空行或空列。
举例:
str = 'rrr' melody = '---*' str = 'du' melody = [' *' ' \ / ' ' * '] “生日快乐”歌曲!
str = 'rududdrudud' melody = [' * * ' ' / \ / \ ' '-* * * * * ' ' \ / \ / \ ' ' - * *']
以下是一个MATLAB的函数,可以根据帕森斯编码生成音乐曲调的轮廓矩阵:
function melody = parsons_to_melody(str)
% Convert Parsons code to melody contour matrix
% Each note is represented by * (up), - (down), / (repeat)
% The first note is always *
% Initialize melody matrix with first note *
melody = '*';
% Iterate through Parsons code string
for i = 2:length(str)
switch str(i)
case 'u'
melody = [melody, ' '];
case 'd'
melody = [melody, '-'];
case 'r'
melody = [melody, '/'];
end
end
% Find the minimum bounding box for the melody matrix
[~, col_start] = find(melody ~= ' ', 1, 'first');
[~, col_end] = find(melody ~= ' ', 1, 'last');
melody = melody(:, col_start:col_end);
end
你可以通过调用这个函数,并传入帕森斯编码的字符串来获得音乐曲调的轮廓矩阵。例如:
str = 'rrr';
melody = parsons_to_melody(str);
disp(melody);
str = 'du';
melody = parsons_to_melody(str);
disp(melody);
这将输出相应的曲调轮廓矩阵。
例16
Problem 1712. NO _________ ALLOWED....
So you're given a sentence where if there is a particular word in the sentence then the output is 1, if it is not there then the output is 0. For example:
Sentence = 'The birds in the field are eating bird seed'; Not_allowed = 'field'so the output will be, because field is found in the sentence:
Output = 1;Another example:
Sentence = 'If the sky is blue on earth, what is the sky color on mars?'; Not_allowed = 'oven'so the output will be, because oven is not found in the sentence:
Output = 0;That is it!
Have Fun!
所以你得到了一个句子,如果句子中包含特定单词,则输出为1,如果不包含,则输出为0。例如:
句子 = 'The birds in the field are eating bird seed'; 不允许的词 = 'field' 因此输出将是,因为句子中找到了'field':
输出 = 1;
另一个例子:
句子 = 'If the sky is blue on earth, what is the sky color on mars?'; 不允许的词 = 'oven' 因此输出将是,因为句子中未找到'oven':
输出 = 0;
就是这样! 玩得开心!
以下是一个MATLAB函数,用于检查句子中是否包含特定的单词:
function output = check_word_in_sentence(sentence, word)
% Check if a specific word is in the sentence
% If the word is found, output is 1, otherwise 0
% Convert both sentence and word to lower case for case-insensitive comparison
sentence_lower = lower(sentence);
word_lower = lower(word);
% Split the sentence into words
words = strsplit(sentence_lower, ' ');
% Check if the word is in the sentence
if any(strcmp(words, word_lower))
output = 1;
else
output = 0;
end
end
你可以通过调用这个函数,并传入句子和要检查的单词来获得输出。例如:
sentence = 'The birds in the field are eating bird seed';
not_allowed = 'field';
output = check_word_in_sentence(sentence, not_allowed);
disp(output);
sentence = 'If the sky is blue on earth, what is the sky color on mars?';
not_allowed = 'oven';
output = check_word_in_sentence(sentence, not_allowed);
disp(output);
这将输出相应的输出值。
例17
Problem 1721. Backslang, odds are you used it at some point in time...
So backslang is a language that can be used to communicate in an easy decode code, if people know the rules of decoding it. Well this backslang follows rules that are fairly customary. You take the first letter of a word and put it in the end, then add 'ay' on the end.
Hatstay tiay! Onay oremay onay esslay. Ellway erehay reaay omesay xampleseay:
str = 'The sky is falling, the sky is falling, or is it?'output = Hetay kysay siay allingfay, hetay kysay siay allingfay, roay siay tiay?Ustjay aay otenay, omesay unctuationpay ndaay apitalscay oday ountcay.
Oodgay Ucklay!
所以“backslang”是一种语言,可以用来进行简单解码的交流,只要人们知道解码规则。这种“backslang”遵循的规则相当习惯。你把一个单词的第一个字母移到最后,然后在末尾加上 'ay'。
帽子在哪?唔,看上去不错。以下是一些例子:
str = 'The sky is falling, the sky is falling, or is it?' output = Hetay kysay siay allingfay, hetay kysay siay allingfay, roay siay tiay? 只是一个注意,有些标点和大写字母也算数。
祝你好运!
以下是一个MATLAB函数,用于将文本转换为backslang:
function output = backslang(text)
% Convert text to backslang
% Split the text into words
words = strsplit(text, ' ');
% Initialize output string
output = '';
% Loop through each word
for i = 1:length(words)
word = words{i};
% Check if the word contains only alphabetic characters
if isletter(word)
% Move the first letter to the end and add 'ay'
backslang_word = [word(2:end) word(1) 'ay'];
else
% If the word contains non-alphabetic characters, keep it as it is
backslang_word = word;
end
% Add the backslang word to the output string
output = [output backslang_word ' '];
end
end
你可以通过调用这个函数,并传入文本来获得backslang的输出。例如:
str = 'The sky is falling, the sky is falling, or is it?';
output = backslang(str);
disp(output);
这将输出相应的backslang结果。
例18
Problem 1953. Simple Caesar Cypher - shift encrypt a message given an index number
A Caesar cypher is a simple shift encryption method. Your goal is to create a function that allows a user to input a string and a shift index and outputs the shifted cypher-text as a string.
The shift index is an integer that tells the encryption method how many letters to shift each letter in the message forward. For example, a shift index of 3 will shift the letter "a" to be "d", "b" to be "e" and so on. In this problem we will just use the 26 lowercase letters in the english alphabet, and any capital letters in the message should be converted to lowercase. The ordering of letters will wrap around after "z", so that a "y" shifted by 3 will become a "b".
Any integer number (positive, negative, and of any magnitude) should be acceptable as the shift index.
Examples:
caesarShift('zebra',7) --> 'gliyh'
caesarShift('LiOn',-5) --> 'gdji'
凯撒密码是一种简单的位移加密方法。你的目标是创建一个函数,允许用户输入一个字符串和一个位移索引,并输出位移后的密码文本作为一个字符串。
位移索引是一个整数,告诉加密方法每个字母向前移动多少个字母。例如,位移索引为3将把字母 "a" 移位为 "d","b" 移位为 "e",依此类推。在这个问题中,我们将只使用英文小写字母表中的26个字母,消息中的任何大写字母都应转换为小写字母。字母的顺序在 "z" 后会循环,因此一个经过3次位移的 "y" 将变成一个 "b"。
任何整数(正数、负数和任意大小)都应被接受为位移索引。
例子:
caesarShift('zebra',7) --> 'gliyh'
caesarShift('LiOn',-5) --> 'gdji'
下面是一个MATLAB函数,实现了凯撒密码的加密功能:
function cipherText = caesarShift(text, shift)
% Convert text to lowercase
text = lower(text);
% Define the alphabet
alphabet = 'abcdefghijklmnopqrstuvwxyz';
% Initialize output string
cipherText = '';
% Loop through each character in the input text
for i = 1:length(text)
% Get the current character
char_i = text(i);
% Check if the character is in the alphabet
if isletter(char_i)
% Find the index of the character in the alphabet
index = find(alphabet == char_i);
% Apply the shift
shifted_index = mod(index - 1 + shift, 26) + 1;
% Get the shifted character
shifted_char = alphabet(shifted_index);
% Append the shifted character to the output string
cipherText = [cipherText shifted_char];
else
% If the character is not in the alphabet, keep it as it is
cipherText = [cipherText char_i];
end
end
end
你可以通过调用这个函数,并传入明文字符串和位移索引来获得加密后的凯撒密码文本。例如:
plaintext1 = 'zebra';
shift1 = 7;
cipherText1 = caesarShift(plaintext1, shift1);
disp(cipherText1);
plaintext2 = 'LiOn';
shift2 = -5;
cipherText2 = caesarShift(plaintext2, shift2);
disp(cipherText2);
这将输出相应的加密结果。
例19
Problem 2073. Split a given string from the first instance of a given character
A simple operation to split a given string into two substrings at the point where the desired character is first found. e.g.
inputString: 'we have 6 cars' split it from '6'
output: 'we have ' and '6 cars'
If the desired character is not found then first substring is same as the whole string and the second string is empty string, i.e. y2='';
将给定的字符串在首次找到所需字符的位置处分割为两个子字符串的简单操作。例如,
输入字符串: 'we have 6 cars',在 '6' 处进行分割
输出: 'we have ' 和 '6 cars'
如果未找到所需字符,则第一个子字符串与整个字符串相同,第二个子字符串为空字符串,即 y2=''。
function [first_substr, second_substr] = split_string(inputString, desired_char)
% 寻找所需字符的位置
index = strfind(inputString, desired_char);
if isempty(index)
% 如果未找到所需字符,则第一个子字符串为整个字符串,第二个子字符串为空字符串
first_substr = inputString;
second_substr = '';
else
% 找到所需字符,分割字符串为两个子字符串
split_point = index(1);
first_substr = inputString(1:split_point-1);
second_substr = inputString(split_point:end);
end
end
% 示例用法
inputString = 'we have 6 cars';
desired_char = '6';
[first_substr, second_substr] = split_string(inputString, desired_char);
disp(['第一个子字符串: ' first_substr]);
disp(['第二个子字符串: ' second_substr]);
这段代码将给定的字符串在首次找到所需字符的位置处分割为两个子字符串。如果未找到所需字符,则第一个子字符串为整个字符串,第二个子字符串为空字符串。
例20
Problem 2081. Concatenate strings
concatenate a variable number of input strings to produce one outputstring
将可变数量的输入字符串连接起来生成一个输出字符串。
在MATLAB中,可以使用以下函数将可变数量的输入字符串连接成一个输出字符串:
function outputString = concatenate_strings(varargin)
% 初始化输出字符串
outputString = '';
% 连接所有输入字符串
for i = 1:nargin
outputString = [outputString varargin{i}];
end
end
% 示例用法
str1 = 'Hello, ';
str2 = 'world! ';
str3 = 'How are you?';
output = concatenate_strings(str1, str2, str3);
disp(['输出字符串: ' output]);
这段代码将三个输入字符串连接成一个输出字符串。您可以根据需要提供更多或更少的输入字符串。
例21
Problem 2139. most frequent character
Obtain the most frequent character. For example,
s='balaram'; output='a';If there is a tie between letters, return the first result alphabetically.
获取最频繁的字符。例如,
s='balaram'; output='a'; 如果字母之间存在并列的情况,则返回字母表中首先出现的字母。
function most_frequent_char = get_most_frequent_char(s)
% 初始化变量
max_count = 0;
most_frequent_char = '';
% 遍历字符串中的每个字符
for i = 1:length(s)
% 计算当前字符在字符串中出现的次数
current_count = sum(s == s(i));
% 如果当前字符的出现次数大于已知的最大次数,则更新最频繁字符
if current_count > max_count || (current_count == max_count && s(i) < most_frequent_char)
max_count = current_count;
most_frequent_char = s(i);
end
end
end
% 示例用法
s = 'balaram';
output = get_most_frequent_char(s);
disp(['输出: ' output]);
这段代码将返回给定字符串中最频繁的字符。如果存在并列情况,则返回字母表中首先出现的字母。