Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3x3 array in Swift [closed]

Tags:

arrays

swift

I'm trying to make a 3x3 array in Swift, but the number of rows is always different than what I expect. For example, I thought the code below would make a 3x3 array, but it's actually 9x3 array. Why? And how can I make it 3x3?

var NumColumns = 3
var NumRows = 3
var occupied = [[Bool]](count: NumColumns, repeatedValue:[Bool](count: NumRows, repeatedValue:false));
for item in occupied {
    for item in occupied {
        print(item)
    }
}
like image 833
amstrudy Avatar asked Aug 03 '26 11:08

amstrudy


1 Answers

It's looks like you want a 3x3 matrix of booleans.

Then you can use the (slightly updated) code provided as example by the Swift Programming Language.

struct Matrix {
    let rows: Int, columns: Int
    var grid: [Bool]
    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        grid = Array(count: rows * columns, repeatedValue: false)
    }
    func indexIsValidForRow(row: Int, column: Int) -> Bool {
        return row >= 0 && row < rows && column >= 0 && column < columns
    }
    subscript(row: Int, column: Int) -> Bool {
        get {
            assert(indexIsValidForRow(row, column: column), "Index out of range")
            return grid[(row * columns) + column]
        }
        set {
            assert(indexIsValidForRow(row, column: column), "Index out of range")
            grid[(row * columns) + column] = newValue
        }
    }
}

Example

var matrix = Matrix(rows: 3, columns: 3)
matrix[0, 0] = true
print(matrix[0, 0]) // true
like image 83
Luca Angeletti Avatar answered Aug 06 '26 02:08

Luca Angeletti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!