cppitertools icon indicating copy to clipboard operation
cppitertools copied to clipboard

Can I get just the counts from combinations_with_replacement ?

Open thehans opened this issue 6 years ago • 1 comments

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 }

thehans avatar Mar 24 '19 04:03 thehans

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.

ryanhaining avatar Mar 24 '19 17:03 ryanhaining