Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

matlab - 在MATLAB中打印n个选择k个组合(Printing n choose k combinations in matlab)

I need to create an algorithm in matlab which returns any combination of n subset from the k set.

(我需要在matlab中创建一个算法 ,该算法从k集返回n个子集的任意组合。)

For example I have a set {1,2,3,4,5} and I need any combination of 3 numbers included in this set.

(例如,我有一个{1,2,3,4,5}集合,并且需要此集合中包含的3个数字的任意组合。)

So this function should returns:

(因此,此函数应返回:)

[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]

([[1、2、3],[1、2、4],[1、2、5],[1、3、4],[1、3、5],[1、4、5],[ 2,3,4],[2,3,5],[2,4,5],[3,4,5]])

I have tried to write it by myself, but unsuccesfully and I give up.

(我试图自己写它,但是没有成功,我放弃了。)

It partially works, but it creates endless loop.

(它部分起作用,但会产生无限循环。)

    for i=1:n
    if(firstTime)
        lastComb=min //123
        firstTime=false
    else
      for d=k:-1:1 
        while(lastComb(:,end) < n-k+d && lastComb(:,end)<=n)
            newComb=lastComb
            newComb(d)=lastComb(d)+1
          combos= [combos; newComb] 
          lastComb=newComb
        end
         while(lastComb(:,end) > n-k+d && lastComb(:,end)<=n)
            newComb=lastComb
            for p=d:-1:1 

         if(newComb(p)+1 <=n)
        newComb(p)=newComb(p)+1 
        combos= [combos; newComb]
         end
     end
        end
      end
    end
end
  ask by user5890114 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...