0

I am trying to reverse an array of strings without using .reverse(). Are there any efficient ways to do this? Here is the prompt:

"Create a variable called reversedLanguages. Use a loop to fill reversedLanguages with the same items as languages, except in reverse order. (You may not use .reversed()).

Print the reversedLanguages array at the end in order for the tests to work"

var languages = ["English", "Spanish", "Japanese", "Italian", "Russian"]

var reversedLanguages = [String]()

var position = 4
for language in languages {
 reversedLanguages.insert(language, at: position)
 position -= 1
print(reversedLanguages)
}
Willishere
  • 25
  • 2

1 Answers1

0
var languages = ["English", "Spanish", "Japanese", "Italian", "Russian"]

var reversedLanguages:[String] = []
for i in 0 ..< languages.count {
    let language = languages[languages.count-i-1]
    reversedLanguages.append(language)
}
print(reversedLanguages)

1) Your initial input

2) Create a new array to insert into

3) Loop through original language (since you are recreating a new array from yours, it will always be O(n) so this is the most efficient it can get)

4) Get the reverse language of current index i since i goes in order 0 ..< languages.count

5) Append to new array

impression7vx
  • 1,728
  • 1
  • 20
  • 50
  • You can also `for i in stride(from: languages.count - 1, through: 0, by: -1) { reversedLanguages.append(languages[i]) }` – Rob Jul 24 '19 at 18:18
  • Well dang. That's pretty nifty. With the "new" way Swift does loops, wasn't sure how to go back like that. I generally just go forwards and find the variable using subtraction **shrug** – impression7vx Jul 24 '19 at 18:32
  • Another way to go backwards (if you allow the use of `reversed()`) is `for i in (0 ..< languages.count).reversed() {`. Of course, you can't do that for this question... – vacawama Jul 24 '19 at 18:35
  • or even `let reversedLanguages = stride(from: languages.count - 1, through: 0, by: -1).map { languages[i] }`. Again, not for *this* question. – vacawama Jul 24 '19 at 18:39
  • So I am running it and it's saying there may be an infinite loop? – Willishere Jul 24 '19 at 19:29
  • Well the fact that this is based off of languages.count, which is a finite array, and not a boolean condition, that is impossible. – impression7vx Jul 24 '19 at 20:06
  • @Willishere - The code here (or that in the various comments here) all work fine. There must be something else going on (e.g. maybe accidentally appending to the wrong array or something like that). Cut and paste the above code and you’ll see it works. There must be some difference between what you’re doing and what impression7vx suggested... – Rob Jul 25 '19 at 07:19