Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Printing all combinations from a set of sets

  • 03-02-2012 07:28PM
    #1
    Closed Accounts Posts: 638 ✭✭✭


    If i was to print out all combinations of multiple sets of items, it would look like this. But This needs to know how many sets there are.
    set1[1,2,3]
    set2[A,B,C]
    set3[X,Y,Z]
    
    for set1 - i
    { 
    for set2 - y
    {
    for set3 - t
    {
    print set1[i] set2[y] set3[t]
    }
    }
    }
    

    Would this solution work for unknown number of sets(less than 20 so efficency isnt a problem). Its my first recursive but i think it would work.
    HistoricValue = " "
    
    Function(HistoricValue,Sets)
    {
    	if(Sets.length != 0){
    		SingleSet = Sets[0]
    		
    		For each i in SingleSet {
    			
    			var currentValue = HistoricValue + " " + SingleSet[i];
    
    			function(currentValue,Sets.subSet(1,Sets.length));
                    }
    	 }else{
    		print HistoricalValue
    	 }
    }
    


    I've no compiler or dev system on this slow laptop! :)


Comments

  • Registered Users, Registered Users 2 Posts: 218 ✭✭Tillotson


    Something like that should work alright. Just make sure "HistoricValue" doesn't have global scope. Might be better to rename to HistoricValue to currentVal and currentVal to nextVal.

    I decided to just go ahead and do it in Haskell:
    fun = go []
        where
          go acc xss
              | length xss == 0 = [acc]
              | otherwise = concatMap (\x -> go (acc++[x]) (tail xss)) $ head xss
    
    -- fun ["ab", "CDEF", "x"] == ["aCx","aDx","aEx","aFx","bCx","bDx","bEx","bFx"]
    
    
    Another way to think of the problem would be to think of each "Set" as a ring on a combination lock and apply rotations to the rings. The code would probably be 3x as long and it might be difficult to deal with uneven sized "Sets".

    I occasionally use a 6+yr old laptop to program. Unless you're stuck using a Visual Studio / Eclipse you should be alright getting started on just about anything.

    If you're interested in programming/maths problems you should check out projecteuler.net


Advertisement