choose k items from a set of x and y to meet certain criteria

坚强是说给别人听的谎言 提交于 2019-12-13 07:17:04

问题


I have given x and y items , I need to choose some x and some y with some constrain say x < 10 and y < 5 and the total number should be p.

How to solve such problem. Algorithm/ mathematical technique.


回答1:


The trick is we only need to go through one array (e.g. the x_array), and we can work out y using p-x=y. Now we only need to ensure y is in the y_array and we know we have our answer. To ensure y is in the y_array, we make a set or binary search tree for fast look-ups.

Here is some python code:

p=13
xs=[1,3,99,9,18]
ys=[10,4,33]

y_set=set(ys)

#y=p-x
results=((x,p-x) for x in xs if x<10 and p-x<5 and p-x in y_set)

print "x=%s,y=%s,p=13" % results.next()
'x=9,y=4,p=13'



回答2:


Are you trying to do something like this:

void main(void) {
     int x[] = {3, 5, 7, 10}
    int y[] = {5, 9, 12, 23}
    int i=0, j=0;
        for(i=0; i<4; i++)
        {
        for(j=0; j<4; j++)
        {
            if (x[i]<10 && y[j]<5)
            {
                if(x[i]+y[j]==p)
                {
                    //do something
                }
            }
        }
    }
}



回答3:


The fastest algorithm I know will be :

  1. Let m be the maximum of your constraints, and z the items constrained by m. In your case m = 10, z = x. This is because as m grows, p - m decreases.
  2. I assume your items are generic. Create a map and associate the key p - z[i].value() to z[i]
  3. Take each item obj in the other list (in your case y), and look if obj.value() is a key of your map. If it is, save both obj.value() and map[obj.value()]

Using the property of retrieving in a map in constant time O(1), you have an algorithm which run in O(sizeof(x)+sizeof(y))



来源:https://stackoverflow.com/questions/9373450/choose-k-items-from-a-set-of-x-and-y-to-meet-certain-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!