gpt4 book ai didi

快速矩阵求和

转载 作者:搜寻专家 更新时间:2023-11-01 07:22:50 25 4
gpt4 key购买 nike

我正在尝试开发一个函数,如果它们等于相同的维度,它允许对两个矩阵求和,但我在尝试时收到错误“EXC_BAD_INSTRUCTION”。

这是我的 Playground :

import Foundation

enum RisedError: ErrorType {
case DimensionNotEquals
case Obvious(String)
}

func ==(lhs: Matrix, rhs: Matrix) -> Bool {
return (lhs.rows) == (rhs.rows) && (lhs.columns) == (rhs.columns)
}

protocol Operation {
mutating func sumWith(matrixB: Matrix) throws -> Matrix
}

struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: 0.0)
}
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
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
}
}
}

var matrixA = Matrix(rows: 2, columns: 2)
matrixA[0,0] = 1.0
matrixA[0,1] = 2.0
matrixA[1,0] = 3.0
matrixA[1,1] = 4.0
var matrixB = Matrix(rows: 2, columns: 2)
matrixB[0,0] = 5.0
matrixB[0,1] = 6.0
matrixB[1,0] = 7.0
matrixB[1,1] = 8.0

print(matrixA)
print(matrixB)

extension Matrix: Operation {

mutating func sumWith(matrixB: Matrix) throws -> Matrix {

guard self == matrixB else { throw RisedError.DimensionNotEquals }

for row in 0...self.rows {
for column in 0...self.columns {
self[row, column] = matrixB[row, column] + self[row, column]
}
}
return self
}
}

do {
try matrixA.sumWith(matrixB)
} catch RisedError.DimensionNotEquals {
print("The two matrix's dimensions aren't equals")
} catch {
print("Something very bad happens")
}

错误日志如下:

enter image description here

最佳答案

实际上你的错误是Index out of range

用此代码替换您的扩展程序。

extension Matrix: Operation {

mutating func sumWith(matrixB: Matrix) throws -> Matrix {

guard self == matrixB else { throw RisedError.DimensionNotEquals }

for row in 0...self.rows - 1 {
for column in 0...self.columns - 1 {
self[row, column] = matrixB[row, column] + self[row, column]
}
}
return self
}
}

希望它能解决您的问题。

关于快速矩阵求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37745743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com