word scrambler script
4 次查看(过去 30 天)
显示 更早的评论
So I am supposed to write a script that scrambles the letters in a word with the exception of the first and last letter and keep the punctuation intact. so the word "couldn't" should reproduce something along the lines of "cldnuo't".
This is my script so far but I do not understand why it does not work. function out = scrambleWord(in)
if length(in) > 3
n = nnz(in);
ri = randperm(n);
ri(ri == max(ri)) = [];
ri(ri == min(ri)) = [];
if isletter(in) ~= 1
in2 = in
o = isletter(in) ~= 1
in(o) = []
in2(1:(find(o)-1)) = in(1:(find(o))-1)
in2((find(o)+1):end) = in((find(o)):end)
out = in2
end
in(2:(n-1)) = in(ri);out = in
out= in
else out = in;
end
end
1 个评论
Walter Roberson
2011-3-1
If the word ends in punctuation (which can happen with some possessive forms), then is the letter before the punctuation the "last letter" ? If so then you need to adjust the way you remove the first and last letter in your ri() = [] statements.
回答(3 个)
Jan
2011-3-1
The question sound very similar to:
Please look there for a answers also. An short method to solve your problem:
word = 'couldn''t';
isPunct = ismember(word, '.,-:;''');
cleaned = word(~isPunct);
newWord(~isPunct) = cleaned(randperm(length(cleaned)));
0 个评论
Matt Fig
2011-3-1
I suspect the problem comes from your (seeming) assumption that the code inside the IF statement only operates on those elements of an array which pass its conditional. That is a false assumption.
When an array is passed to an IF statement, the body of the IF statement is only executed if ALL elements of the vector are true. Try this:
if ([1 0]),disp('inif 1'),end
if ([1 1]),disp('inif 2'),end
To operate only on the elements of an array for which a condition is true, use logical indexing instead. For example:
x = [0 1 4 0 3 0];
idx = x>0; % A logical index.
x(idx) = -9 % Set only the values in the index to -9.
If there are differences between how you treat certain subgroups of the logical index, you may have to make two passes, or simply use a FOR loop and an IF statement to deal with each element one at a time.
0 个评论
Matt Tearle
2011-3-1
Is this a homework problem? Without wanting to do the whole thing for you, let me suggest an approach that works:
- Use the approach Jan & I showed here to strip and replace punctuation.
- Instead of just doing randperm, scramble the letters within the words by splitting into words using regexp. See example 4 "splitting the input string" in the doc for regexp.
- Loop through the resulting cell array of words, extract and scramble the 2:end-1 letters. randperm works well for the scrambling.
- Reassemble the string (again, see example 4 in the regexp doc).
- Reinsert the punctuation (see #1).
I have this working in about a dozen lines of code.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!