Skip to content

Commit bbf4b44

Browse files
feat: add reverse array function (#54)
* [add] reverse array function Signed-off-by: Sumit Banik <[email protected]> * [update] comparison for two uint arrays * [add] endline in the file * chore: removed duplicated entry Signed-off-by: Sumit Banik <[email protected]> Co-authored-by: David Leal <[email protected]>
1 parent c2cc33b commit bbf4b44

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

src/Maths/ReverseArray.sol

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// SPDX-License-Identifier: MIT
2+
3+
pragma solidity ^0.8.0;
4+
5+
/**
6+
* @title Array Reversal.
7+
* @author Sumit Banik https://github.com/iSumitBanik
8+
* @dev Contract to demonstrate how an array is reversed.
9+
*/
10+
11+
contract ReverseArray {
12+
/**
13+
* @dev internal function which takes in an array of numbers,start and end index,as an ouput returns the reversed array.
14+
* @param _array => array of numbers
15+
* @param start => start index of the array
16+
* @param end => ending index of the array
17+
* @return _array => reversed array.
18+
*/
19+
function _reverseArray(
20+
uint256[] memory _array,
21+
uint256 start,
22+
uint256 end
23+
) internal pure returns (uint256[] memory) {
24+
while (start < end) {
25+
(_array[start], _array[end]) = (_array[end], _array[start]);
26+
start++;
27+
end--;
28+
}
29+
30+
return _array;
31+
}
32+
/**
33+
* @dev external function which takes in an array of numbers and as an ouput returns the reversed array.
34+
* @param _array => array of numbers
35+
* @return _array => reversed array using the _reverseArray internal function.
36+
*/
37+
function reverse(uint256[] memory _array)
38+
external
39+
pure
40+
returns (uint256[] memory)
41+
{
42+
uint256 end = (_array.length) - 1;
43+
return _reverseArray(_array, 0, end);
44+
}
45+
}

src/Maths/test/ReverseArray.t.sol

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// SPDX-License-Identifier: UNLICENSED
2+
pragma solidity ^0.8.0;
3+
4+
import "forge-std/Test.sol";
5+
import "../ReverseArray.sol";
6+
7+
contract ReverseArrayTest is Test {
8+
// Target contract
9+
ReverseArray reverseArray;
10+
11+
/// Test Params
12+
uint256[] private testArray = [202,27,123,1,66,76,2,55,111,455];
13+
uint256[] private expectedreversedArray = [455, 111, 55, 2, 76, 66, 1, 123, 27, 202];
14+
15+
function setUp() public {
16+
reverseArray = new ReverseArray();
17+
}
18+
19+
/// @dev Test `reverseArray`
20+
21+
function test_reverseArray() public {
22+
23+
uint[] memory reversedArray = reverseArray.reverse(testArray);
24+
assertEq(reversedArray,expectedreversedArray);
25+
}
26+
}

0 commit comments

Comments
 (0)