Simple Recursion problem
Apr 19, 2014 at 10:49pm UTC
Ok, so I have this assignment where i have to create a program that takes in input for the length of string and amount of ones and produce an ordered output for the ones and length...
i.e.
UNIX>enum 3 1
001
010
100
or
UNIX>enum 2 1
01
10
where the input is enum (length) (amount of ones)
Well all i can do through recursion is the very first output before it goes away. and when i do fit in more than one line, it seg faults at the second line.. i.e
UNIX>enum 3 1
001
010
Seg Fault()
Can Anyone help me???
here is my code for the class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
class Enum
{
public :
Enum(int );
int do_enumeration(int , int );
int ones;
protected :
string word;
int lenth;
int zero;
};
Enum::Enum(int size)
{
lenth = size;
word = "" ;
for (int i = 0; i < size; i++)
{
word+= '0' ;
}
ones = 0;
zero = 0;
}
int Enum::do_enumeration(int index, int number)
{
if (index == lenth && zero == (lenth - ones))
{
cout << word << endl;
return 0;
}
else
{
if (zero < lenth - ones)
{
zero++;
word[index] = '0' ;
do_enumeration(index + 1, number);
//number++;
//zero--;
}
if (number != 0)
{
word[index] = '1' ;
do_enumeration(index + 1, number - 1);
number++;
word[index] = '0' ;
}
}
return 0;
}
I'm new here so i don't know if this is appropriate or in the proper manner. so i apologize if its incorrect
the commented out code is what i put in to have two lines of output before seg fault
Last edited on Apr 19, 2014 at 10:50pm UTC
Apr 19, 2014 at 11:05pm UTC
I got it figured out guys, but that brings on a different question... Why does it work?? and is there a more intelligent way of doing it?
here is my solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
int Enum::do_enumeration(int index, int number)
{
if (index == lenth && number == 0)
{
cout << word << endl;
return 0;
}
else
{
if (zero < lenth - ones)
{
zero++;
word[index] = '0' ;
do_enumeration(index + 1, number);
//number++;
zero--;
}
if (number != 0)
{
word[index] = '1' ;
do_enumeration(index + 1, number - 1);
number++;
word[index] = '0' ;
}
}
return 0;
}
Thanks ahead of time
Topic archived. No new replies allowed.