0

Here is the code :

// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;

contract Day1 {

function reverseArray(uint[] memory arr1, uint length) public pure returns(uint[] memory){

  uint[] memory arr2;
  uint i = length-1;
  uint j = 0;

  while(i>=0 && j<length){
    arr2[j] = arr1[i];    
    i--;
    j++;
  } 

  return arr2;

  }
}

The error:

revert

entire script

2 Answers 2

1

So, two things:

  1. you need to change how you declare your arr2
  2. in your while loop, i gets to 0 and goes into the loop where you do i-- so you are doing '0 - 1' and you underflow, which reverts your transaction.

I got it to work by doing the last swap outside of the loop. I'm sure there is a better way but I don't have enough time to find it right now.

here is the code

pragma solidity >=0.5.0 <0.9.0;

contract Day1 {

  function reverseArray(uint[] memory arr1, uint length) public pure returns(uint[] memory){

    uint[] memory arr2 = new uint[](length);
    uint i = length-1;
    uint j = 0;

    while(i>0 && j<length){
      arr2[j] = arr1[i]; 
      i--;
      j++;
    }

    arr2[j] = arr1[i];

    return arr2;

    }
}

Hope this helps!

3
  • Thanks! this sure helps. Commented Dec 17, 2022 at 10:43
  • i tried changing all data types from uint to int to avoid the underflow problem but it still wouldn't work if the last loop is not declared out of the while loop. Why is it so? Commented Dec 17, 2022 at 11:13
  • @GimmeGinNtonic We would have to see that code. But my assumption is that it didn't work because your arrays were also unit[] type.
    – Sky
    Commented Dec 17, 2022 at 11:34
1

There are number of syntax issues in the code you posted. But this should help;

// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;

contract RevertArray {

    function reverseArray(uint[] memory array) public pure returns(uint[] memory) {

    uint length = array.length;
    uint numberOfElements = length -1;
    uint[] memory reversed = new uint[](length);
    
    uint i = numberOfElements;
    uint j;

    while( j < numberOfElements) {
        reversed[j] = array[i];    
        i--;
        j++;
    } 

    reversed[j] = array[i];

    return reversed;

    }

}
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.