Ashh
Ashh

Reputation: 569

Create nXn matrix with values incrementing Swift

Im trying to find an easy way to create matrix with self incrementing values i.e., if 3x3 array then it should look like [[0,1,2],[3,4,5],[6,7,8]]

when I do something like below, I could get all zero's

var arr = Array(repeating: Array(repeating: 0, count: 3), count: 3)

Inorder to acheive, I need to loop through elements and reassign incremented values. Instead of that is there any fast approach I could follow without using for-loop?

Upvotes: 0

Views: 357

Answers (2)

skittle
skittle

Reputation: 238

There is the a Subscripts tutorial on Swift.org showing a Matrix struct example, which I really like

Upvotes: 0

Martin R
Martin R

Reputation: 539845

A possible approach is to use map() on the range of rows and columns:

let nrows = 3 // Number of rows
let ncols = 3 // Number of columns
let matrix = (0..<nrows).map { row in (0..<ncols).map { col in ncols * row + col } }
print(matrix) // [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

The outer (0..<nrows).map maps each row number to an array (the “row”), and the inner (0..<ncols).map maps each column number to a matrix entry.

With a little bit “tuple magic” you could assign auto-incrementing values:

var entry = 0
let matrix = (0..<nrows).map { _ in (0..<ncols).map { _ in (entry, entry += 1).0 } }

but that's not what I would really recommend.

Upvotes: 2

Related Questions