Random shuffle of vector elements without repeating
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Antworten (1)
Jan
am 12 Mär. 2016
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 Kommentar
Siehe auch
Kategorien
Mehr zu Numeric Types finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!