Skip to content

Instantly share code, notes, and snippets.

@BitPuffin
Created November 23, 2013 19:48
Show Gist options
  • Save BitPuffin/7619079 to your computer and use it in GitHub Desktop.
Save BitPuffin/7619079 to your computer and use it in GitHub Desktop.
## Hard-coded implementations of the submatrix operator
proc `{}`*[T](m: TMatrix[T, range[0..1], range[0..1]], n: range[10..99]): T =
let therow = n div 10 mod 10
let thecol = n mod 10
result = m[if therow == 1: 0 else: 1][if thecol == 1: 0 else: 1]
proc `{}`*[T](M: TMatrix[T, range[0..2], range[0..2]], n: range[10..99]): TMatrix[T, range[0..1], range[0..1]] =
let therow = n div 10 mod 10
let thecol = n mod 10
for i in 0..2:
if i == therow:
continue
for j in 0..2:
if j == thecol:
continue
let ro = if i < therow: i else: i -1
let co = if j < thecol: j else: j -1
result[ro][co] = m[i][j]
when isMainModule:
var a, b: TMatrix[int, range[0..2], range[0..2]] # 3x3 matrix
var c: TMatrix[int, range[0..1], range[0..1]]
a = [[ 1, -5, 3],
[ 0, -2, 6],
[ 7, 2, -4]]
b = [[-8, 6, 1],
[ 7, 0, -3],
[ 2, 4, 5]]
c = [[ 4, 8],
[ 7, -2]]
var v: TVector[int, range[0..1]] = [2, 4]
assert(+a == a)
assert(-a == [[-1, 5, -3], [0, 2, -6], [-7, -2, 4]])
assert b.transposed == [[-8, 7, 2], [6, 0, 4], [1, -3, 5]]
assert a + b == [[-7, 1, 4], [7, -2, 3], [9, 6, 1]]
assert a - b == [[9, -11, 2], [-7, -2, 9], [5, -2, -9]]
assert a.row(1) == [0, -2, 6]
assert a.col(2) == [3, 6, -4]
assert a*b == [[-37, 18, 31], [-2, 24, 36], [-50, 26, -19]]
var d = [[1, 2],
[3, 4]]
assert d{10} == 2
assert a{20} == [[-5, 3], [-2, 6]]
echo("Sucessfully tested! No STDs found trololol.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment