how to generate random integers without using built-in functions?

4 ビュー (過去 30 日間)
Sarah Sadeq
Sarah Sadeq 2016 年 12 月 5 日
コメント済み: Sarah Sadeq 2016 年 12 月 5 日
Hello,
I'm kind of stuck on this question and I'd appreciate the help.
Write a function permutation that will receive a positive integer n as an input argument. The function will return a vector of size n , where the elements of the vector are the positive integers from 1 to n , in random order. Each number from 1 to n should appear only once. You are required to use the programming method (loops, conditional statements). You are NOT allowed to use the following built-in Matlab functions: perms, randperm, randsample .
My code uses randperm and I don't know how I can write a code without using this builtin function.
Code:
function vec = permutation(n) vec = 1:n; index = 1:n; while any(vec == index); vec = vec(randperm(n)); end
end

採用された回答

Adam
Adam 2016 年 12 月 5 日
doc rand
doc randi
Neither of these are on the list of functions you are not allowed to use and either one of them can be worked into an algorithm to achieve what you are being asked for.

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2016 年 12 月 5 日
Hint: read the randperm source code

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by