[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Randomly generate 10 different integers
From: |
Jaroslav Hajek |
Subject: |
Re: Randomly generate 10 different integers |
Date: |
Thu, 17 Sep 2009 08:08:38 +0200 |
On Wed, Sep 16, 2009 at 12:22 PM, Dupuis <address@hidden> wrote:
>
>
>
> Xin Dong wrote:
>>
>> Hi,
>>
>> I wanna randomly generate 10 different integers in a given range. I know I
>> can use random function and discard duplicate values. But is there any
>> other
>> simple way to do it?
>>
>>
>
> What you're searching for is an implementation of the Fisher-Yates
> algortihm, see http://en.wikipedia.org/wiki/Fisher–Yates_shuffle
>
> Here is a possible way:
> x=(1:10); n = length(x);
> while n >= 2,
> t = ceil(unifrnd(0, n)); %# returns 1 <= t <= n
> if (n != t), dummy = x(n); x(n) = x(t); x(t) = dummy; endif %# permute
> n = n - 1;
> endwhile
> --
Btw., in current tip, randperm is a compiled function and implements
the Fisher-Yates (Knuth) shuffle. It can also produce a set of
permutations at once.
--
RNDr. Jaroslav Hajek
computing expert & GNU Octave developer
Aeronautical Research and Test Institute (VZLU)
Prague, Czech Republic
url: www.highegg.matfyz.cz