CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 19

Threaded View

  1. #12
    Join Date
    Jun 2015
    Posts
    208

    Re: How to distribute a value into vector

    Quote Originally Posted by Ramees219 View Post
    I didn't use the zero combination because i need this code run faster
    But since #post 10 i realized its still take lost of time on big value
    So redesign my algorithm now i don't want zero combination and dual character in one array like .10, 11, 12 .. so on
    For example
    Slots = 3
    Sum = 17
    Have you noticed my post #11?

    Say we have V=3 (slots) and D= 17 (sum).

    Just use V=3 and D=D-V = 17-3 = 14. Then run Gosper's hack with those values and add 1 to each number in every output combination, like,

    Code:
    void test() {
    	int V = 3; // vector size
    	int D = 17-V; // modified sum
    
    	const BitSet ONE = BitSet(1);
    	BitSet your_start = (ONE << (V + D - 1)) | ((ONE << (V - 1)) - ONE);
    
    //	std::cout << "Expected number of combinations: " << bs_binominal(V+D-1, V-1) << std::endl;
    
    	long long int c = 0; // counter
    	for (BitSet x = your_start; x < gosper_limit<BitSet>(V + D); x = gosper_next<BitSet>(x)) {
    		VecSet v = bs_0vector(x);
    		for (auto& n : v) ++n; // add on 1 to each number in VecSet
    		std::cout << bs_0string(v) << std::endl;
    		++c;
    	}
    	std::cout << "Actual number of combinations = " << c << std::endl;
    }
    I generates exactly the 120 combinations you are looking for, nothing more nothing less.

    So Gosper's hack now can be used to very efficiently produce the result you wanted. The D+V <= 62 limit is still there of course but since I too am interested in an unlimited algorithm for this I'll post my own replacement for Gosper's hack anytime soon.
    Last edited by tiliavirga; March 1st, 2016 at 02:10 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured