mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
arrays: implement python-inspired array zip function and test (#8667)
This commit is contained in:
parent
82085b0140
commit
a902178fdb
@ -98,6 +98,33 @@ pub fn merge<T>(a []T, b []T) []T {
|
|||||||
return m
|
return m
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// group n arrays into a single array of arrays with n elements
|
||||||
|
pub fn group<T>(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]
|
[deprecated]
|
||||||
pub fn shuffle<T>(mut a []T, n int) {
|
pub fn shuffle<T>(mut a []T, n int) {
|
||||||
panic('Please use rand.util.shuffle() instead')
|
panic('Please use rand.util.shuffle() instead')
|
||||||
|
@ -52,3 +52,36 @@ fn test_merge() {
|
|||||||
assert merge<int>(a, c) == a
|
assert merge<int>(a, c) == a
|
||||||
assert merge<int>(d, b) == b
|
assert merge<int>(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<int>(x, y)
|
||||||
|
assert z == [[4, 2], [5, 1], [6, 3]]
|
||||||
|
x2 := [8, 9]
|
||||||
|
z2 := group<int>(x2, y)
|
||||||
|
assert z2 == [[8, 2], [9, 1]]
|
||||||
|
assert group<int>(x, []int{}) == [][]int{}
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user