Skip to content

Can I get just the counts from combinations_with_replacement ? #56

Open

Description

@thehans

I am interested in using this library to iterate over all "n multichoose k" possibilities for a multiset, but I am representing each set as a simple vector of counts, with length n, where all counts add up to k. Is it possible to extract the counts from your iterators without iterating through each "multiset" itself? I had a peek at the headers but I am a bit lost as to how its working exactly.

So using the provided example for combinations_with_replacement, I would like to get a simple result that would look like:

combinations_with_replacement({1, 2}, 4):
{ 4 0 }
{ 3 1 }
{ 2 2 }
{ 1 3 }
{ 0 4 }

Activity

  1. ryanhaining commented on Mar 24, 2019

    @ryanhaining
    Owner

    Without iterating through at all, I don't think so. With just printing them I have:

    #include "cppitertools/combinations_with_replacement.hpp"
    
    #include <iostream>
    #include <vector>
    
    int main() {
      const std::vector<int> v = {3, 7};
      for (auto &&ns : iter::combinations_with_replacement(v, 4)) {
        std::cout << "{ ";
        for (auto i : v) {
          std::cout << std::count(ns.begin(), ns.end(), i) << ' ';
        }
        std::cout << "}\n";
      }
    }

    For one object that you can iterate through:

    #include "cppitertools/combinations_with_replacement.hpp"
    #include "cppitertools/imap.hpp"
    
    #include <iostream>
    #include <vector>
    
    int main() {
      const std::vector<int> v = {3, 7};
    
      auto counts = iter::imap([&v](auto&& ns) {
          return iter::imap([&ns](auto i) {
              return std::count(std::begin(ns), std::end(ns), i);
          }, v);
      }, iter::combinations_with_replacement(v, 4));
    
      // then to iterate over it and display
      for (auto&& c : counts) {
        std::cout << "{ ";
        for (auto i : c) {
          std::cout << i << ' ';
        }
        std::cout << "}\n";
      }
    }

    The above still iterates through it with the call to std::count of course.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions