Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can I get just the counts from combinations_with_replacement ? #56

Open
thehans opened this issue Mar 24, 2019 · 1 comment
Open

Can I get just the counts from combinations_with_replacement ? #56

thehans opened this issue Mar 24, 2019 · 1 comment
Labels

Comments

@thehans
Copy link

thehans commented Mar 24, 2019

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 }
@ryanhaining
Copy link
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
Labels
Projects
None yet
Development

No branches or pull requests

2 participants