Monday, May 24, 2010

Need help fixing my C++ program.?

This is my problem, and my faulty solution is attached bellow.


Write a predicate function





bool same_set(vector%26lt;int%26gt; a, vector%26lt;int%26gt; b)





that checks whether two vectors have the same elements in some order, ignoring multiplicities. For example, the two vectors





1 4 9 16 9 7 4 9 11


and





11 11 7 9 16 4 1





would be considered identical. You will probably need one or more helper functions.











#include %26lt;iostream%26gt;


#include %26lt;vector%26gt;





using namespace std;











bool same_set(vector%26lt;int%26gt; a, vector%26lt;int%26gt; b)


{


int i = 0;


int j = 0;





for (i = 0; i%26lt; a.size(); i++)


{


for (j = 0; j %26lt; b.size(); j++)


{


if (a[i] == b[j])


{


return true;


break;


}


}


}


}





int main()


{


vector%26lt;int%26gt; a(9);


a[0] = 1;


a[1] = 4;


a[2] = 9;


a[3] = 16;


a[4] = 9;


a[5] = 7;


a[6] = 4;


a[7] = 9;


a[8] = 11;





vector%26lt;int%26gt; b(7);


b[0] = 11;


b[1] = 11;


b[2] = 7;


b[3] = 1;


b[4] = 14;


b[5] = 4;


b[6] = 6;








cout %26lt;%26lt; "Vectors a an

Need help fixing my C++ program.?
1- I don't see any way of your same_set function returning false.





2- When you use a return statement, your function ends. It seems to me that your function will end as soon as it finds its first match. So, unless there are no matches, your result will be true. Otherwise, your boolean variable will have garbage in it.





3- Generally speaking, its a bad idea to use break or continue as they violate the top down methodology of coding. Besides, you'll find that they're not really necessary all that often.





What you need is a few lines of code in your outer loop that sets your boolean variable to false if it can't find a match with the inner loop.





Don't use a return statement until you have accounted for the true or false scenario.
Reply:What the above answerer means is:





//Begin function same_set


bool same_set(vector%26lt;int%26gt; a, vector%26lt;int%26gt; b)


{


int i = 0;


int j = 0;


int eq=true, scan; //LEGAL; true is int 1





if(a.size()!=b.size())


return false;





for (i = 0; i%26lt; a.size(); i++)


{


scan=false;


for (j = 0; j %26lt; b.size(); j++)


{


if (a[i] == b[j])


{


scan=true;


break;


}


}


eq=eq%26amp;%26amp;scan;


}


return eq;


}


//End function same_set





Oh, and by the way, even though break and continue technically violate structured programming principles, I still use continue a lot for while controlled loops when the condition needs to be immediately re-evaluated.


No comments:

Post a Comment