Background: Each array represents a mathematical set (in this case, a lottery ticket). The inSet function should see if the element passed to it is in the set (obviously).
I have created numerous dummy cout statements in order to see if it is iterating and/or if my function can accurately relay when it is true. It can. However, when it finds that a number is already in the set (i.e. inSet(element) is true), the number (element) gets added to the set anyway.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
bool MySet::inSet(int element){
//POST: returns true if the item is in the set and false if the item
// is not in the set
int i;
bool inSet;
if(cardinality()==0){//cardinality() returns the size of the array
inSet = false;
}else{
for(i=0;i<cardinality();i++){
if(getElement(i) == element){//getElement retrieves the element at index i
inSet = true;
}else{
inSet = false;
}
}
}
return inSet;
}
This code was provided by my professor. It clearly states to add a number to the set when inSet(randNum) is false. However, as previously stated, the number (randNum) has been added regardless every time.
I have played with this for a few hours now and am frustrated beyond belief at this. Any ideas as to what I have done wrong? I'm guessing it's something really simple that I'm overlooking.
OK. I edited my for loop a little bit to look like this:
1 2 3 4 5 6 7
for(i=0;i<cardinality();i++){
if(getElement(i) == element){
returntrue;//this is the changed part right here
}else{
inSet = false;
}
}
So far I haven't had a problem with numbers repeating (*fingers crossed*). I decided to make it so that if it found a number in the set it would immediately exit back to main (via the return statement) and otherwise, it would stick it out until it reached the end of the array.
Just thought I'd post this in case it helps someone else.
hmm, everything looks fine to me. But i re read your top post and you are saying even tho the function returns true( ie in the set) the number still gets added. i think your problem is the if statement (i think) try this.
1 2 3 4 5
if(Winners.inSet(randNum) == false) { // see if this works
Winners += randNum;
}
}
pretty much if the number is not in the set, put it in the set. Hope this helps