From c7b7d5f50feb290eadac5ec8e7c9d8a786b657d2 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Mon, 4 Dec 2023 15:21:01 +0200 Subject: [PATCH] arrays: fix off by one error in arrays.uniq_only_repeated/1 and arrays.uniq_all_repeated/1 --- vlib/arrays/uniq.v | 4 ++-- vlib/arrays/uniq_test.v | 11 +++++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/vlib/arrays/uniq.v b/vlib/arrays/uniq.v index 0b70e38a50d25f..6d41603bf4f8ad 100644 --- a/vlib/arrays/uniq.v +++ b/vlib/arrays/uniq.v @@ -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 } } @@ -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] diff --git a/vlib/arrays/uniq_test.v b/vlib/arrays/uniq_test.v index 49b20847423fa5..cc07492a6b119d 100644 --- a/vlib/arrays/uniq_test.v +++ b/vlib/arrays/uniq_test.v @@ -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() @@ -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() { @@ -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() { @@ -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() { @@ -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] }