1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

From a list of numbers find all the combinations that sum to more than a given number

  1. Sep 20, 2012 #1

    Ryan_m_b

    User Avatar
    Staff Emeritus
    Science Advisor

    This is born out of musings around coalition governments that arise from the party with the most votes not achieving ≥50% of the votes (as opposed to emergency coalitions).

    Taking the figures below how would one go about determining all the possible combinations of parties who combined have >50% of the votes without sitting down and working them out one by one?

    Kid gloves please :redface: I haven't studied maths for the better part of a decade...

    Parties / Percentage of votes

    Pink / 21
    Orange / 19
    Brown / 16
    Blue / 10
    Green / 10
    Tan / 8
    Red / 5
    Black / 4
    Purple / 4
    White / 3
     
  2. jcsd
  3. Sep 20, 2012 #2
    Re: From a list of numbers find all the combinations that sum to more than a given nu

    Brute force my friend !
    Here is a groovy script that answers your question:
    Code (Text):

    def X=[Pink:21, Orange:19, Brown:16, Blue:10, Green:10, Tan:8, Red:5, Black:4, Purple:4, White:3]
    def XS=X.keySet() as List
    def N=XS.size()
    def F; F={ ix,n ->
        def L0=[XS[ix]]
        if(n==1) return [L0]
        def L=[]
        for(def j=ix; j<N-1; j++) {
            F(j+1, n-1).each{ L<<(L0+it) }
        }
        L
    }
    def OK=[:]
    for(def i=0;i<N;i++) {
        for(def j=1;j<=N-i;j++) {
            def c=F(i,j)
            c.each{
                def s=0; it.each { s+=X[it]}
                if(s>50) OK[it]=s
            }
        }
    }
    OK.keySet().sort{x,y->OK[y]<=>OK[x]}.each{ println "$it: ${OK[it]}%" }
     
    I don't post the result since there are 502 winning combinations going all the way from 51% up to 100% :smile:
     
  4. Sep 21, 2012 #3

    Ryan_m_b

    User Avatar
    Staff Emeritus
    Science Advisor

    Re: From a list of numbers find all the combinations that sum to more than a given nu

    Wow thanks a lot! To be honest I'm not really sure how to work code lol but it's good to know that there's a relatively simple way to get it done. Thanks!
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: From a list of numbers find all the combinations that sum to more than a given number
Loading...