CS50x Problem Set 5 - Inheritance allows inheriting both alleles from one parent
BallyCode opened this issue · 1 comments
BallyCode commented
My initially incorrect code passed check50 with this:
// TODO: Randomly assign current person's alleles based on the alleles of their parents
aperson->alleles[0] = parent0->alleles[rand() % 2];
aperson->alleles[1] = parent0->alleles[rand() % 2];
inheriting both alleles from parent0
.
The second line should have been aperson->alleles[1] = parent1->alleles[rand() % 2];
I discovered the error when I noticed a person with an OO blood type had parents with OO and BB blood types in the printout of the family.
BallyCode commented
I believe this code will correctly check that a person inherits from both parents but it should be carefully double-checked! It includes a few debugging printf
s that are commented out.
Unfortunately, due to the random assignment of alleles, it requires multiple runs of inheritance in order to catch errors.
bool check_inheritance(person *p)
// Returns true if all persons are inheriting from both their parents. Returns false if error.
{
if (p == NULL)
{
return true;
}
if (p->parents[0] != NULL) // no need to check for parents[1], since a person can't have only one parent
{
bool match = (p->alleles[0] == p->parents[0]->alleles[0] || p->alleles[0] == p->parents[0]->alleles[1]) &&
(p->alleles[1] == p->parents[1]->alleles[0] || p->alleles[1] == p->parents[1]->alleles[1]);
if (! match)
{
// printf("ERROR FOUND in person%p\n", &p);
return false;
}
else
{
return true;
}
}
if (check_inheritance(p->parents[0]) == true)
{
return check_inheritance(p->parents[1]);
}
else
{
return false;
}
}