首页 > 解决方案 > SAS中不重复的随机数生成

问题描述

我试图在不重复的情况下获得随机数生成。我的想法是进行 5 次循环。在里面我会得到随机数,将它存储在表中,并在每次迭代时检查选择的数字是否在表中,然后确定这个随机选择是否是重复的。

这是我的代码,我尝试执行我的想法,但是出了点问题,我不知道我在哪里犯了错误。

data WithoutRepetition;
counter = 0;
array temp (5)  _temporary_;
do while(1);
    rand=round(4*ranuni(0) +1,1);

    if counter = 0 then 
    do;
        temp(1) = rand;
        counter=counter+1;
        output;
        continue;
    end;    

    do a=1 to counter by 1;      
        if  temp(a) = rand then continue ;   
    end; 
        temp(counter) = rand;
        output;
        counter=counter+1;
        if counter = 5 then do; 
            leave;
        end;  
end;    
run;

标签: sas

解决方案


听起来你想要一个随机排列。

165  data _null_;
166     seed=12345;
167     array r[5] (1:5);
168     put r[*];
169     call ranperm(seed,of r[*]);
170     put r[*];
171     run;

1 2 3 4 5
5 1 4 3 2

这是您正在尝试做的事情的简化版本。

data WithoutRepetition;
   i=0;
   array temp[5];
   do r=1 by 1 until(i eq dim(temp));
      rand=round(4*ranuni(0)+1,1);
      if rand not in temp then do; i+1; temp[i]=rand; end;
      end;
   drop i rand;
   run;

在此处输入图像描述


推荐阅读