1 Replies - 1316 Views - Last Post: 08 February 2009 - 02:36 AM Rate Topic: -----

#1 felixer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 07-February 09

Subsets of an Integer HELP

Posted 07 February 2009 - 08:48 PM

I need help in my Discrete class. The assignment is to accept any integer as input and print all subsets of that integer plus an empty set. So if someone inputed a 3 then all the subsets would be {}, {1}. {2}. {3}. {1,2},{1,3},{2,3},{1,2,3}.

I'm having some problems figuring out how to do this. I dont know how to use bit masking techniques. Ive tried everything i could and i went back to what i originally had as code so you guys could possibly help me out.

Also, i have figured out a way to do it if i initialize the array with the full set, but he said that this is not accepted. You must generate a set after an integer is given.

What i have thus far(it prints off every set for 3 but 2 of them):
int main(){
int* set = NULL; //Initializes a dynamically allocated array, allowing user input to set size.
int NUM; //The natural integer number that will determine size of array.

cout << "Enter any natural integer: ";
cin >> NUM;
cout << endl << endl;
set = new int [NUM];

cout << "All possible subsets for " << NUM << ": " << endl; 

for(int i = 1; i <= NUM; i++) //Prints off the original single-digit subset
{
	set[i] = i;
	cout << "{ " << set[i] << " }" << endl;
}


for( int i = 0; i <= NUM+1; i++ ) 
{ 
cout << "{ "; 
for( int j = 0; j < NUM+1; j++ ) 
{ 
if( (i < j)) { cout << set[j] << " "; } 
} 
cout << "}" << endl; 
} 

return 0;
} //End of Main


Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: Subsets of an Integer HELP

#2 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 280
  • View blog
  • Posts: 1,787
  • Joined: 20-September 08

Re: Subsets of an Integer HELP

Posted 08 February 2009 - 02:36 AM

Have you thought about using recursion ?

1:
{},{1}

2:
{},{1},{2}
{1,2}

3:
{},{1},{2}, {3}
{1,2}, {1,3}, {2,3}
{1,2,3}

4:
{},{1},{2}, {3},{4}
{1,2}, {1,3}, {1,4},{2,3}, {2,4},{3,4}
{1,2,3},{1,2,4},{2,3,4}
{1,2,3,4}

5: ...
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1