【问题标题】:MATLAB randsample in function form函数形式的 MATLAB randsample
【发布时间】:2016-04-28 17:32:37
【问题描述】:

目标是生成六个乐透号码,但显然它们必须是唯一的。不过,这必须以函数形式编写,以下是使用库的等价物:

    (randsample(42,6))' 

我的想法是创建具有所有可能性的向量,通过索引一次选择一个,并且通过在选择下一个之前将其取出来使其无法再次选择。

    function numbers = lottonumbers()

    pool = 1:42;
    numbers = zeros(1,6); 

    for i=1:6
        for j=42-i

            randIndex = round(1+j*rand);
            randNumber = pool(randIndex);
            numbers(i) = randNumber;

            if randIndex==1
                pool = pool(2:end);
            else if randIndex==length(pool)
                pool = pool(1:(end-1));
            else  
                pool = [pool(1:randIndex-1), pool(randIndex+1:end)];
                 end
            end
        end   
     end

由于我在 MATLAB 上很菜鸟(实际上只是编程菜鸟),而且我在提问时自己解决了这个问题,所以我将把它留在这里并向你们征求建议(更好的风格,其他算法...)

【问题讨论】:

    标签: matlab function random-sample


    【解决方案1】:

    乐透基于顺序不发挥作用的排列。

    % p = randperm(n,k) returns a row vector containing k unique integers selected randomly from 1 to n inclusive.
    randperm( 42, 6 )
    

    应该可以解决问题。

    来自代码:“这有时被称为 1:N 的 K 排列或无放回抽样。”

    【讨论】:

      【解决方案2】:

      另一种方法是使用rejection sampling:独立生成数字,如果它们不完全不同,则重新开始。只要数字不完全不同的可能性很小,这是有效的。

      N = 6;
      M = 42;
      done = false;
      while ~done
          result = randi(M,1,N); %// generate N numbers from [1,...,M]
          done = all(diff(sort(result))); %// if all are different, we're done
      end
      

      【讨论】:

        猜你喜欢
        • 2013-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-20
        相关资源
        最近更新 更多