473,837 Members | 1,550 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

recursion in combinations

Hi

I came up with this code which prints out all combinations as in
"c_choose_k "
so, if we have a vector of char abcdef, and we want all combinations
with 3 elements only, we make the 3 for loops as below,
>>>>>>>>>>>>>>> code <<<<<<<<<<<<<<< <
int main(){
vector<strings;
s.push_back("1" );
s.push_back("2" );
s.push_back("3" );
s.push_back("4" );
s.push_back("5" );
s.push_back("6" );

for(unsigned p=0; p<s.size(); p++){
for(unsigned q=p+1; q<s.size(); q++)
for(unsigned r=q+1; r<s.size(); r++)
cout << s[p]
<< s[q]
<< s[r]
<< endl;
}
}

I am thinking to generalize it and make it more flexible, so that it
takes n and k and puts out a vector<vector<i nt each vector<int>
contains the combined elements and the main vector contains all the
combination vectors.
i.e
n = 3
k = 2
vector<int>.siz e() == k "2 in this case"
vector<vector<i nt .size() == n_choose_k "3" in this case
here, 3 is the number of combinations, and 2 is the number of digits
in each of the "k"
12
13
23
n = 6
k = 3
vector<int>.siz e() == k "3 in this case"
vector<vector<i nt .size() == n_choose_k "20 in this case"
so that the vector of vector looks like
123
124
125
126
134
135
136
145
146
156
234
235
236
245
246
256
345
346
356
456

so instead of feeding a vector of values to the routine, I can just
use the first argument "n" as an index representation of the number of
elements need to be combined, then use this index to get the element
combination in the client code.

I tried to do it recursively but need some help. I was thinking

