Skip to content

Commit

Permalink
arrays: fix off by one error in arrays.uniq_only_repeated/1 and array…
Browse files Browse the repository at this point in the history
…s.uniq_all_repeated/1
  • Loading branch information
spytheman committed Dec 4, 2023
1 parent d9e9c71 commit c7b7d5f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
4 changes: 2 additions & 2 deletions vlib/arrays/uniq.v
Expand Up @@ -91,7 +91,7 @@ pub fn uniq_only_repeated[T](a []T) []T {
// found the right border of the repeated elements
if j - i > 1 {
res << a[i]
i = j
i = j - 1
continue loop
}
}
Expand Down Expand Up @@ -132,7 +132,7 @@ pub fn uniq_all_repeated[T](a []T) []T {
for j := i + 1; j < a.len; j++ {
if a[i] != a[j] && j - i > 0 {
// found the right border of the repeated elements
i = j
i = j - 1
continue loop
}
res << a[i]
Expand Down
11 changes: 9 additions & 2 deletions vlib/arrays/uniq_test.v
Expand Up @@ -4,6 +4,8 @@ const a = [1, 5, 5, 1, 5, 2, 1, 1, 9, 2]

const s = [1, 1, 1, 1, 2, 2, 5, 5, 5, 9] // a.sorted()

const many_repeats = [1, 1, 1, 1, 2, 2, 5, 5, 5, 9, 1, 1, 9, 5, 5]

const astrings = ['b', 'b', 'a', 'b', 'z', 'a', 'a', 'd']

const sstrings = ['a', 'a', 'a', 'b', 'b', 'b', 'd', 'z'] // astrings.sorted()
Expand All @@ -16,6 +18,7 @@ fn test_uniq() {
assert arrays.uniq(s) == [1, 2, 5, 9]
assert arrays.uniq(astrings) == ['b', 'a', 'b', 'z', 'a', 'd']
assert arrays.uniq(sstrings) == ['a', 'b', 'd', 'z']
assert arrays.uniq(many_repeats) == [1, 2, 5, 9, 1, 9, 5]
}

fn test_uniq_only() {
Expand All @@ -27,6 +30,7 @@ fn test_uniq_only() {
assert arrays.uniq_only(s) == [9]
assert arrays.uniq_only(astrings) == ['a', 'b', 'z', 'd']
assert arrays.uniq_only(sstrings) == ['d', 'z']
assert arrays.uniq_only(many_repeats) == [9, 9]
}

fn test_uniq_only_repeated() {
Expand All @@ -52,7 +56,8 @@ fn test_uniq_only_repeated() {
assert arrays.uniq_only_repeated([5, 5, 1, 5, 5, 2, 5, 5, 3, 5, 5]) == [5, 5, 5, 5]
assert arrays.uniq_only_repeated([5, 5, 5, 1, 5, 5, 2, 5, 5, 3, 5, 5]) == [5, 5, 5, 5]
assert arrays.uniq_only_repeated(a) == [5, 1]
assert arrays.uniq_only_repeated(s) == [1, 5]
assert arrays.uniq_only_repeated(s) == [1, 2, 5]
assert arrays.uniq_only_repeated(many_repeats) == [1, 2, 5, 1, 5]
}

fn test_uniq_all_repeated() {
Expand Down Expand Up @@ -80,10 +85,12 @@ fn test_uniq_all_repeated() {
assert arrays.uniq_all_repeated([5, 5, 5, 1, 5, 5, 2, 5, 5, 3, 5, 5]) == [5, 5, 5, 5, 5, 5,
5, 5, 5]
assert arrays.uniq_all_repeated(a) == [5, 5, 1, 1]
assert arrays.uniq_all_repeated(s) == [1, 1, 1, 1, 5, 5, 5]
assert arrays.uniq_all_repeated(s) == [1, 1, 1, 1, 2, 2, 5, 5, 5]
assert arrays.uniq_all_repeated(many_repeats) == [1, 1, 1, 1, 2, 2, 5, 5, 5, 1, 1, 5, 5]
}

fn test_distinct() {
assert arrays.distinct(a) == arrays.distinct(s)
assert arrays.distinct(a) == [1, 2, 5, 9]
assert arrays.distinct(many_repeats) == [1, 2, 5, 9]
}

0 comments on commit c7b7d5f

Please sign in to comment.