Random shuffle of vector elements without repeating

조회 수: 7 (최근 30일)
Janell Lopez
Janell Lopez 2016년 3월 12일
댓글: Janell Lopez 2016년 3월 12일
For my class, I have to create an anagram-type function that receives an input string, shuffles all the elements, and returns a new string of the shuffled letters. We are to use for loops and if statements; we can't use perms, randperm, or randsample. I have a good start on this:
outstr=zeros(size(instr));
for i=1:numel(instr)
outstr(randi([1,numel(instr)]))=instr(randi([1,numel(instr)]));
end
char(outstr)
My question is how to avoid repetition. Right now my function works, but it will repeat elements and thus leave some out. I'm thinking an if statement, to compare the randomly selected index to what has already been selected, but I can't pound it out yet. Any help is appreciated.

답변 (1개)

Jan
Jan 2016년 3월 12일
You can sort a vector of random values. The sorting index does not contain repetitions.
Did you search for a shuffle algorithm in the internet already? Look for "Knuth" and "Yates".
  댓글 수: 1
Janell Lopez
Janell Lopez 2016년 3월 12일
This is what I see for Yates:
function shuffle(array) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
I'm not familiar with Javascript--what would the likenesses be for my instr and outstr? How can I divide up this code for a function with input/output arguments?
Thank you!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by