Loop over two arrays with different length

Hello guys, I have a quite basic question but actually I do not how to approach the problem.

Given two arrays
  • The first one with n items

Code Block swift
arrayOfItems = ["1", "2", "3", "4", "5", "6", ..., "n"]
  • The second one with 5 items

Code Block swift
arrayOfFive = ["Item1", "Item2", "Item3", "Item4", "Item5"]


I want to loop over the two arrays such as the output is like:
Code Block
1
Item_1
2
Item_2
3
Item_3
4
Item_4
5
Item_5
6
Item_1
7
Item_2
.
.
.


Any help is appreciated.
Dennis
Answered by OOPer in 664327022
When will the loop finish? When arrayOfItems is finished? Or a longer Array finished? Or else you want an infinite loop?


In case When arrayOfItems is finished:
Code Block
for i in arrayOfItems.indices {
let elt1 = arrayOfItems[i]
let elt2 = arrayOfFive[i % arrayOfFive.count]
print(elt1)
print(elt2)
print()
}

(Assuming arrayOfFive is not empty.)
Accepted Answer
When will the loop finish? When arrayOfItems is finished? Or a longer Array finished? Or else you want an infinite loop?


In case When arrayOfItems is finished:
Code Block
for i in arrayOfItems.indices {
let elt1 = arrayOfItems[i]
let elt2 = arrayOfFive[i % arrayOfFive.count]
print(elt1)
print(elt2)
print()
}

(Assuming arrayOfFive is not empty.)
The loop will finish when arrayOfItems is finished. But it is a dynamic array in the sense that sometimes n could be 100 or 1000. I think I could approach the problem like this but it is not efficient and is difficult to read:
  • In this example, assume arrayOfItems is an array of String items not Integers, so in the loop I will use .indices to obtain the index.

Code Block swift
import Foundation
let arrayOfItems = (0...100)
let arrayOfFive = ["Item1", "Item2", "Item3", "Item4", "Item5"]
for index in arrayOfItems {
    if (0...4).contains(index) {
        print(index)
        print(arrayOfFive[index])
    } else if (5...9).contains(index) {
        print(index)
        print(arrayOfFive[index - 5])
    } else if (10...19).contains(index) {
        if (10...14).contains(index) {
            print(index)
            print(arrayOfFive[index - 10])
        } else {
            print(index)
            print(arrayOfFive[index - 15])
        }
    }
}
// Using this approach I will have to create if statements every tens. So, it's not generic for any n numbers


The loop will finish when arrayOfItems is finished. But it is a dynamic array in the sense that sometimes n could be 100 or 1000.

What is the problem with the proposed solution ? It will work in all cases. n can be 100 or 1000, it will work the same.

Using this approach I will have to create if statements every tens. So, it's not generic for any n numbers

Effectively, as you don't know if n is 10 or 10 000 it is unpractical solution.
You are just hard coding a computed solution.
Don't do this.
Loop over two arrays with different length
 
 
Q