From 550c941949773896422361fae0d72bceb610050f Mon Sep 17 00:00:00 2001 From: Younes Date: Mon, 7 Aug 2023 11:03:35 +0200 Subject: [PATCH 1/2] Update Contract.sol with new functions --- lesson-2/chapter-5/Contract.sol | 41 +++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/lesson-2/chapter-5/Contract.sol b/lesson-2/chapter-5/Contract.sol index 835be47..120b638 100644 --- a/lesson-2/chapter-5/Contract.sol +++ b/lesson-2/chapter-5/Contract.sol @@ -29,12 +29,45 @@ 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); +} + + + randDna = randDna - randDna % 100; + _createZombie(_name, randDna); +} + + } contract ZombieFeeding is ZombieFactory { } From d07b95ff6f22a45f10a07aca55bd6a7833bf35eb Mon Sep 17 00:00:00 2001 From: Younes <112932882+Winter9998@users.noreply.github.com> Date: Mon, 7 Aug 2023 11:18:31 +0200 Subject: [PATCH 2/2] Update Contract.sol --- lesson-2/chapter-5/Contract.sol | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lesson-2/chapter-5/Contract.sol b/lesson-2/chapter-5/Contract.sol index 120b638..c2d2ffe 100644 --- a/lesson-2/chapter-5/Contract.sol +++ b/lesson-2/chapter-5/Contract.sol @@ -63,8 +63,7 @@ contract ZombieFactory { } - randDna = randDna - randDna % 100; - _createZombie(_name, randDna); + }