Knuth Shuffle key-based
2 views (last 30 days)
Show older comments
Zeeshan Abbas
on 1 Jul 2019
Answered: Zeeshan Abbas
on 4 Jul 2019
I have this code of Knuth-Shuffle Algo in forward direction as below (Matlab):
X=[1 2 3 4 5 6];
n = numel(X);
for i = 2:n % Knuth shuffle in forward direction:
w = ceil(rand * i); % 1 <= w <= i
t = X(w);
X(w) = X(i);
X(i) = t;
end
I want to make it key dependent. i.e. whenever I change the key, the algorithm should give a different permutation.
Accepted Answer
More Answers (1)
Steven Lord
on 1 Jul 2019
You want to control the random number generator, to allow you to generate random numbers repeatably? Use the rng function as shown on this documentation page.
3 Comments
Steven Lord
on 1 Jul 2019
What's the role of this KEY in permuting X? You want to control which elements get swapped? That requires controlling the value of w, which requires controlling the output of rand, which is exactly what rng does.
By the way, two ways in which your code can be made shorter:
- Rather than calling ceil(rand*i), consider using the randi function. It is designed specifically to return integer values.
- You don't need to use a temporary value to swap. You can use indexing.
sampledata = 1:10
valuesToSwap = [4 7];
sampledata(valuesToSwap) = flip(sampledata(valuesToSwap))
% or
sampledata(valuesToSwap) = sampledata(flip(valuesToSwap))
If you run both of the last two lines of code in that example, sampledata will be back to 1:10 since you will have swapped elements 4 and 7 twice.
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!