|
| 1 | +import std/[strutils, sugar, tables] |
| 2 | + |
| 3 | +type SparseVector* = object |
| 4 | + elements*: Table[int, float32] |
| 5 | + dim*: int |
| 6 | + |
| 7 | +proc `$`*(v: SparseVector): string = |
| 8 | + let elements = collect(newSeqOfCap(v.elements.len)): |
| 9 | + for k, v in v.elements: $(k + 1) & ":" & $v |
| 10 | + result = "{" & elements.join(",") & "}/" & $v.dim |
| 11 | + |
| 12 | +proc toSparseVector*[T](a: openArray[T]): SparseVector = |
| 13 | + var elements = initTable[int, float32]() |
| 14 | + for i, v in a: |
| 15 | + let f = float32(v) |
| 16 | + if f != 0: |
| 17 | + elements[i] = f |
| 18 | + result = SparseVector(elements: elements, dim: a.len) |
| 19 | + |
| 20 | +proc toSparseVector*[T](elements: Table[int, T], dim: int): SparseVector = |
| 21 | + var e = initTable[int, float32]() |
| 22 | + for k, v in elements: |
| 23 | + e[k] = float32(v) |
| 24 | + result = SparseVector(elements: e, dim: dim) |
| 25 | + |
| 26 | +proc toSparseVector*(s: string): SparseVector = |
| 27 | + let parts = s.split("}/", maxsplit = 2) |
| 28 | + var elements = initTable[int, float32]() |
| 29 | + for e in parts[0][1..^1].split(","): |
| 30 | + let ep = e.split(":", maxsplit = 2) |
| 31 | + let index = parseInt(ep[0]) |
| 32 | + let value = float32(parseFloat(ep[1])) |
| 33 | + elements[index - 1] = value |
| 34 | + let dim = parseInt(parts[1]) |
| 35 | + result = SparseVector(elements: elements, dim: dim) |
0 commit comments