Random Elements in Multidimensional Array

Hello community. I hope you are doing well.

My task was to create a multidimensional Array with random elements in each row and column. In result, I got a multidimensional Array which I have identical rows in. The function randomizer does not seem to be working as I expected.

May anybody explain why?

var word = "contemplation"
var length : Int = word.count + 2
var VH : [[Int]] = [[]]
var randomNum : [Int] = []

func randomizer() -> [Int] {
while randomNum.count != length {
randomNum.append(Int.random(in: 0...9))
print(randomNum.count)
}
return randomNum
}
var counter = 0
repeat {
VH.append(randomizer())
counter += 1
}while counter != length

Thanks for your priceless time.

You have the array randomNum outside the function. Moving the randomNum variable inside the function will fix your issue.

var word = "contemplation"
var length : Int = word.count + 2
var VH : [[Int]] = [[]]

func randomizer() -> [Int] {
    var randomNum : [Int] = [] //<---
    while randomNum.count != length {
        randomNum.append(Int.random(in: 0...9))
        print(randomNum.count)
    }
    return randomNum
}
var counter = 0
repeat {
    VH.append(randomizer())
    counter += 1
} while counter != length

This way you create a new empty array every time you call the randomizer function and then populate it with random numbers.

1 Like

Since randomNum is global state that outlives the body of randomizer for every call after the first one randomNum is already full.

Said another way, the first call to randomizer fills randomNum with length values and nothing ever clears it out so every subsequent call immediately skips over the while loop and returns the same array.

Instead of relying on shared mutable state try creating a function that takes in a length and returns an array of random Ints.

func makeRandomInts(length: Int) -> [Int] {
    // Implementation that does not access global state
}
1 Like

Are you familiar with the map function? You can achieve this much more succinctly with it:

let randomArray2D = (0..<rows).map { _ in
  (0..<columns).map { _ in
    Int.random(in: range)
  }
}
4 Likes

I don't know the map yet. I've been studying swift for only a couple of weeks. I'll take it into account.Thanks.

1 Like
Terms of Service

Privacy Policy

Cookie Policy