0

May I know how I can get the array size of NxN matrix

like number of rows and no: of columns where my input is 4x4

arr[4][4]

Is it something like arr[N].count for rows and arr[][N].count for columns?

Please advice

ielyamani
  • 17,807
  • 10
  • 55
  • 90
Ashh
  • 569
  • 1
  • 6
  • 28
  • https://docs.swift.org/swift-book/LanguageGuide/Subscripts.html Scroll down to just over half way – Bram Mar 12 '19 at 16:29
  • Please update your question with relevant code. Show how you declared your "matrix". – rmaddy Mar 12 '19 at 16:53

2 Answers2

1

Using the built-in Array type, you cannot create a two-dimensional Array (which you refer to as matrix) that's guaranteed to be "NxN", because you cannot guarantee that all inner arrays will have the same number of elements and you also cannot guarantee that the number of elements in the inner arrays will be the same as the number of arrays in the two-dimensional array.

However, you can access the number of inner arrays (or "rows") using arr.count and you can access the number of elements in the inner arrays using arr[i].count (which will be the number of "columns" assuming that all inner arrays have the same number of elements).

If you'll be using two-dimensional Arrays a lot and you want to guarantee that all of the inner arrays have the same number of elements, I'd suggest creating a custom Collection.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
1

You can use count or endIndex to get the dimensions but you need to check each row separately.

var matrix: [[Int]] = [[1,2,3], [4,5,6,7], [8,9]]

print(matrix.count)

for i in 0..<matrix.endIndex {
    print(matrix[i].endIndex)
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52