From a902178fdb2ca0f974834879e1310ec3c4815907 Mon Sep 17 00:00:00 2001 From: nyx-litenite <50533436+nyx-litenite@users.noreply.github.com> Date: Sun, 7 Mar 2021 04:58:13 -0500 Subject: [PATCH] arrays: implement python-inspired array zip function and test (#8667) --- vlib/arrays/arrays.v | 27 +++++++++++++++++++++++++++ vlib/arrays/arrays_test.v | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/vlib/arrays/arrays.v b/vlib/arrays/arrays.v index c83022c4d8..71465b7399 100644 --- a/vlib/arrays/arrays.v +++ b/vlib/arrays/arrays.v @@ -98,6 +98,33 @@ pub fn merge(a []T, b []T) []T { return m } +// group n arrays into a single array of arrays with n elements +pub fn group(lists ...[]T) [][]T { + mut length := if lists.len > 0 { lists[0].len } else { 0 } + // calculate length of output by finding shortest input array + for ndx in 1 .. lists.len { + if lists[ndx].len < length { + length = lists[ndx].len + } + } + + if length > 0 { + mut arr := [][]T{cap: length} + // append all combined arrays into the resultant array + for ndx in 0 .. length { + mut zipped := []T{cap: lists.len} + // combine each list item for the ndx position into one array + for list_ndx in 0 .. lists.len { + zipped << lists[list_ndx][ndx] + } + arr << zipped + } + return arr + } + + return [][]T{} +} + [deprecated] pub fn shuffle(mut a []T, n int) { panic('Please use rand.util.shuffle() instead') diff --git a/vlib/arrays/arrays_test.v b/vlib/arrays/arrays_test.v index 37d2cd314d..54042b1f09 100644 --- a/vlib/arrays/arrays_test.v +++ b/vlib/arrays/arrays_test.v @@ -52,3 +52,36 @@ fn test_merge() { assert merge(a, c) == a assert merge(d, b) == b } + +fn test_fixed_array_assignment() { + mut a := [2]int{} + a[0] = 111 + a[1] = 222 + b := a + assert b[0] == a[0] + assert b[1] == a[1] + mut c := [2]int{} + c = a + assert c[0] == a[0] + assert c[1] == a[1] + d := [3]int{init: 333} + for val in d { + assert val == 333 + } + e := [3]string{init: 'vlang'} + for val in e { + assert val == 'vlang' + } +} + +fn test_group() { + x := [4, 5, 6] + y := [2, 1, 3] + + z := group(x, y) + assert z == [[4, 2], [5, 1], [6, 3]] + x2 := [8, 9] + z2 := group(x2, y) + assert z2 == [[8, 2], [9, 1]] + assert group(x, []int{}) == [][]int{} +}