Info
この質問は閉じられています。 編集または回答するには再度開いてください。
Need Some Help Formatting a Function Output Using Count
1 回表示 (過去 30 日間)
古いコメントを表示
I'm using MATLAB to make a word scramble that scrambles the inner letters of every word in a sentence, leaving the first and last letter of each word in their respective places. I'm trying to figure out how to format this function so that if the user enters more than 10 words, the function will use a count to put the rest of the words on the next line down. Also, this function won't allow me to use two letter words (I assume because there is no "middle" letter in the word to pass through my function), and I was wondering how I can make my function work with two letter words. Here's what I have so far:
function outword= wordScramble(my_sentence)
while ~isempty(my_sentence)
[my_word,my_sentence] = strtok(my_sentence);
len = length(my_word);
first_letter = my_word(1);
last_letter = my_word(end);
input_word = my_word(2:end-1);
len = length(input_word);
in_vec = zeros(1,len);
in_vec(1) = randi([1 len]);
for i = 2:len
ran = randi([1 len]);
while any(in_vec(1:i-1) == ran)
ran = randi([1,len]);
end
in_vec(i) = ran;
end
inner_letters = input_word(in_vec);
outword = strcat(first_letter,inner_letters,last_letter);
fprintf('%s ',outword)
end
fprintf('\n')
end
3 件のコメント
dpb
2020 年 4 月 30 日
Well, think thru the problem...you start by getting a word, then the very next thing your code does is find out how long it is. Wouldn't right there be the place to make the decision on what to do depending on the length? Looks like to me... :)
BTW, if the length is four characters, there's only one permutation you can make and odds are 50:50 on a random choice you'll return the same sequence as you started with so you might want to special case it as well and just swap the two inner letters.
And, of course, with 5 or more, there's still a finite chance the random order could be the same as the initial altho odds go down pretty quickly as the number grows. Whether you want to build in the logic to make sure your return isn't the same is probably added credit...
>> input_word='machine';
>> len=numel(input_word);
>> input_word(2:end-1)=input_word(randperm(len-2))
input_word =
'mhmacie'
>>
回答 (0 件)
この質問は閉じられています。
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!