Last active
April 21, 2020 08:08
-
-
Save amfathi/487e2642f197f71c00d6d5748dbfc8a1 to your computer and use it in GitHub Desktop.
Basic reversing algorithms for arrays and strings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| // MARK: - Reverse Array | |
| func reverse<T>(array: [T]) -> [T] { | |
| var reversedArray = array | |
| var index = 0 | |
| while index < array.count { | |
| reversedArray[index] = array[array.count - index - 1] | |
| index += 1 | |
| } | |
| return reversedArray | |
| } | |
| reverse(array: [1, 2, 3, 4, 5]) // -> [5, 4, 3, 2, 1] | |
| reverse(array: ["1", "2", "3", "4", "5"]) // -> ["5", "4", "3", "2", "1"] | |
| reverse(array: [true, false, false]) // -> [false, false, true] | |
| // MARK: - Reverse String | |
| func reverse(string: String) -> String { | |
| var reversedString = "" | |
| for char in string { | |
| reversedString = String(char) + reversedString | |
| } | |
| return reversedString | |
| } | |
| reverse(string: "Ahmed Fathi") // -> "ihtaF demhA" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment