Randomly scramble letters in a single word

2 ビュー (過去 30 日間)
PenguinForce
PenguinForce 2016 年 10 月 24 日
編集済み: Vegard Hansen 2019 年 3 月 20 日
So I am trying to create a function that would take in a word when the function is called and then randomly scramble the letters within it and return that new "word" back. I am trying not to use perms, randperm or randsample as I am trying to practice while loops. A friend suggested I try this challenge out but after working on it for many hours without success, I'm trying to see if this is actually possible, and if anyone can actually get a function with an input and output to work. I don't have much to show for the code used so far as a large portion of it I accidentally deleted. I am a self taught learner.
function output = scramble(input)
X = size(input);
while X > 0
idx = randi([1 X]);
A(idx) = A(idx) + 1 ;
output = X-1;
end

採用された回答

Jan
Jan 2016 年 10 月 24 日
Some suggestions:
function output = scramble(input)
Do not use the term "input" as name of a variable, because this is an important Matlab function.
X = size(input);
Now X is a vector. Better use numel or length.
while X > 0
X does not change its value inside the loop. Therefore the loop will run infinitely.
idx = randi([1 X]);
Keep code as simple as possible. Better:
idx = randi(X);
The purpose of the next two lines is not clear to me:
A(idx) = A(idx) + 1 ;
output = X-1;
Together:
function output = scramble(in)
n = numel(in);
out = repmat(' ', 1, n); % Pre-allocation
while n > 0
idx = randi(n);
out(k) = in(idx);
in(idx) = [];
n = n - 1;
end
The iterative shrinking of the input array is a bad programming pattern and if the input is large (e.g. millions of characters), this will waste time. There are better methods for scrambling, search for "Fisher Yates Shuffle" or "Knuth Shuffle" in the net. This is the algorithm implemente in randperm when called with 2 inputs.
  1 件のコメント
PenguinForce
PenguinForce 2016 年 10 月 26 日
Thanks for the resources. I will definitely check them out!

サインインしてコメントする。

その他の回答 (2 件)

Massimo Zanetti
Massimo Zanetti 2016 年 10 月 24 日
編集済み: Massimo Zanetti 2016 年 10 月 24 日
No need of while. If you want to permute word letters with forced use of a loop, extract one-by-one the letters from word without replacement:
x='matlabthebest';
y=char(size(x));
for k=1:numel(x)
[y(k),idx] = datasample(x,1,'Replace',false);
x(idx)=[];
end
%result
y

Vegard Hansen
Vegard Hansen 2019 年 3 月 20 日
編集済み: Vegard Hansen 2019 年 3 月 20 日
I found this by accident, but it works.
prompt = input(['Word of your choice:\n'],'s');
lengde = length(prompt);
rnd = randperm(lengde)
prompt(rnd)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by