FOR LOOPS AND ARRAY EXERCISES IN SOLIDITY

16 April 2022, Abdulhakim Altunkaya

Execise 3: Remove the Repetitive Numbers inside an Array by using For Loop

To find the repetitive number and remove it, we can follow these steps:

1. Create a uint array

2. Create a write function. The algorithm is, we will compare each number to the number on its right. To make this possible, we will use two for loops. First for loop, will store the number on the left and this for loop will be the parent for loop. The second for loop will bring all numbers on the right of first number. It will then compare each number (the numbers brought by second for loop) to the first loop number.

3. Inside our second (child) for loop, there will be an if statement to detect if the first number is equal to second number. If same, then it will replace it with the element at the end of our array.

4. Later we can remove the last element by using "pop()". We will see that the order will be broken, but in any case it will be a solution to what we want to do.

5. Lastly we will create a view function, to see our uint array.

6. You can copy-paste this to Remix, and play with it to practice and learn.

//SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.7;

contract Exercise {

/* First cycle of the Parent loop: We are comparing 20 to 15, 10, 2, 15
Second cycle of the Parent loop: We are comparing 15 to 10, 2, 15
Third cycle of the Parent loop: We are comparing 10 to 2, 15
Fourth cycle of the Parent loop: We are comparing 2 to 15
I am not comparing 15 to any number. Because limit is "myArray.length-1"
And parent loop finishes.
As you can see child loop is dependent on the parent loop. If parent loop starts with 20
then child loop starts with 15. */

//Creating an array
uint[] myArray = [20, 15, 10, 2, 15];

//Find repetitive/duplicate number and remove it
function removeDuplicate() external {
for(uint a = 0; a < myArray.length-1; a++){

uint x = myArray[a];
for(uint i = a+1; i < myArray.length; i++) {
if(x == myArray[i]) {
myArray[i] = myArray[myArray.length-1];
myArray.pop();
}
}

}
}

//To see our array after the loop:
function getArray() external view returns(uint[] memory) {
return myArray;
}
}

Click on arrows for the next Article: ⇨ ⇨