Skip to content

Commit 3b8fba8

Browse files
Merge pull request #141 from weilycoder/dev2
Fixed errors in Vector.random when generating floating-point vectors or vectors with repeated elements.
2 parents 2727298 + ef32276 commit 3b8fba8

File tree

3 files changed

+36
-2
lines changed

3 files changed

+36
-2
lines changed

cyaron/tests/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@
44
from .polygon_test import TestPolygon
55
from .compare_test import TestCompare
66
from .graph_test import TestGraph
7+
from .vector_test import TestVector

cyaron/tests/vector_test.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import unittest
2+
from cyaron.vector import *
3+
4+
5+
def has_duplicates(lst: list):
6+
return len(lst) != len(set(lst))
7+
8+
9+
class TestVector(unittest.TestCase):
10+
def test_unique_vector(self):
11+
v = Vector.random(10**5, [10**6])
12+
self.assertFalse(has_duplicates(list(map(lambda tp: tuple(tp), v))))
13+
self.assertTrue(all(map(lambda v: 0 <= v[0] <= 10**6, v)))
14+
v = Vector.random(1000, [(10**5, 10**6)])
15+
self.assertTrue(all(map(lambda v: 10**5 <= v[0] <= 10**6, v)))
16+
with self.assertRaises(
17+
Exception,
18+
msg="1st param is so large that CYaRon can not generate unique vectors",
19+
):
20+
v = Vector.random(10**5, [10**4])
21+
22+
def test_repeatable_vector(self):
23+
v = Vector.random(10**5 + 1, [10**5], VectorRandomMode.repeatable)
24+
self.assertTrue(all(map(lambda v: 0 <= v[0] <= 10**5, v)))
25+
self.assertTrue(has_duplicates(list(map(lambda tp: tuple(tp), v))))
26+
v = Vector.random(1000, [(10**5, 10**6)], VectorRandomMode.repeatable)
27+
self.assertTrue(all(map(lambda v: 10**5 <= v[0] <= 10**6, v)))
28+
29+
def test_float_vector(self):
30+
v = Vector.random(10**5, [10**5], VectorRandomMode.float)
31+
self.assertTrue(all(map(lambda v: 0 <= v[0] <= 10**5, v)))
32+
v = Vector.random(10**5, [(24, 25)], VectorRandomMode.float)
33+
self.assertTrue(all(map(lambda v: 24 <= v[0] <= 25, v)))

cyaron/vector.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,9 @@ def random(num: int = 5, position_range: list = None, mode: VectorRandomMode = 0
5454

5555
result = []
5656
if mode == VectorRandomMode.repeatable:
57-
result = [[random.randint(x, y) for x, y in zip(offset, length)] for _ in range(num)]
57+
result = [[random.randint(x, x + y) for x, y in zip(offset, length)] for _ in range(num)]
5858
elif mode == VectorRandomMode.float:
59-
result = [[random.uniform(x, y) for x, y in zip(offset, length)] for _ in range(num)]
59+
result = [[random.uniform(x, x + y) for x, y in zip(offset, length)] for _ in range(num)]
6060
elif mode == VectorRandomMode.unique and vector_space > 5 * num:
6161
# O(NlogN)
6262
num_set = set()

0 commit comments

Comments
 (0)