Knuth Shuffle key-based

조회 수: 1 (최근 30일)
Zeeshan Abbas
Zeeshan Abbas 2019년 7월 1일
답변: Zeeshan Abbas 2019년 7월 4일
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.
  댓글 수: 1
darova
darova 2019년 7월 1일
waitforbuttonpress and waitfor?

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

채택된 답변

Zeeshan Abbas
Zeeshan Abbas 2019년 7월 4일
X=[1:1:m];
n = numel(X);
key = 2538 %Just for example as it will be decided at run time
for i = 1:n % Knuth shuffle in forward direction: 1:n
w = mod(ceil((any fixed value) * key * i),m);
t = X(w+1);
X(w+1) = X(i);
X(i) = t;
end

추가 답변 (1개)

Steven Lord
Steven Lord 2019년 7월 1일
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
Steven Lord
Steven Lord 2019년 7월 1일
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:
  1. Rather than calling ceil(rand*i), consider using the randi function. It is designed specifically to return integer values.
  2. 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.
Zeeshan Abbas
Zeeshan Abbas 2019년 7월 2일
Thanks Steven. Actually I need not to use rand function that's why I have put a fixed value over there and taken mod. It's wroking fine now.
Here is the code below. Please, let me know if you find something wrong in it.
X=[1:1:202500];
n = numel(X);
key = 2538 %Just for example as it will be decided at run time
for i = 1:n % Knuth shuffle in forward direction: 1:n
w = mod(ceil(0.387 * key * i),202500);
t = X(w+1);
X(w+1) = X(i);
X(i) = t;
end

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by