vector<vector<i nt>n_choose_k(i nt n, int k){
static int nn = n;
vector<intvk;
vector<vector<i nt>vn;
int a = nn==n ? 0 : n+1;
for(int i=a; i<n; i++)
unsigned kk -= k;
ok, I am just scratching my head here...
vector.push_bac k(something) some where .. i give up
thanks
Aug 30 '06 #1
7 7193
Can you take a look at the code snippet pasted below:

////////////////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

typedef std::vector<std ::vector<int::i terator ITER;

void GetResults(int n,
int k,
int start,
std::vector<std ::vector<int &results
)
{

if (k == 1)
{
for (int i = start; i <= n; i++)
{
std::vector<int tmp;
tmp.push_back(i );
results.push_ba ck(tmp);
}
return;
}

for (int i = start; i <= n; ++i)
{

std::vector<std ::vector<int tmp;
GetResults(n, k-1, i+1, tmp);

ITER iterEnd = tmp.end();
for (ITER iter = tmp.begin(); iter != iterEnd; ++iter)
{
std::vector<int vSeq;
vSeq.push_back( i);

std::copy(iter->begin(), iter->end(), std::back_inser ter(vSeq));
results.push_ba ck(vSeq);
}
}
}

std::vector<std ::vector<int N_Choose_K(int n, int k)
{
std::vector<std ::vector<int vResult;
if (k 0 && k <= n)
{
GetResults(n, k, 1, vResult);
}
return vResult;
}

int main()
{
std::vector<std ::vector<int vResults = N_Choose_K(6, 3);

ITER iterEnd = vResults.end();
for (ITER iter = vResults.begin( ); iter != iterEnd; ++iter)
{
std::copy(iter->begin(), iter->end(),
std::ostream_it erator<int>(std ::cout, " "));
std::cout << std::endl;
}
std::cout << "Count = " << vResults.size() << std::endl;
return 0;
}
///////////////////////////////////////////////////////////////////////

Aug 30 '06 #2
Is this a homework assignment?

------------------------------------------------
Bumperstickers: http://www.cafepress.com/bush_doggers?pid=2794571

Gary Wessle wrote:
Hi

I came up with this code which prints out all combinations as in
"c_choose_k "
so, if we have a vector of char abcdef, and we want all combinations
with 3 elements only, we make the 3 for loops as below,
>>>>>>>>>>>>>>c ode <<<<<<<<<<<<<<< <
int main(){
vector<strings;
s.push_back("1" );
s.push_back("2" );
s.push_back("3" );
s.push_back("4" );
s.push_back("5" );
s.push_back("6" );

for(unsigned p=0; p<s.size(); p++){
for(unsigned q=p+1; q<s.size(); q++)
for(unsigned r=q+1; r<s.size(); r++)
cout << s[p]
<< s[q]
<< s[r]
<< endl;
}
}

I am thinking to generalize it and make it more flexible, so that it
takes n and k and puts out a vector<vector<i nt each vector<int>
contains the combined elements and the main vector contains all the
combination vectors.
i.e
n = 3
k = 2
vector<int>.siz e() == k "2 in this case"
vector<vector<i nt .size() == n_choose_k "3" in this case
here, 3 is the number of combinations, and 2 is the number of digits
in each of the "k"
12
13
23
n = 6
k = 3
vector<int>.siz e() == k "3 in this case"
vector<vector<i nt .size() == n_choose_k "20 in this case"
so that the vector of vector looks like
123
124
125
126
134
135
136
145
146
156
234
235
236
245
246
256
345
346
356
456

so instead of feeding a vector of values to the routine, I can just
use the first argument "n" as an index representation of the number of
elements need to be combined, then use this index to get the element
combination in the client code.

I tried to do it recursively but need some help. I was thinking

vector<vector<i nt>n_choose_k(i nt n, int k){
static int nn = n;
vector<intvk;
vector<vector<i nt>vn;
int a = nn==n ? 0 : n+1;
for(int i=a; i<n; i++)
unsigned kk -= k;
ok, I am just scratching my head here...
vector.push_bac k(something) some where .. i give up
thanks
Aug 30 '06 #3
de********@yaho o.com writes:
Is this a homework assignment?

No, it is NOT a homework assignment.
Aug 31 '06 #4
Gary Wessle wrote:
Hi

I came up with this code which prints out all combinations as in
"c_choose_k "
so, if we have a vector of char abcdef, and we want all combinations
with 3 elements only, we make the 3 for loops as below,
[snip]

There are easier way to do this. One option is to take advantage of the
standard library function next_permutatio n defined in the standard
header <algorithm>. Start with a "mask" vector such as:

0 0 0 0 0 1 1 1

Repeatedly apply next_permutatio n to this vector until the function
returns false. For each mask, including the first, pick out the
elements of the input vector that correspond to a '1' in the mask.

The example above gives 8C3, by changing the length of the mask (n) and
the number of ones (m), you can get nCm.

Mark
Aug 31 '06 #5
Mark P wrote:
[snip]

There are easier way to do this. One option is to take advantage of
the standard library function next_permutatio n defined in the standard
header <algorithm>. Start with a "mask" vector such as:

0 0 0 0 0 1 1 1

Repeatedly apply next_permutatio n to this vector until the function
returns false. For each mask, including the first, pick out the
elements of the input vector that correspond to a '1' in the mask.

The example above gives 8C3, by changing the length of the mask (n)
and the number of ones (m), you can get nCm.
I think this would give repeated patterns. For example, swapping the
last 1 with the one-before-last 1 is a different permutation (of this
vector), but not a different combination.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 31 '06 #6
Victor Bazarov wrote:
Mark P wrote:
>[snip]

There are easier way to do this. One option is to take advantage of
the standard library function next_permutatio n defined in the standard
header <algorithm>. Start with a "mask" vector such as:

0 0 0 0 0 1 1 1

Repeatedly apply next_permutatio n to this vector until the function
returns false. For each mask, including the first, pick out the
elements of the input vector that correspond to a '1' in the mask.

The example above gives 8C3, by changing the length of the mask (n)
and the number of ones (m), you can get nCm.

I think this would give repeated patterns. For example, swapping the
last 1 with the one-before-last 1 is a different permutation (of this
vector), but not a different combination.

V
Not so. next_permutatio n will yield a lexicographical ly greater
ordering of the input sequence if one exists, or return false if none
exists. If you think about it for a minute, I think you'll see that it
must behave in this way, otherwise it would have no way to keep track of
its "position". That is, how can it know whether it's at the first
occurrence of 0 1 1 or the second such occurrence, given that the input
is merely a pair of iterators?

// Example: prints the 10 permutations of {0,0,1,1,1}

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>

using namespace std;

int main ()
{
int data[] = {0,0,1,1,1};
vector<intdata_ vec( data, data + sizeof(data)/sizeof(data[0]));

do
{
copy( data_vec.begin( ), data_vec.end(),
ostream_iterato r< int>( cout, " "));
cout << endl;
}
while( next_permutatio n( data_vec.begin( ), data_vec.end()) );
}

-Mark
Aug 31 '06 #7
Mark P wrote:
Victor Bazarov wrote:
>Mark P wrote:
>>[snip]

There are easier way to do this. One option is to take advantage of
the standard library function next_permutatio n defined in the
standard header <algorithm>. Start with a "mask" vector such as:

0 0 0 0 0 1 1 1

Repeatedly apply next_permutatio n to this vector until the function
returns false. For each mask, including the first, pick out the
elements of the input vector that correspond to a '1' in the mask.

The example above gives 8C3, by changing the length of the mask (n)
and the number of ones (m), you can get nCm.

I think this would give repeated patterns. For example, swapping the
last 1 with the one-before-last 1 is a different permutation (of this
vector), but not a different combination.

V

Not so. next_permutatio n will yield a lexicographical ly greater
ordering of the input sequence if one exists, or return false if none
exists. [..]
My bad. For some reason (incorrectly) I thought (what was I thinking?)
that next_permutatio n doesn't depend on the sequence...

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Sep 1 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3426
by: Peri | last post by:
I'm trying to create Python parser/interpreter using ANTLR. Reading grammar from language refference I found: or_expr::= xor_expr | or_expr "|" xor_expr For me it looks like infinite recursion. And so it says ANTLR. Maybe I don't understand EBNF notation. For me it should look like this. or_expr::= xor_expr | xor_expr "|" xor_expr and in ANTLR grammar file like this:
20
3135
by: drs | last post by:
Hi, I am trying to find all lists of length x with elements a, b, and c. To this end, I have created the class below, but it is not quite working and I am having trouble figuring out what to change. Does anyone have any insight? class c: def __init__(self): self.traits = 4 # number of list elements self.types = 3 # elements can be 0, 1, or 2
12
2771
by: da Vinci | last post by:
Greetings. I want to get everyone's opinion on the use of recursion. We covered it in class tonight and I want a good solid answer from people in the "know" on how well recursion is accepted in modern day applications. Should we readily use it when we can or only when absolutly forced to use it?
36
9492
by: rbt | last post by:
Say I have a list that has 3 letters in it: I want to print all the possible 4 digit combinations of those 3 letters: 4^3 = 64 aaaa
43
4181
by: Lorenzo Villari | last post by:
I've tried to transform this into a not recursive version but without luck... #include <stdio.h> void countdown(int p) { int x;
75
5652
by: Sathyaish | last post by:
Can every problem that has an iterative solution also be expressed in terms of a recursive solution? I tried one example, and am in the process of trying out more examples, increasing their complexity as I go. Here's a simple one I tried out: #include<stdio.h> /* To compare the the time and space cost of iteration against
18
3728
by: MTD | last post by:
Hello all, I've been messing about for fun creating a trial division factorizing function and I'm naturally interested in optimising it as much as possible. I've been told that iteration in python is generally more time-efficient than recursion. Is that true? Here is my algorithm as it stands. Any suggestions appreciated!
20
3010
by: athar.mirchi | last post by:
..plz define it.
35
4750
by: Muzammil | last post by:
int harmonic(int n) { if (n=1) { return 1; } else { return harmonic(n-1)+1/n; } } can any help me ??
0
10902
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10583
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10642
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9420
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7824
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7013
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5863
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4481
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3128
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.