Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix createRandomZombie function for DNA uniqueness #47

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions lesson-2/chapter-5/Contract.sol
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,44 @@ contract ZombieFactory {
return rand % dnaModulus;
}

function createRandomZombie(string _name) public {
require(ownerZombieCount[msg.sender] == 0);
uint randDna = _generateRandomDna(_name);
_createZombie(_name, randDna);
function createRandomZombie(string memory _name) public {
require(ownerZombieCount[msg.sender] == 0);
uint randDna = _generateRandomDna(_name);

// Check if the generated DNA is already used by an existing zombie
bool isDnaUnique = true;
for (uint i = 0; i < zombies.length; i++) {
if (zombies[i].dna == randDna) {
isDnaUnique = false;
break;
}
}

if (!isDnaUnique) {
// Keep generating a new randDna until it is unique
while (!isDnaUnique) {
randDna = _generateRandomDna(_name);
isDnaUnique = true;
for (uint i = 0; i < zombies.length; i++) {
if (zombies[i].dna == randDna) {
isDnaUnique = false;
break;
}
}
}
} else {
// The initial randDna is already unique, no need to re-generate
}

randDna = randDna - randDna % 100;
_createZombie(_name, randDna);
}



}


}
contract ZombieFeeding is ZombieFactory {
}