Skip to content

Commit

Permalink
Added fromMap constructor to SparseVector
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Sep 10, 2024
1 parent cfab8e6 commit a48fea5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/src/sparsevec.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ class SparseVector {
return SparseVector._(dimensions, indices, values);
}

factory SparseVector.fromMap(Map<int, double> map, int dimensions) {
var elements = map.entries.where((v) => v.value != 0).toList();
elements.sort((a, b) => a.key.compareTo(b.key));

var indices = elements.map((v) => v.key).toList();
var values = elements.map((v) => v.value).toList();

return SparseVector._(dimensions, indices, values);
}

factory SparseVector.fromBinary(Uint8List bytes) {
var buf = new ByteData.view(bytes.buffer, bytes.offsetInBytes);
var dimensions = buf.getInt32(0);
Expand Down
9 changes: 9 additions & 0 deletions test/sparsevec_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,13 @@ void main() {
expect(vec.indices, equals([0, 2, 4]));
expect(vec.values, equals([1, 2, 3]));
});

test('fromMap', () {
var vec = SparseVector.fromMap({2: 2.0, 4: 3.0, 0: 1.0, 3: 0.0}, 6);
expect(vec.toString(), equals('{1:1.0,3:2.0,5:3.0}/6'));
expect(vec.toList(), equals([1, 0, 2, 0, 3, 0]));
expect(vec.dimensions, equals(6));
expect(vec.indices, equals([0, 2, 4]));
expect(vec.values, equals([1, 2, 3]));
});
}

0 comments on commit a48fea5

Please sign in to comment.