Initial project import
This commit is contained in:
commit
23f2d29e32
11957 files changed
+1754577
No files matched your search
@@ -0,0 +1,16 @@
|
||||
## Description
|
||||
|
||||
`arrays` is a module that provides utility functions to make working with arrays easier.
|
||||
|
||||
## Examples
|
||||
|
||||
```v
|
||||
import arrays
|
||||
|
||||
fn main() {
|
||||
a := [1, 5, 7, 0, 9]
|
||||
assert arrays.min(a)! == 0
|
||||
assert arrays.max(a)! == 9
|
||||
assert arrays.idx_min(a)! == 3
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,783 @@
|
||||
module arrays
|
||||
|
||||
import strings
|
||||
|
||||
// Common arrays functions:
|
||||
// - min / max - return the value of the minimum / maximum
|
||||
// - idx_min / idx_max - return the index of the first minimum / maximum
|
||||
// - merge - combine two sorted arrays and maintain sorted order
|
||||
// - append - combine two arrays, by appending the second array to the first
|
||||
// - chunk - chunk array to arrays with n elements
|
||||
// - window - get snapshots of the window of the given size sliding along array with the given step, where each snapshot is an array
|
||||
// - group - merge two arrays by interleaving e.g. arrays.group([1,3,5], [2,4,6]) => [[1,2],[3,4],[5,6]]
|
||||
// - flatten - reduce dimensionality of array by one. e.g. arrays.flatten([[1,2],[3,4],[5,6]]) => [1,2,3,4,5,6]
|
||||
// - each - call a callback fn, for each element of the array, similar to a.map(), but unlike it, the callback should not return anything
|
||||
|
||||
// min returns the minimum value in the array.
|
||||
// Example: arrays.min([1, 2, 3, 0, 9])! // => 0
|
||||
pub fn min[T](array []T) !T {
|
||||
if array.len == 0 {
|
||||
return error('.min called on an empty array')
|
||||
}
|
||||
mut val := array[0]
|
||||
for e in array {
|
||||
if e < val {
|
||||
val = e
|
||||
}
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
// max returns the maximum value in the array.
|
||||
// Example: arrays.max([1, 2, 3, 0, 9])! // => 9
|
||||
pub fn max[T](array []T) !T {
|
||||
if array.len == 0 {
|
||||
return error('.max called on an empty array')
|
||||
}
|
||||
mut val := array[0]
|
||||
for e in array {
|
||||
if e > val {
|
||||
val = e
|
||||
}
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
// idx_min returns the index of the minimum value in the array.
|
||||
// Example: arrays.idx_min([1, 2, 3, 0, 9])! // => 3
|
||||
pub fn idx_min[T](array []T) !int {
|
||||
if array.len == 0 {
|
||||
return error('.idx_min called on an empty array')
|
||||
}
|
||||
mut idx := 0
|
||||
mut val := array[0]
|
||||
for i, e in array {
|
||||
if e < val {
|
||||
val = e
|
||||
idx = i
|
||||
}
|
||||
}
|
||||
return idx
|
||||
}
|
||||
|
||||
// idx_max returns the index of the maximum value in the array.
|
||||
// Example: arrays.idx_max([1, 2, 3, 0, 9])! // => 4
|
||||
pub fn idx_max[T](array []T) !int {
|
||||
if array.len == 0 {
|
||||
return error('.idx_max called on an empty array')
|
||||
}
|
||||
mut idx := 0
|
||||
mut val := array[0]
|
||||
for i, e in array {
|
||||
if e > val {
|
||||
val = e
|
||||
idx = i
|
||||
}
|
||||
}
|
||||
return idx
|
||||
}
|
||||
|
||||
// merge two sorted arrays (ascending) and maintain sorted order.
|
||||
// Example: arrays.merge([1, 3, 5, 7], [2, 4, 6, 8]) // => [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
@[direct_array_access]
|
||||
pub fn merge[T](a []T, b []T) []T {
|
||||
mut m := []T{len: a.len + b.len}
|
||||
mut ia := 0
|
||||
mut ib := 0
|
||||
mut j := 0
|
||||
// TODO: efficient approach to merge_desc where: a[ia] >= b[ib]
|
||||
for ia < a.len && ib < b.len {
|
||||
if a[ia] <= b[ib] {
|
||||
m[j] = a[ia]
|
||||
ia++
|
||||
} else {
|
||||
m[j] = b[ib]
|
||||
ib++
|
||||
}
|
||||
j++
|
||||
}
|
||||
// a leftovers
|
||||
for ia < a.len {
|
||||
m[j] = a[ia]
|
||||
ia++
|
||||
j++
|
||||
}
|
||||
// b leftovers
|
||||
for ib < b.len {
|
||||
m[j] = b[ib]
|
||||
ib++
|
||||
j++
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// append the second array `b` to the first array `a`, and return the result.
|
||||
// Note, that unlike arrays.concat, arrays.append is less flexible, but more efficient,
|
||||
// since it does not require you to use ...a for the second parameter.
|
||||
// Example: arrays.append([1, 3, 5, 7], [2, 4, 6, 8]) // => [1, 3, 5, 7, 2, 4, 6, 8]
|
||||
pub fn append[T](a []T, b []T) []T {
|
||||
mut m := []T{cap: a.len + b.len}
|
||||
m << a
|
||||
m << b
|
||||
return m
|
||||
}
|
||||
|
||||
// group n arrays into a single array of arrays with n elements.
|
||||
// This function is analogous to the "zip" function of other languages.
|
||||
// To fully interleave two arrays, follow this function with a call to `flatten`.
|
||||
// NOTE: An error will be generated if the type annotation is omitted.
|
||||
// Example: arrays.group[int]([1, 2, 3], [4, 5, 6]) // => [[1, 4], [2, 5], [3, 6]]
|
||||
pub fn group[T](arrs ...[]T) [][]T {
|
||||
mut length := if arrs.len > 0 { arrs[0].len } else { 0 }
|
||||
// calculate length of output by finding shortest input array
|
||||
for ndx in 1 .. arrs.len {
|
||||
if arrs[ndx].len < length {
|
||||
length = arrs[ndx].len
|
||||
}
|
||||
}
|
||||
|
||||
if length > 0 {
|
||||
mut arr := [][]T{cap: length}
|
||||
// append all combined arrays into the resultant array
|
||||
for ndx in 0 .. length {
|
||||
mut grouped := []T{cap: arrs.len}
|
||||
// combine each list item for the ndx position into one array
|
||||
for arr_ndx in 0 .. arrs.len {
|
||||
grouped << arrs[arr_ndx][ndx]
|
||||
}
|
||||
arr << grouped
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
return [][]T{}
|
||||
}
|
||||
|
||||
// chunk array into a single array of arrays where each element is the next `size` elements of the original.
|
||||
// Example: arrays.chunk([1, 2, 3, 4, 5, 6, 7, 8, 9], 2) // => [[1, 2], [3, 4], [5, 6], [7, 8], [9]]
|
||||
pub fn chunk[T](array []T, size int) [][]T {
|
||||
// allocate chunk array
|
||||
mut chunks := [][]T{cap: array.len / size + if array.len % size == 0 { 0 } else { 1 }}
|
||||
|
||||
for i := 0; true; {
|
||||
// check chunk size is greater than remaining element size
|
||||
if array.len < i + size {
|
||||
// check if there's no more element to chunk
|
||||
if array.len <= i {
|
||||
break
|
||||
}
|
||||
|
||||
chunks << array[i..]
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
chunks << array[i..i + size]
|
||||
i += size
|
||||
}
|
||||
|
||||
return chunks
|
||||
}
|
||||
|
||||
// chunk_while splits the input array `a` into chunks of varying length, using the `predicate`, passing to it pairs of adjacent elements `before` and `after`.
|
||||
// Each chunk, will contain all ajdacent elements, for which the `predicate` returned true.
|
||||
// The chunks are split *between* the `before` and `after` elements, for which the `predicate` returned false.
|
||||
// Example: assert arrays.chunk_while([0,9,2,2,3,2,7,5,9,5],fn(x int,y int)bool{return x<=y})==[[0,9],[2,2,3],[2,7],[5,9],[5]]
|
||||
// Example: assert arrays.chunk_while('aaaabbbcca'.runes(),fn(x rune,y rune)bool{return x==y})==[[`a`,`a`,`a`,`a`],[`b`,`b`,`b`],[`c`,`c`],[`a`]]
|
||||
// Example: assert arrays.chunk_while('aaaabbbcca'.runes(),fn(x rune,y rune)bool{return x==y}).map({it[0]:it.len})==[{`a`:4},{`b`:3},{`c`:2},{`a`:1}]
|
||||
pub fn chunk_while[T](a []T, predicate fn (before T, after T) bool) [][]T {
|
||||
if a.len == 0 {
|
||||
return []
|
||||
}
|
||||
mut chunks := [][]T{}
|
||||
mut current := [a[0]]
|
||||
mut i := 0
|
||||
for i = 1; i < a.len; i++ {
|
||||
if predicate(a[i - 1], a[i]) {
|
||||
current << a[i]
|
||||
continue
|
||||
}
|
||||
if current.len > 0 {
|
||||
chunks << current
|
||||
}
|
||||
current = [a[i]]
|
||||
}
|
||||
if current.len > 0 {
|
||||
chunks << current
|
||||
}
|
||||
return chunks
|
||||
}
|
||||
|
||||
pub struct WindowAttribute {
|
||||
pub:
|
||||
size int
|
||||
step int = 1
|
||||
}
|
||||
|
||||
// get snapshots of the window of the given size sliding along array with the given step, where each snapshot is an array.
|
||||
// - `size` - snapshot size
|
||||
// - `step` - gap size between each snapshot, default is 1.
|
||||
//
|
||||
// Example: arrays.window([1, 2, 3, 4], size: 2) // => [[1, 2], [2, 3], [3, 4]]
|
||||
// Example: arrays.window([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], size: 3, step: 2) // => [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9]]
|
||||
pub fn window[T](array []T, attr WindowAttribute) [][]T {
|
||||
if array.len == 0 {
|
||||
return [][]T{}
|
||||
}
|
||||
// allocate snapshot array
|
||||
mut windows := [][]T{cap: array.len - attr.size + 1}
|
||||
|
||||
for i := 0; true; {
|
||||
// check remaining elements size is less than snapshot size
|
||||
if array.len < i + attr.size {
|
||||
break
|
||||
}
|
||||
|
||||
windows << array[i..i + attr.size]
|
||||
i += attr.step
|
||||
}
|
||||
|
||||
return windows
|
||||
}
|
||||
|
||||
// sum up array, return an error, when the array has no elements.
|
||||
// Example: arrays.sum([1, 2, 3, 4, 5])! // => 15
|
||||
pub fn sum[T](array []T) !T {
|
||||
if array.len == 0 {
|
||||
return error('Cannot sum up array of nothing.')
|
||||
} else {
|
||||
mut head := array[0]
|
||||
|
||||
for e in array[1..] {
|
||||
head += e
|
||||
}
|
||||
|
||||
return head
|
||||
}
|
||||
}
|
||||
|
||||
// reduce sets `acc = array[0]`, then successively calls `acc = reduce_op(acc, elem)` for each remaining element in `array`.
|
||||
// returns the accumulated value in `acc`.
|
||||
// returns an error if the array is empty.
|
||||
// See also: [fold](#fold).
|
||||
// Example: arrays.reduce([1, 2, 3, 4, 5], fn (t1 int, t2 int) int { return t1 * t2 })! // => 120
|
||||
pub fn reduce[T](array []T, reduce_op fn (acc T, elem T) T) !T {
|
||||
if array.len == 0 {
|
||||
return error('Cannot reduce array of nothing.')
|
||||
} else {
|
||||
mut value := array[0]
|
||||
|
||||
for e in array[1..] {
|
||||
value = reduce_op(value, e)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
// reduce_indexed sets `acc = array[0]`, then successively calls `acc = reduce_op(idx, acc, elem)` for each remaining element in `array`.
|
||||
// returns the accumulated value in `acc`.
|
||||
// returns an error if the array is empty.
|
||||
// See also: [fold_indexed](#fold_indexed).
|
||||
pub fn reduce_indexed[T](array []T, reduce_op fn (idx int, acc T, elem T) T) !T {
|
||||
if array.len == 0 {
|
||||
return error('Cannot reduce array of nothing.')
|
||||
} else {
|
||||
mut value := array[0]
|
||||
|
||||
for i, e in array {
|
||||
if i == 0 {
|
||||
continue
|
||||
} else {
|
||||
value = reduce_op(i, value, e)
|
||||
}
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
// filter_indexed filters elements based on `predicate` function being invoked on each element with its index in the original array.
|
||||
pub fn filter_indexed[T](array []T, predicate fn (idx int, elem T) bool) []T {
|
||||
mut result := []T{cap: array.len}
|
||||
|
||||
for i, e in array {
|
||||
if predicate(i, e) {
|
||||
result << e
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// fold sets `acc = init`, then successively calls `acc = fold_op(acc, elem)` for each element in `array`.
|
||||
// returns `acc`.
|
||||
// Example:
|
||||
// ```v
|
||||
// // Sum the length of each string in an array
|
||||
// a := ['Hi', 'all']
|
||||
// r := arrays.fold[string, int](a, 0,
|
||||
// fn (r int, t string) int { return r + t.len })
|
||||
// assert r == 5
|
||||
// ```
|
||||
pub fn fold[T, R](array []T, init R, fold_op fn (acc R, elem T) R) R {
|
||||
$if R is $array {
|
||||
mut value := init.clone()
|
||||
for e in array {
|
||||
value = fold_op(value, e)
|
||||
}
|
||||
return value
|
||||
} $else {
|
||||
mut value := init
|
||||
for e in array {
|
||||
value = fold_op(value, e)
|
||||
}
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
// fold_indexed sets `acc = init`, then successively calls `acc = fold_op(idx, acc, elem)` for each element in `array`.
|
||||
// returns `acc`.
|
||||
pub fn fold_indexed[T, R](array []T, init R, fold_op fn (idx int, acc R, elem T) R) R {
|
||||
mut value := init
|
||||
|
||||
for i, e in array {
|
||||
value = fold_op(i, value, e)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
// flatten flattens n + 1 dimensional array into n dimensional array.
|
||||
// Example: arrays.flatten[int]([[1, 2, 3], [4, 5]]) // => [1, 2, 3, 4, 5]
|
||||
pub fn flatten[T](array [][]T) []T {
|
||||
// calculate required capacity
|
||||
mut required_size := 0
|
||||
|
||||
for e1 in array {
|
||||
for _ in e1 {
|
||||
required_size += 1
|
||||
}
|
||||
}
|
||||
|
||||
// allocate flattened array
|
||||
mut result := []T{cap: required_size}
|
||||
|
||||
for e1 in array {
|
||||
for e2 in e1 {
|
||||
result << e2
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// flat_map creates a new array populated with the flattened result of calling transform function being invoked on each element of `list`.
|
||||
pub fn flat_map[T, R](array []T, transform fn (elem T) []R) []R {
|
||||
mut result := [][]R{cap: array.len}
|
||||
|
||||
for v in array {
|
||||
result << transform(v)
|
||||
}
|
||||
|
||||
return flatten(result)
|
||||
}
|
||||
|
||||
// flat_map_indexed creates a new array with the flattened result of calling the `transform` fn, invoked on each idx,elem pair from the original.
|
||||
pub fn flat_map_indexed[T, R](array []T, transform fn (idx int, elem T) []R) []R {
|
||||
mut result := [][]R{cap: array.len}
|
||||
|
||||
for i, v in array {
|
||||
result << transform(i, v)
|
||||
}
|
||||
|
||||
return flatten(result)
|
||||
}
|
||||
|
||||
// map_indexed creates a new array with the result of calling the `transform` fn, invoked on each idx,elem pair from the original.
|
||||
pub fn map_indexed[T, R](array []T, transform fn (idx int, elem T) R) []R {
|
||||
mut result := []R{cap: array.len}
|
||||
|
||||
for i, v in array {
|
||||
result << transform(i, v)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// group_by groups together elements, for which the `grouping_op` callback produced the same result.
|
||||
// Example: arrays.group_by[int, string](['H', 'el', 'lo'], fn (v string) int { return v.len }) // => {1: ['H'], 2: ['el', 'lo']}
|
||||
pub fn group_by[K, V](array []V, grouping_op fn (val V) K) map[K][]V {
|
||||
mut result := map[K][]V{}
|
||||
|
||||
for v in array {
|
||||
key := grouping_op(v)
|
||||
|
||||
// check if key exists, if not, then create a new array with matched value, otherwise append.
|
||||
if key in result {
|
||||
result[key] << v
|
||||
} else {
|
||||
result[key] = [v]
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// concatenate an array with an arbitrary number of additional values.
|
||||
// NOTE: if you have two arrays, you should simply use the `<<` operator directly.
|
||||
// Example: assert arrays.concat([1, 2, 3], 4, 5, 6) == [1, 2, 3, 4, 5, 6]
|
||||
// Example: assert arrays.concat([1, 2, 3], ...[4, 5, 6]) == [1, 2, 3, 4, 5, 6]
|
||||
// Example: mut arr := arrays.concat([1, 2, 3], 4); arr << [10,20]; assert arr == [1,2,3,4,10,20] // note: arr is mutable
|
||||
pub fn concat[T](a []T, b ...T) []T {
|
||||
mut m := []T{cap: a.len + b.len}
|
||||
|
||||
m << a
|
||||
m << b
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
// returns the smallest element >= val, requires `array` to be sorted.
|
||||
// Example: arrays.lower_bound([2, 4, 6, 8], 3)! // => 4
|
||||
pub fn lower_bound[T](array []T, val T) !T {
|
||||
if array.len == 0 {
|
||||
return error('.lower_bound called on an empty array')
|
||||
}
|
||||
mut left, mut right := 0, array.len - 1
|
||||
for ; left <= right; {
|
||||
idx := (left + right) / 2
|
||||
elem := array[idx]
|
||||
if elem < val {
|
||||
left = idx + 1
|
||||
} else {
|
||||
right = idx - 1
|
||||
}
|
||||
}
|
||||
if left >= array.len {
|
||||
return error('')
|
||||
} else {
|
||||
return array[left]
|
||||
}
|
||||
}
|
||||
|
||||
// returns the largest element <= val, requires `array` to be sorted.
|
||||
// Example: arrays.upper_bound([2, 4, 6, 8], 3)! // => 2
|
||||
pub fn upper_bound[T](array []T, val T) !T {
|
||||
if array.len == 0 {
|
||||
return error('.upper_bound called on an empty array')
|
||||
}
|
||||
mut left, mut right := 0, array.len - 1
|
||||
for ; left <= right; {
|
||||
idx := (left + right) / 2
|
||||
elem := array[idx]
|
||||
if elem > val {
|
||||
right = idx - 1
|
||||
} else {
|
||||
left = idx + 1
|
||||
}
|
||||
}
|
||||
if right < 0 {
|
||||
return error('')
|
||||
} else {
|
||||
return array[right]
|
||||
}
|
||||
}
|
||||
|
||||
// binary_search, requires `array` to be sorted, returns index of found item or error.
|
||||
// Binary searches on sorted lists can be faster than other array searches because at maximum
|
||||
// the algorithm only has to traverse log N elements
|
||||
// Example: arrays.binary_search([1, 2, 3, 4], 4)! // => 3
|
||||
pub fn binary_search[T](array []T, target T) !int {
|
||||
mut left := 0
|
||||
mut right := array.len - 1
|
||||
for ; left <= right; {
|
||||
idx := (left + right) / 2
|
||||
elem := array[idx]
|
||||
if elem == target {
|
||||
return idx
|
||||
}
|
||||
if elem < target {
|
||||
left = idx + 1
|
||||
} else {
|
||||
right = idx - 1
|
||||
}
|
||||
}
|
||||
return error('')
|
||||
}
|
||||
|
||||
// rotate_left rotates the array in-place.
|
||||
// It does it in such a way, that the first `mid` elements of the array, move to the end,
|
||||
// while the last `array.len - mid` elements move to the front.
|
||||
// After calling `rotate_left`, the element previously at index `mid` will become the first element in the array.
|
||||
// Example:
|
||||
// ```v
|
||||
// mut x := [1,2,3,4,5,6]
|
||||
// arrays.rotate_left(mut x, 2)
|
||||
// println(x) // [3, 4, 5, 6, 1, 2]
|
||||
// ```
|
||||
pub fn rotate_left[T](mut array []T, mid int) {
|
||||
assert mid <= array.len && mid >= 0
|
||||
k := array.len - mid
|
||||
p := unsafe { &T(array.data) }
|
||||
unsafe {
|
||||
ptr_rotate[T](mid, &T(usize(voidptr(p)) + usize(sizeof(T)) * usize(mid)), k)
|
||||
}
|
||||
}
|
||||
|
||||
// rotate_right rotates the array in-place.
|
||||
// It does it in such a way, that the first `array.len - k` elements of the array, move to the end,
|
||||
// while the last `k` elements move to the front.
|
||||
// After calling `rotate_right`, the element previously at index `array.len - k` will become the first element in the array.
|
||||
// Example:
|
||||
// ```v
|
||||
// mut x := [1,2,3,4,5,6]
|
||||
// arrays.rotate_right(mut x, 2)
|
||||
// println(x) // [5, 6, 1, 2, 3, 4]
|
||||
// ```
|
||||
pub fn rotate_right[T](mut array []T, k int) {
|
||||
assert k <= array.len && k >= 0
|
||||
mid := array.len - k
|
||||
p := unsafe { &T(array.data) }
|
||||
unsafe {
|
||||
ptr_rotate[T](mid, &T(usize(voidptr(p)) + usize(sizeof(T)) * usize(mid)), k)
|
||||
}
|
||||
}
|
||||
|
||||
@[unsafe]
|
||||
fn ptr_rotate[T](left_ int, mid &T, right_ int) {
|
||||
sz := usize(sizeof(T))
|
||||
mut left := usize(left_)
|
||||
mut right := usize(right_)
|
||||
limit := raw_array_cap[T]()
|
||||
for {
|
||||
delta := if left < right { left } else { right }
|
||||
if delta <= usize(limit) {
|
||||
break
|
||||
}
|
||||
unsafe {
|
||||
swap_nonoverlapping[T](&T(usize(voidptr(mid)) - left * sz), &T(usize(voidptr(mid)) +
|
||||
usize(right - delta) * sz), int(delta))
|
||||
}
|
||||
if left <= right {
|
||||
right -= delta
|
||||
} else {
|
||||
left -= delta
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
rawarray := malloc(raw_array_malloc_size[T]())
|
||||
defer {
|
||||
free(rawarray)
|
||||
}
|
||||
dim := &T(usize(voidptr(mid)) - left * sz + right * sz)
|
||||
if left <= right {
|
||||
vmemcpy(rawarray, voidptr(usize(voidptr(mid)) - left * sz), isize(left * sz))
|
||||
vmemmove(voidptr(usize(voidptr(mid)) - left * sz), voidptr(mid), isize(right * sz))
|
||||
vmemcpy(voidptr(dim), rawarray, isize(left * sz))
|
||||
} else {
|
||||
vmemcpy(rawarray, voidptr(mid), isize(right * sz))
|
||||
vmemmove(voidptr(dim), voidptr(usize(voidptr(mid)) - left * sz), isize(left * sz))
|
||||
vmemcpy(voidptr(usize(voidptr(mid)) - left * sz), rawarray, isize(right * sz))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Block {
|
||||
mut:
|
||||
x u64
|
||||
y u64
|
||||
z u64
|
||||
w u64
|
||||
}
|
||||
|
||||
struct UnalignedBlock {
|
||||
mut:
|
||||
x u64
|
||||
y u64
|
||||
z u64
|
||||
w u64
|
||||
}
|
||||
|
||||
const extra_size = 32 * isize(sizeof(usize))
|
||||
|
||||
fn raw_array_cap[T]() isize {
|
||||
size := isize(sizeof(T))
|
||||
if size > extra_size {
|
||||
return 1
|
||||
} else {
|
||||
return extra_size / size
|
||||
}
|
||||
}
|
||||
|
||||
fn raw_array_malloc_size[T]() isize {
|
||||
size := isize(sizeof(T))
|
||||
if size > extra_size {
|
||||
return size * 2
|
||||
} else {
|
||||
return extra_size
|
||||
}
|
||||
}
|
||||
|
||||
@[unsafe]
|
||||
fn memswap(x voidptr, y voidptr, len usize) {
|
||||
block_size := isize(sizeof(Block))
|
||||
|
||||
mut i := usize(0)
|
||||
for i + usize(block_size) <= len {
|
||||
mut t_ := Block{}
|
||||
t := voidptr(&t_)
|
||||
|
||||
xi := usize(x) + i
|
||||
yi := usize(y) + i
|
||||
unsafe {
|
||||
vmemcpy(t, voidptr(xi), block_size)
|
||||
vmemcpy(voidptr(xi), voidptr(yi), block_size)
|
||||
vmemcpy(voidptr(yi), t, block_size)
|
||||
}
|
||||
i += usize(block_size)
|
||||
}
|
||||
if i < len {
|
||||
mut t_ := UnalignedBlock{}
|
||||
t := voidptr(&t_)
|
||||
rem := isize(len - i)
|
||||
xi := usize(x) + i
|
||||
yi := usize(y) + i
|
||||
unsafe {
|
||||
vmemcpy(t, voidptr(xi), rem)
|
||||
vmemcpy(voidptr(xi), voidptr(yi), rem)
|
||||
vmemcpy(voidptr(yi), t, rem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@[unsafe]
|
||||
fn swap_nonoverlapping[T](x_ &T, y_ &T, count int) {
|
||||
x := voidptr(x_)
|
||||
y := voidptr(y_)
|
||||
|
||||
len := usize(sizeof(T)) * usize(count)
|
||||
unsafe {
|
||||
memswap(x, y, len)
|
||||
}
|
||||
}
|
||||
|
||||
// copy copies the `src` array elements to the `dst` array.
|
||||
// The number of the elements copied is the minimum of the length of both arrays.
|
||||
// Returns the number of elements copied.
|
||||
pub fn copy[T](mut dst []T, src []T) int {
|
||||
min_len := if dst.len < src.len { dst.len } else { src.len }
|
||||
if min_len <= 0 {
|
||||
return 0
|
||||
}
|
||||
if can_copy_bits[T]() {
|
||||
blen := min_len * isize(sizeof(T))
|
||||
unsafe { vmemmove(&T(dst.data), src.data, blen) }
|
||||
} else {
|
||||
for i in 0 .. min_len {
|
||||
dst[i] = src[i]
|
||||
}
|
||||
}
|
||||
return min_len
|
||||
}
|
||||
|
||||
// can_copy_bits determines if T can be copied using `memcpy`.
|
||||
// false if autofree needs to intervene
|
||||
// false if type is not copyable e.g. map
|
||||
fn can_copy_bits[T]() bool {
|
||||
// references, C pointers, integers, floats, runes
|
||||
if T.name[0] in [`&`, `b`, `c`, `f`, `i`, `r`, `u`, `v`] {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// carray_to_varray copies a C byte array into a V array of type `T`.
|
||||
// See also: `cstring_to_vstring`
|
||||
@[unsafe]
|
||||
pub fn carray_to_varray[T](c_array_data voidptr, items int) []T {
|
||||
mut v_array := []T{len: items}
|
||||
total_size := items * isize(sizeof(T))
|
||||
unsafe { vmemcpy(v_array.data, c_array_data, total_size) }
|
||||
return v_array
|
||||
}
|
||||
|
||||
// find_first returns the first element that matches the given predicate.
|
||||
// Returns `none` if no match is found.
|
||||
// Example: arrays.find_first([1, 2, 3, 4, 5], fn (i int) bool { return i == 3 })? // => 3
|
||||
pub fn find_first[T](array []T, predicate fn (elem T) bool) ?T {
|
||||
if array.len == 0 {
|
||||
return none
|
||||
}
|
||||
for item in array {
|
||||
if predicate(item) {
|
||||
return item
|
||||
}
|
||||
}
|
||||
return none
|
||||
}
|
||||
|
||||
// find_last returns the last element that matches the given predicate.
|
||||
// Returns `none` if no match is found.
|
||||
// Example: arrays.find_last([1, 2, 3, 4, 5], fn (i int) bool { return i == 3})? // => 3
|
||||
pub fn find_last[T](array []T, predicate fn (elem T) bool) ?T {
|
||||
if array.len == 0 {
|
||||
return none
|
||||
}
|
||||
for idx := array.len - 1; idx >= 0; idx-- {
|
||||
item := array[idx]
|
||||
if predicate(item) {
|
||||
return item
|
||||
}
|
||||
}
|
||||
return none
|
||||
}
|
||||
|
||||
// join_to_string takes in a custom transform function and joins all elements into a string with
|
||||
// the specified separator
|
||||
@[manualfree]
|
||||
pub fn join_to_string[T](array []T, separator string, transform fn (elem T) string) string {
|
||||
mut sb := strings.new_builder(array.len * 2)
|
||||
defer {
|
||||
unsafe { sb.free() }
|
||||
}
|
||||
for i, item in array {
|
||||
x := transform(item)
|
||||
sb.write_string(x)
|
||||
unsafe { x.free() }
|
||||
if i < array.len - 1 {
|
||||
sb.write_string(separator)
|
||||
}
|
||||
}
|
||||
return sb.str()
|
||||
}
|
||||
|
||||
// partition splits the original array into pair of lists.
|
||||
// The first list contains elements for which the predicate fn returned true,
|
||||
// while the second list contains elements for which the predicate fn returned false.
|
||||
pub fn partition[T](array []T, predicate fn (elem T) bool) ([]T, []T) {
|
||||
mut matching, mut non_matching := []T{}, []T{}
|
||||
for item in array {
|
||||
if predicate(item) {
|
||||
matching << item
|
||||
} else {
|
||||
non_matching << item
|
||||
}
|
||||
}
|
||||
return matching, non_matching
|
||||
}
|
||||
|
||||
// each calls the callback fn `cb`, for each element of the given array `a`.
|
||||
pub fn each[T](a []T, cb fn (elem T)) {
|
||||
for item in a {
|
||||
cb(item)
|
||||
}
|
||||
}
|
||||
|
||||
// each_indexed calls the callback fn `cb`, for each element of the given array `a`.
|
||||
// It passes the callback both the index of the current element, and the element itself.
|
||||
pub fn each_indexed[T](a []T, cb fn (i int, e T)) {
|
||||
for idx, item in a {
|
||||
cb(idx, item)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import arrays
|
||||
|
||||
type MyInt = int
|
||||
|
||||
interface FoldCyclable {
|
||||
id() int
|
||||
}
|
||||
|
||||
struct FoldWheel {
|
||||
v int
|
||||
}
|
||||
|
||||
fn (w FoldWheel) id() int {
|
||||
return w.v
|
||||
}
|
||||
|
||||
fn test_main() {
|
||||
assert arrays.fold[int, []int]([1, 2, 3, 4], []int{}, fn (r []int, t int) []int {
|
||||
return arrays.merge(r, [t])
|
||||
}) == [1, 2, 3, 4]
|
||||
assert arrays.fold[string, []string](['a', 'b', 'c', 'd'], []string{}, fn (r []string, t string) []string {
|
||||
return arrays.merge(r, [t])
|
||||
}) == ['a', 'b', 'c', 'd']
|
||||
assert arrays.fold[bool, []bool]([true, false], []bool{}, fn (r []bool, t bool) []bool {
|
||||
return arrays.merge(r, [t])
|
||||
}) == [false, true]
|
||||
assert arrays.fold[MyInt, []MyInt]([MyInt(0), 1], []MyInt{}, fn (r []MyInt, t MyInt) []MyInt {
|
||||
return arrays.merge(r, [t])
|
||||
}) == [MyInt(0), 1]
|
||||
assert arrays.fold([1, 2, 3, 4], [5, 6, 7], fn (r []int, t int) []int {
|
||||
return r.map(it * t)
|
||||
}) == [120, 144, 168]
|
||||
}
|
||||
|
||||
fn test_fold_with_interface_accumulator() {
|
||||
items := [FoldWheel{1}, FoldWheel{2}]
|
||||
result := arrays.fold[FoldWheel, FoldCyclable](items, FoldCyclable(FoldWheel{}), fn (_ FoldCyclable, elem FoldWheel) FoldCyclable {
|
||||
return elem
|
||||
})
|
||||
assert result.id() == 2
|
||||
}
|
||||
@@ -0,0 +1,606 @@
|
||||
module arrays
|
||||
|
||||
fn test_min() {
|
||||
a := [8, 2, 6, 4]
|
||||
mut ri := min(a)!
|
||||
assert ri == 2
|
||||
ri = min(a[2..])!
|
||||
assert ri == 4
|
||||
b := [f32(5.1), 3.1, 1.1, 9.1]
|
||||
mut rf := min(b)!
|
||||
assert rf == f32(1.1)
|
||||
rf = min(b[..2])!
|
||||
assert rf == f32(3.1)
|
||||
c := [u8(4), 9, 3, 1]
|
||||
mut rb := min(c)!
|
||||
assert rb == u8(1)
|
||||
rb = min(c[..3])!
|
||||
assert rb == u8(3)
|
||||
}
|
||||
|
||||
fn test_max() {
|
||||
a := [8, 2, 6, 4]
|
||||
mut ri := max(a)!
|
||||
assert ri == 8
|
||||
ri = max(a[1..])!
|
||||
assert ri == 6
|
||||
b := [f32(5.1), 3.1, 1.1, 9.1]
|
||||
mut rf := max(b)!
|
||||
assert rf == f32(9.1)
|
||||
rf = max(b[..3])!
|
||||
assert rf == f32(5.1)
|
||||
c := [u8(4), 9, 3, 1]
|
||||
mut rb := max(c)!
|
||||
assert rb == u8(9)
|
||||
rb = max(c[2..])!
|
||||
assert rb == u8(3)
|
||||
}
|
||||
|
||||
fn test_idx_min() {
|
||||
a := [8, 2, 6, 4]
|
||||
ri := idx_min(a)!
|
||||
assert ri == 1
|
||||
b := [f32(5.1), 3.1, 1.1, 9.1]
|
||||
rf := idx_min(b)!
|
||||
assert rf == 2
|
||||
c := [u8(4), 9, 3, 1]
|
||||
rb := idx_min(c)!
|
||||
assert rb == 3
|
||||
}
|
||||
|
||||
fn test_idx_max() {
|
||||
a := [8, 2, 6, 4]
|
||||
ri := idx_max(a)!
|
||||
assert ri == 0
|
||||
b := [f32(5.1), 3.1, 1.1, 9.1]
|
||||
rf := idx_max(b)!
|
||||
assert rf == 3
|
||||
c := [u8(4), 9, 3, 1]
|
||||
rb := idx_max(c)!
|
||||
assert rb == 1
|
||||
}
|
||||
|
||||
fn test_merge() {
|
||||
a := [1, 3, 5, 5, 7]
|
||||
b := [2, 4, 4, 5, 6, 8]
|
||||
c := []int{}
|
||||
d := []int{}
|
||||
assert merge[int](a, b) == [1, 2, 3, 4, 4, 5, 5, 5, 6, 7, 8]
|
||||
assert merge[int](c, d) == []
|
||||
assert merge[int](a, c) == a
|
||||
assert merge[int](d, b) == b
|
||||
}
|
||||
|
||||
fn test_append() {
|
||||
a := [1, 3, 5, 5, 7]
|
||||
b := [2, 4, 4, 5, 6, 8]
|
||||
assert append(a, b) == [1, 3, 5, 5, 7, 2, 4, 4, 5, 6, 8]
|
||||
assert append(b, a) == [2, 4, 4, 5, 6, 8, 1, 3, 5, 5, 7]
|
||||
assert append(a, []int{}) == a
|
||||
assert append([]int{}, 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_array_flat_map() {
|
||||
a := ['Hello V', 'Hello World', 'V Lang']
|
||||
assert flat_map[string, string](a, fn (e string) []string {
|
||||
return e.split(' ')
|
||||
}) == ['Hello', 'V', 'Hello', 'World', 'V', 'Lang']
|
||||
}
|
||||
|
||||
fn test_array_flat_map_indexed() {
|
||||
a := ['AB', 'CD', 'EF']
|
||||
assert flat_map_indexed[string, string](a, fn (i int, e string) []string {
|
||||
mut arr := [i.str()]
|
||||
arr << e.split('')
|
||||
return arr
|
||||
}) == ['0', 'A', 'B', '1', 'C', 'D', '2', 'E', 'F']
|
||||
}
|
||||
|
||||
fn test_map_indexed() {
|
||||
a := [1, 2, 3]
|
||||
assert map_indexed[int, int](a, fn (i int, e int) int {
|
||||
return i + e * e
|
||||
}) == [1, 5, 11]
|
||||
}
|
||||
|
||||
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{}
|
||||
}
|
||||
|
||||
fn test_chunk() {
|
||||
x := [1, 2, 3, 4, 5]
|
||||
y := ['a', 'b', 'c', 'd', 'e', 'f']
|
||||
|
||||
z1 := chunk[int](x, 2)
|
||||
assert z1 == [[1, 2], [3, 4], [5]]
|
||||
z2 := chunk[string](y, 3)
|
||||
assert z2 == [['a', 'b', 'c'], ['d', 'e', 'f']]
|
||||
assert chunk[int]([]int{}, 2) == [][]int{}
|
||||
}
|
||||
|
||||
fn test_chunk_while() {
|
||||
assert chunk_while([0, 9, 2, 2, 3, 2, 7, 5, 9, 5], fn (x int, y int) bool {
|
||||
return x == y
|
||||
}) == [[0], [9], [2, 2], [3], [2], [7], [5], [9], [5]]
|
||||
|
||||
assert chunk_while([0, 9, 2, 2, 3, 2, 7, 5, 9, 5], fn (x int, y int) bool {
|
||||
return x <= y
|
||||
}) == [[0, 9], [2, 2, 3], [2, 7], [5, 9], [5]]
|
||||
|
||||
assert chunk_while('aaaabbbcca'.runes(), fn (x rune, y rune) bool {
|
||||
return x == y
|
||||
}).map({
|
||||
it[0]: it.len
|
||||
}).str() == '[{`a`: 4}, {`b`: 3}, {`c`: 2}, {`a`: 1}]'
|
||||
}
|
||||
|
||||
fn test_window() {
|
||||
x := [1, 2, 3, 4, 5, 6]
|
||||
|
||||
assert window[int](x, size: 3) == [[1, 2, 3], [2, 3, 4], [3, 4, 5],
|
||||
[4, 5, 6]]
|
||||
assert window[int](x, size: 3, step: 2) == [[1, 2, 3], [3, 4, 5]]
|
||||
assert window[int]([]int{}, size: 2) == [][]int{}
|
||||
}
|
||||
|
||||
/////////////////////////////
|
||||
type MyAlias = i64
|
||||
|
||||
fn (a MyAlias) + (b MyAlias) MyAlias {
|
||||
return MyAlias(i64(a) * 10 + i64(b) * 10)
|
||||
}
|
||||
|
||||
struct MyStruct {
|
||||
x int = 5
|
||||
}
|
||||
|
||||
fn (a MyStruct) + (b MyStruct) MyStruct {
|
||||
return MyStruct{
|
||||
x: a.x + b.x
|
||||
}
|
||||
}
|
||||
|
||||
fn test_sum() {
|
||||
assert sum([1, 2, 3, 4, 5]) or { 0 } == 15
|
||||
assert sum([1.0, 2.5, 3.5, 4.0]) or { 0.0 } == 11.0
|
||||
assert sum([]int{}) or { 0 } == 0
|
||||
// test summing of a struct, with an overloaded + operator:
|
||||
s := [MyStruct{
|
||||
x: 30
|
||||
}, MyStruct{
|
||||
x: 20
|
||||
}, MyStruct{
|
||||
x: 10
|
||||
}]
|
||||
assert sum(s)! == MyStruct{
|
||||
x: 60
|
||||
}
|
||||
// test summing of a number type alias with an overloaded + operator:
|
||||
assert sum([MyAlias(5), MyAlias(7), MyAlias(3)])! == MyAlias((5 * 10 + 7 * 10) * 10 + 3 * 10)
|
||||
}
|
||||
|
||||
/////////////////////////////
|
||||
fn test_reduce() {
|
||||
x := [1, 2, 3, 4, 5]
|
||||
|
||||
assert reduce[int](x, fn (t1 int, t2 int) int {
|
||||
return t1 + t2
|
||||
}) or { 0 } == 15
|
||||
assert reduce[string](['H', 'e', 'l', 'l', 'o'], fn (t1 string, t2 string) string {
|
||||
return t1 + t2
|
||||
}) or { '' } == 'Hello' // For the sake please use array's join instead.
|
||||
assert reduce[int]([]int{}, fn (t1 int, t2 int) int {
|
||||
return 0
|
||||
}) or { -1 } == -1
|
||||
}
|
||||
|
||||
fn test_reduce_indexed() {
|
||||
x := [1, 2, 3, 4, 5]
|
||||
assert reduce_indexed[int](x, fn (idx int, t1 int, t2 int) int {
|
||||
return idx + t1 + t2
|
||||
}) or { 0 } == 25
|
||||
}
|
||||
|
||||
fn test_filter_indexed() {
|
||||
x := [0, 1, 2, 3, 4, 5]
|
||||
|
||||
assert filter_indexed[int](x, fn (idx int, e int) bool {
|
||||
return idx % 2 == 0
|
||||
}) == [0, 2, 4]
|
||||
}
|
||||
|
||||
fn test_fold() {
|
||||
x := [1, 2, 3, 4, 5]
|
||||
|
||||
assert fold[int, int](x, 5, fn (r int, t int) int {
|
||||
return r + t
|
||||
}) == 20
|
||||
assert fold[string, int](['H', 'e', 'l', 'l', 'l'], 0, fn (r int, t string) int {
|
||||
return r + t[0]
|
||||
}) == 497
|
||||
assert fold[int, int]([]int{}, -1, fn (t1 int, t2 int) int {
|
||||
return 0
|
||||
}) == -1
|
||||
}
|
||||
|
||||
fn test_fold_indexed() {
|
||||
x := [1, 2, 3, 4, 5]
|
||||
|
||||
assert fold_indexed[int, int](x, 5, fn (idx int, r int, t int) int {
|
||||
return idx + r + t
|
||||
}) == 30
|
||||
}
|
||||
|
||||
fn test_flatten() {
|
||||
x := [[1, 2, 3], [4, 5, 6]]
|
||||
|
||||
assert flatten[int](x) == [1, 2, 3, 4, 5, 6]
|
||||
assert flatten[int]([[]int{}]) == []
|
||||
}
|
||||
|
||||
fn test_group_by() {
|
||||
x := ['H', 'el', 'l', 'o ']
|
||||
|
||||
assert group_by[int, string](x, fn (v string) int {
|
||||
return v.len
|
||||
}) == {
|
||||
1: ['H', 'l']
|
||||
2: ['el', 'o ']
|
||||
}
|
||||
assert group_by[int, int]([]int{}, fn (v int) int {
|
||||
return 0
|
||||
}) == map[int][]int{}
|
||||
}
|
||||
|
||||
fn test_concat_int() {
|
||||
mut a := [1, 2, 3]
|
||||
mut b := [3, 2, 1]
|
||||
|
||||
assert concat(a, ...b) == [1, 2, 3, 3, 2, 1]
|
||||
}
|
||||
|
||||
fn test_concat_string() {
|
||||
mut a := ['1', '2', '3']
|
||||
mut b := ['3', '2', '1']
|
||||
|
||||
assert concat(a, ...b) == ['1', '2', '3', '3', '2', '1']
|
||||
}
|
||||
|
||||
fn test_binary_search() {
|
||||
a := [1, 3, 3, 4, 5, 6, 7, 8, 10]
|
||||
assert binary_search(a, 3)! == 1
|
||||
assert (binary_search(a, 0) or { -1 }) == -1
|
||||
}
|
||||
|
||||
fn test_lower_bound() {
|
||||
a := [1, 3, 3, 4, 5, 6, 7, 8, 10]
|
||||
b := []int{}
|
||||
c := [1, 2, 3]
|
||||
assert lower_bound(a, 2)! == 3
|
||||
assert (lower_bound(b, 4) or { -1 }) == -1
|
||||
assert lower_bound(c, 3)! == 3
|
||||
}
|
||||
|
||||
fn test_upper_bound() {
|
||||
a := [1, 3, 3, 4, 5, 6, 7, 8, 10]
|
||||
b := []int{}
|
||||
c := [1, 2, 3]
|
||||
assert upper_bound(a, 9)! == 8
|
||||
assert (upper_bound(b, 4) or { -1 }) == -1
|
||||
assert upper_bound(c, 2)! == 2
|
||||
}
|
||||
|
||||
fn test_rotate_right() {
|
||||
mut x := [1, 2, 3, 4, 5, 6]
|
||||
rotate_right(mut x, 2)
|
||||
assert x == [5, 6, 1, 2, 3, 4]
|
||||
}
|
||||
|
||||
fn test_rotate_right_long() {
|
||||
mut x := []u64{len: 128, init: 255}
|
||||
x[0] = 0
|
||||
x[1] = 0
|
||||
x[2] = 0
|
||||
rotate_right(mut x, 64)
|
||||
assert x.len == 128
|
||||
idx := index_of_first(x, fn (idx int, x u64) bool {
|
||||
return x == 0
|
||||
})
|
||||
assert idx == 64
|
||||
assert x[idx - 1] == 255
|
||||
assert x[idx] == 0
|
||||
assert x[idx + 1] == 0
|
||||
assert x[idx + 2] == 0
|
||||
assert x[idx + 3] == 255
|
||||
}
|
||||
|
||||
fn test_rotate_left() {
|
||||
mut x := [1, 2, 3, 4, 5, 6]
|
||||
rotate_left(mut x, 2)
|
||||
assert x == [3, 4, 5, 6, 1, 2]
|
||||
}
|
||||
|
||||
struct Abc {
|
||||
x u64 = 1
|
||||
y u64 = 2
|
||||
z u64 = 3
|
||||
}
|
||||
|
||||
fn test_rotate_right_struct() {
|
||||
mut x := [Abc{1, 0, 1}, Abc{2, 0, 1}, Abc{3, 0, 1}, Abc{4, 0, 1},
|
||||
Abc{5, 0, 1}, Abc{6, 0, 1}]
|
||||
rotate_right(mut x, 2)
|
||||
assert x == [Abc{5, 0, 1}, Abc{6, 0, 1}, Abc{1, 0, 1}, Abc{2, 0, 1},
|
||||
Abc{3, 0, 1}, Abc{4, 0, 1}]
|
||||
}
|
||||
|
||||
fn test_rotate_left_struct() {
|
||||
mut x := [Abc{1, 0, 1}, Abc{2, 0, 1}, Abc{3, 0, 1}, Abc{4, 0, 1},
|
||||
Abc{5, 0, 1}, Abc{6, 0, 1}]
|
||||
rotate_left(mut x, 2)
|
||||
assert x == [Abc{3, 0, 1}, Abc{4, 0, 1}, Abc{5, 0, 1}, Abc{6, 0, 1},
|
||||
Abc{1, 0, 1}, Abc{2, 0, 1}]
|
||||
}
|
||||
|
||||
fn test_rotate_right_string() {
|
||||
mut x := ['x1', 'x2', 'x3', 'x4', 'x5', 'x6']
|
||||
rotate_right(mut x, 2)
|
||||
assert x == ['x5', 'x6', 'x1', 'x2', 'x3', 'x4']
|
||||
}
|
||||
|
||||
fn test_rotate_left_string() {
|
||||
mut x := ['x1', 'x2', 'x3', 'x4', 'x5', 'x6']
|
||||
rotate_left(mut x, 2)
|
||||
assert x == ['x3', 'x4', 'x5', 'x6', 'x1', 'x2']
|
||||
}
|
||||
|
||||
fn test_copy() {
|
||||
mut a := [1, 2, 3]
|
||||
mut b := [4, 5, 6]
|
||||
assert copy(mut b, a) == 3
|
||||
assert b == [1, 2, 3]
|
||||
// check independent copies
|
||||
b[0] = 99
|
||||
assert a[0] == 1
|
||||
// check longer src
|
||||
b << 7
|
||||
assert copy(mut a, b) == 3
|
||||
assert a == [99, 2, 3]
|
||||
// check longer dst
|
||||
assert copy(mut b, [8, 9]) == 2
|
||||
assert b == [8, 9, 3, 7]
|
||||
}
|
||||
|
||||
fn test_can_copy_bits() {
|
||||
assert can_copy_bits[u8]()
|
||||
assert can_copy_bits[int]()
|
||||
assert can_copy_bits[voidptr]()
|
||||
assert can_copy_bits[&u8]()
|
||||
// autofree needs to intercept assign
|
||||
assert !can_copy_bits[string]()
|
||||
assert !can_copy_bits[[]int]()
|
||||
// map not copyable
|
||||
assert !can_copy_bits[map[string]int]()
|
||||
}
|
||||
|
||||
type Str = string
|
||||
|
||||
fn test_alias_string_contains() {
|
||||
names := [Str('')]
|
||||
assert (Str('') in names) == true
|
||||
}
|
||||
|
||||
struct XYZ {}
|
||||
|
||||
fn test_array_append_empty_struct() {
|
||||
mut names := []XYZ{cap: 2}
|
||||
names << XYZ{}
|
||||
assert (XYZ{} in names) == true
|
||||
|
||||
// test fixed array
|
||||
array := [XYZ{}]!
|
||||
assert (XYZ{} in names) == true
|
||||
}
|
||||
|
||||
fn test_index_of_first() {
|
||||
// vfmt off
|
||||
assert index_of_first([1], fn (idx int, x int) bool { return x == 0 }) == -1
|
||||
assert index_of_first([4, 5, 0, 7, 0, 9], fn (idx int, x int) bool { return x == 0 }) == 2
|
||||
assert index_of_first([4, 5, 0, 7, 0, 9], fn (idx int, x int) bool { return x == 4 }) == 0
|
||||
// vfmt on
|
||||
}
|
||||
|
||||
fn test_index_of_last() {
|
||||
// vfmt off
|
||||
assert index_of_last([1], fn (idx int, x int) bool { return x == 0 }) == -1
|
||||
assert index_of_last([4, 5, 0, 7, 0, 9], fn (idx int, x int) bool { return x == 0 }) == 4
|
||||
assert index_of_last([4, 5, 0, 7, 0, 9], fn (idx int, x int) bool { return x == 4 }) == 0
|
||||
// vfmt on
|
||||
}
|
||||
|
||||
fn test_map_of_indexes() {
|
||||
// vfmt off
|
||||
assert arrays.map_of_indexes([]int{}) == {}
|
||||
assert arrays.map_of_indexes([1]) == {1: [0]}
|
||||
assert arrays.map_of_indexes([1, 2, 3, 999]) == {1: [0], 2: [1], 3: [2], 999: [3]}
|
||||
assert arrays.map_of_indexes([999, 1, 2, 3]) == {1: [1], 2: [2], 3: [3], 999: [0]}
|
||||
assert arrays.map_of_indexes([1, 2, 3, 4, 4, 2, 1, 4, 4, 999]) == {1: [0, 6], 2: [1, 5], 3: [2], 4: [3, 4, 7, 8], 999: [9]}
|
||||
|
||||
assert arrays.map_of_indexes([]string{}) == {}
|
||||
assert arrays.map_of_indexes(['abc']) == {'abc': [0]}
|
||||
assert arrays.map_of_indexes(['abc', 'abc']) == {'abc': [0, 1]}
|
||||
assert arrays.map_of_indexes(['abc', 'def', 'abc']) == {'abc': [0, 2], 'def': [1]}
|
||||
// vfmt on
|
||||
}
|
||||
|
||||
fn test_map_of_counts() {
|
||||
// vfmt off
|
||||
assert map_of_counts([]int{}) == {}
|
||||
assert map_of_counts([1]) == {1: 1}
|
||||
assert map_of_counts([1, 2, 3, 999]) == {1: 1, 2: 1, 3: 1, 999: 1}
|
||||
assert map_of_counts([999, 1, 2, 3]) == {1: 1, 2: 1, 3: 1, 999: 1}
|
||||
assert map_of_counts([1, 2, 3, 4, 4, 2, 1, 4, 4, 999]) == {1: 2, 2: 2, 3: 1, 4: 4, 999: 1}
|
||||
|
||||
assert map_of_counts([]string{}) == {}
|
||||
assert map_of_counts(['abc']) == {'abc': 1}
|
||||
assert map_of_counts(['abc', 'abc']) == {'abc': 2}
|
||||
assert map_of_counts(['abc', 'def', 'abc']) == {'abc': 2, 'def': 1}
|
||||
// vfmt on
|
||||
}
|
||||
|
||||
struct FindTest {
|
||||
name string
|
||||
age int
|
||||
}
|
||||
|
||||
const test_structs = [FindTest{'one', 1}, FindTest{'two', 2},
|
||||
FindTest{'three', 3}, FindTest{'one', 4}]
|
||||
|
||||
fn test_find_first() {
|
||||
// element in array
|
||||
a := [1, 2, 3, 4, 5]
|
||||
assert find_first[int](a, fn (arr int) bool {
|
||||
return arr == 3
|
||||
})? == 3, 'find element couldnt find the right element'
|
||||
|
||||
// find struct
|
||||
find_by_name := find_first(test_structs, fn (arr FindTest) bool {
|
||||
return arr.name == 'one'
|
||||
})?
|
||||
assert find_by_name == FindTest{'one', 1}
|
||||
|
||||
// not found
|
||||
if _ := find_first(test_structs, fn (arr FindTest) bool {
|
||||
return arr.name == 'nothing'
|
||||
})
|
||||
{
|
||||
assert false
|
||||
} else {
|
||||
assert true
|
||||
}
|
||||
}
|
||||
|
||||
fn test_find_last() {
|
||||
// // element in array
|
||||
a := [1, 2, 3, 4, 5]
|
||||
assert find_last[int](a, fn (arr int) bool {
|
||||
return arr == 3
|
||||
})? == 3, 'find element couldnt find the right element'
|
||||
|
||||
// find struct
|
||||
find_by_name := find_last(test_structs, fn (arr FindTest) bool {
|
||||
return arr.name == 'one'
|
||||
})?
|
||||
assert find_by_name == FindTest{'one', 4}
|
||||
|
||||
// not found
|
||||
if _ := find_last(test_structs, fn (arr FindTest) bool {
|
||||
return arr.name == 'nothing'
|
||||
})
|
||||
{
|
||||
assert false
|
||||
} else {
|
||||
assert true
|
||||
}
|
||||
}
|
||||
|
||||
fn test_join_to_string() {
|
||||
assert join_to_string[FindTest](test_structs, ':', fn (it FindTest) string {
|
||||
return it.name
|
||||
}) == 'one:two:three:one'
|
||||
assert join_to_string[FindTest](test_structs, '', fn (it FindTest) string {
|
||||
return it.name
|
||||
}) == 'onetwothreeone'
|
||||
assert join_to_string[int]([]int{}, ':', fn (it int) string {
|
||||
return '1'
|
||||
}) == ''
|
||||
}
|
||||
|
||||
fn test_partition() {
|
||||
a := [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
lower, upper := partition(a, fn (it int) bool {
|
||||
return it < 5
|
||||
})
|
||||
assert lower.len == 4
|
||||
assert upper.len == 4
|
||||
assert lower == [1, 2, 3, 4]
|
||||
assert upper == [5, 6, 7, 8]
|
||||
|
||||
lower2, upper2 := partition(a, fn (it int) bool {
|
||||
return it < 1
|
||||
})
|
||||
assert lower2.len == 0
|
||||
assert upper2.len == 8
|
||||
}
|
||||
|
||||
fn test_each() {
|
||||
a := [99, 1, 2, 3, 4, 5, 6, 7, 8, 1001]
|
||||
mut control_sum := 0
|
||||
for x in a {
|
||||
control_sum += x
|
||||
}
|
||||
|
||||
each(a, fn (x int) {
|
||||
println(x)
|
||||
})
|
||||
mut sum := 0
|
||||
mut psum := &sum
|
||||
each(a, fn [mut psum] (x int) {
|
||||
unsafe {
|
||||
*psum += x
|
||||
}
|
||||
})
|
||||
assert control_sum == sum
|
||||
}
|
||||
|
||||
fn test_each_indexed() {
|
||||
a := [99, 1, 2, 3, 4, 5, 6, 7, 8, 1001]
|
||||
mut control_sum := 0
|
||||
f := fn (idx int, x int) int {
|
||||
return (idx + 1) * 1000_000 + x
|
||||
}
|
||||
for idx, x in a {
|
||||
control_sum += f(idx, x)
|
||||
}
|
||||
|
||||
each_indexed(a, fn (idx int, x int) {
|
||||
println('idx: ${idx}, x: ${x}')
|
||||
})
|
||||
mut sum := 0
|
||||
mut psum := &sum
|
||||
each_indexed(a, fn [mut psum, f] (idx int, x int) {
|
||||
unsafe {
|
||||
*psum += f(idx, x)
|
||||
}
|
||||
})
|
||||
assert control_sum == sum
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
module diff
|
||||
|
||||
import strings
|
||||
|
||||
// DiffChange contains one or more deletions or inserts at one position in two arrays.
|
||||
pub struct DiffChange {
|
||||
pub mut:
|
||||
a int // position in input a []T
|
||||
b int // position in input b []T
|
||||
del int // delete Del elements from input a
|
||||
ins int // insert Ins elements from input b
|
||||
}
|
||||
|
||||
@[flag]
|
||||
enum DiffContextFlag {
|
||||
delete
|
||||
insert
|
||||
}
|
||||
|
||||
pub struct DiffContext[T] {
|
||||
mut:
|
||||
a []T
|
||||
b []T
|
||||
flags []DiffContextFlag
|
||||
max int
|
||||
// forward and reverse d-path endpoint x components
|
||||
forward []int
|
||||
reverse []int
|
||||
pub mut:
|
||||
changes []DiffChange
|
||||
}
|
||||
|
||||
// diff returns the difference of two arrays.
|
||||
pub fn diff[T](a []T, b []T) &DiffContext[T] {
|
||||
mut c := &DiffContext[T]{
|
||||
a: a
|
||||
b: b
|
||||
}
|
||||
c.flags = if a.len > b.len {
|
||||
[]DiffContextFlag{len: a.len}
|
||||
} else {
|
||||
[]DiffContextFlag{len: b.len}
|
||||
}
|
||||
c.max = a.len + b.len + 1
|
||||
c.forward = []int{len: 2 * c.max}
|
||||
c.reverse = []int{len: 2 * c.max}
|
||||
c.compare(0, 0, a.len, b.len)
|
||||
c.changes = c.result(a.len, b.len)
|
||||
return c
|
||||
}
|
||||
|
||||
// A directly conversion from https://github.com/covrom/diff
|
||||
// Fast diff library for Myers algorithm.
|
||||
// The algorithm is described in "An O(ND) Difference Algorithm and its Variations", Eugene Myers, Algorithmica Vol. 1 No. 2, 1986, pp. 251-266
|
||||
@[direct_array_access]
|
||||
fn (mut c DiffContext[T]) compare(mut_aoffset int, mut_boffset int, mut_alimit int, mut_blimit int) {
|
||||
mut aoffset := mut_aoffset
|
||||
mut boffset := mut_boffset
|
||||
mut alimit := mut_alimit
|
||||
mut blimit := mut_blimit
|
||||
// eat common prefix
|
||||
for aoffset < alimit && boffset < blimit && c.a[aoffset] == c.b[boffset] {
|
||||
aoffset++
|
||||
boffset++
|
||||
}
|
||||
// eat common suffix
|
||||
for alimit > aoffset && blimit > boffset && c.a[alimit - 1] == c.b[blimit - 1] {
|
||||
alimit--
|
||||
blimit--
|
||||
}
|
||||
// both equal or b inserts
|
||||
if aoffset == alimit {
|
||||
for boffset < blimit {
|
||||
c.flags[boffset].set(.insert)
|
||||
boffset++
|
||||
}
|
||||
return
|
||||
}
|
||||
// a deletes
|
||||
if boffset == blimit {
|
||||
for aoffset < alimit {
|
||||
c.flags[aoffset].set(.delete)
|
||||
aoffset++
|
||||
}
|
||||
return
|
||||
}
|
||||
x, y := c.find_middle_snake(aoffset, boffset, alimit, blimit)
|
||||
c.compare(aoffset, boffset, x, y)
|
||||
c.compare(x, y, alimit, blimit)
|
||||
}
|
||||
|
||||
@[direct_array_access]
|
||||
fn (mut c DiffContext[T]) find_middle_snake(aoffset int, boffset int, alimit int, blimit int) (int, int) {
|
||||
// midpoints
|
||||
fmid := aoffset - boffset
|
||||
rmid := alimit - blimit
|
||||
// correct offset in d-path slices
|
||||
foff := c.max - fmid
|
||||
roff := c.max - rmid
|
||||
isodd := (rmid - fmid) & 1 != 0
|
||||
maxd := (alimit - aoffset + blimit - boffset + 2) / 2
|
||||
c.forward[c.max + 1] = aoffset
|
||||
c.reverse[c.max - 1] = alimit
|
||||
mut x, mut y := 0, 0
|
||||
for d := 0; d <= maxd; d++ {
|
||||
// forward search
|
||||
for k := fmid - d; k <= fmid + d; k += 2 {
|
||||
if k == fmid - d || (k != fmid + d && c.forward[foff + k + 1] > c.forward[foff + k - 1]) {
|
||||
x = c.forward[foff + k + 1] // down
|
||||
} else {
|
||||
x = c.forward[foff + k - 1] + 1 // right
|
||||
}
|
||||
y = x - k
|
||||
for x < alimit && y < blimit && c.a[x] == c.b[y] {
|
||||
x++
|
||||
y++
|
||||
}
|
||||
c.forward[foff + k] = x
|
||||
if isodd && k > rmid - d && k < rmid + d {
|
||||
if c.reverse[roff + k] <= c.forward[foff + k] {
|
||||
return x, x - k
|
||||
}
|
||||
}
|
||||
}
|
||||
// reverse search x,y correspond to u,v
|
||||
for k := rmid - d; k <= rmid + d; k += 2 {
|
||||
if k == rmid + d || (k != rmid - d && c.reverse[roff + k - 1] < c.reverse[roff + k + 1]) {
|
||||
x = c.reverse[roff + k - 1] // up
|
||||
} else {
|
||||
x = c.reverse[roff + k + 1] - 1 // left
|
||||
}
|
||||
y = x - k
|
||||
for x > aoffset && y > boffset && c.a[x - 1] == c.b[y - 1] {
|
||||
x--
|
||||
y--
|
||||
}
|
||||
c.reverse[roff + k] = x
|
||||
if !isodd && k >= fmid - d && k <= fmid + d {
|
||||
if c.reverse[roff + k] <= c.forward[foff + k] {
|
||||
// lookup opposite end
|
||||
x = c.forward[foff + k]
|
||||
return x, x - k
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
panic('diff.find_middle_snake: should never be reached')
|
||||
}
|
||||
|
||||
@[direct_array_access]
|
||||
fn (c DiffContext[T]) result(n int, m int) []DiffChange {
|
||||
mut x, mut y := 0, 0
|
||||
mut res := []DiffChange{}
|
||||
for x < n || y < m {
|
||||
if x < n && y < m && !c.flags[x].has(.delete) && !c.flags[y].has(.insert) {
|
||||
x++
|
||||
y++
|
||||
} else {
|
||||
mut a := x
|
||||
mut b := y
|
||||
for x < n && (y >= m || c.flags[x].has(.delete)) {
|
||||
x++
|
||||
}
|
||||
for y < m && (x >= n || c.flags[y].has(.insert)) {
|
||||
y++
|
||||
}
|
||||
if a < x || b < y {
|
||||
res << DiffChange{a, b, x - a, y - b}
|
||||
}
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// merge_changes merges neighboring changes smaller than the specified context_lines.
|
||||
// The changes must be ordered by ascending positions.
|
||||
@[direct_array_access]
|
||||
fn (mut c DiffContext[T]) merge_changes(context_lines int) {
|
||||
if c.changes.len == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
mut merged := []DiffChange{}
|
||||
mut current := c.changes[0]
|
||||
|
||||
for i in 1 .. c.changes.len {
|
||||
next := c.changes[i]
|
||||
if next.a <= current.a + current.del + context_lines {
|
||||
current = DiffChange{
|
||||
a: current.a
|
||||
b: current.b
|
||||
del: next.a + next.del - current.a
|
||||
ins: next.b + next.ins - current.b
|
||||
}
|
||||
} else {
|
||||
merged << current
|
||||
current = next
|
||||
}
|
||||
}
|
||||
merged << current
|
||||
c.changes = merged
|
||||
}
|
||||
|
||||
@[params]
|
||||
pub struct DiffGenStrParam {
|
||||
pub mut:
|
||||
colorful bool
|
||||
unified int = 3 // how many context lines before/after diff block
|
||||
block_header bool // output `@@ -3,4 +3,5 @@` or not
|
||||
}
|
||||
|
||||
// generate_patch generate a diff string of two arrays.
|
||||
@[direct_array_access]
|
||||
pub fn (mut c DiffContext[T]) generate_patch(param DiffGenStrParam) string {
|
||||
mut sb := strings.new_builder(100)
|
||||
defer { unsafe { sb.free() } }
|
||||
|
||||
mut unified := if param.unified < 0 { 0 } else { param.unified }
|
||||
|
||||
c.merge_changes(unified)
|
||||
if c.changes.len == 0 {
|
||||
return ''
|
||||
}
|
||||
|
||||
mut prev_a_end := 0
|
||||
mut prev_b_end := 0
|
||||
|
||||
for change in c.changes {
|
||||
ctx_start_a := int_max(prev_a_end, change.a - unified)
|
||||
ctx_end_a := change.a + change.del + unified
|
||||
ctx_start_b := int_max(prev_b_end, change.b - unified)
|
||||
ctx_end_b := change.b + change.ins + unified
|
||||
|
||||
if param.block_header {
|
||||
if param.colorful {
|
||||
sb.write_string('\033[36m')
|
||||
}
|
||||
sb.writeln('@@ -${ctx_start_a + 1},${ctx_end_a - ctx_start_a} +${ctx_start_b + 1},${ctx_end_b - ctx_start_b} @@')
|
||||
if param.colorful {
|
||||
sb.write_string('\033[0m')
|
||||
}
|
||||
}
|
||||
|
||||
c.write_context(mut sb, ctx_start_b, change.b, param)
|
||||
c.write_change(mut sb, change, param)
|
||||
c.write_context(mut sb, change.b + change.ins, ctx_end_b, param)
|
||||
|
||||
prev_a_end = ctx_end_a
|
||||
prev_b_end = ctx_end_b
|
||||
}
|
||||
|
||||
return sb.str()
|
||||
}
|
||||
|
||||
@[direct_array_access]
|
||||
fn (c DiffContext[T]) write_context(mut sb strings.Builder,
|
||||
start int, end int,
|
||||
param DiffGenStrParam) {
|
||||
for i in start .. end {
|
||||
if i >= c.b.len {
|
||||
break
|
||||
}
|
||||
|
||||
line := c.b[i].str()
|
||||
|
||||
if param.colorful {
|
||||
sb.writeln('\033[37m${line}\033[0m')
|
||||
} else {
|
||||
sb.writeln(line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@[direct_array_access]
|
||||
fn (c DiffContext[T]) write_change(mut sb strings.Builder,
|
||||
change DiffChange,
|
||||
param DiffGenStrParam) {
|
||||
for i in change.a .. change.a + change.del {
|
||||
line := c.a[i].str()
|
||||
if param.colorful {
|
||||
sb.writeln('\033[31m-${line}\033[0m')
|
||||
} else {
|
||||
sb.writeln('-${line}')
|
||||
}
|
||||
}
|
||||
|
||||
for i in change.b .. change.b + change.ins {
|
||||
line := c.b[i].str()
|
||||
if param.colorful {
|
||||
sb.writeln('\033[32m+${line}\033[0m')
|
||||
} else {
|
||||
sb.writeln('+${line}')
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import arrays.diff
|
||||
|
||||
fn test_diff_array() {
|
||||
mut aa := ['hi', '1', '5', '3']
|
||||
mut bb := aa.clone()
|
||||
mut ctx := diff.diff(aa, bb)
|
||||
assert ctx.changes.len == 0
|
||||
bb.insert(2, 'max')
|
||||
// aa := ['hi', '1', '5', '3']
|
||||
// bb := ['hi', '1', 'max', '5', '3']
|
||||
ctx = diff.diff(aa, bb)
|
||||
assert ctx.changes == [
|
||||
diff.DiffChange{
|
||||
a: 2
|
||||
b: 2
|
||||
del: 0
|
||||
ins: 1
|
||||
},
|
||||
]
|
||||
|
||||
bb.delete(4)
|
||||
// aa := ['hi', '1', '5', '3']
|
||||
// bb := ['hi', '1', 'max', '5']
|
||||
ctx = diff.diff(aa, bb)
|
||||
assert ctx.changes == [
|
||||
diff.DiffChange{
|
||||
a: 2
|
||||
b: 2
|
||||
del: 0
|
||||
ins: 1
|
||||
},
|
||||
diff.DiffChange{
|
||||
a: 3
|
||||
b: 4
|
||||
del: 1
|
||||
ins: 0
|
||||
},
|
||||
]
|
||||
|
||||
str1 := ctx.generate_patch()
|
||||
assert str1 == 'hi
|
||||
1
|
||||
-5
|
||||
-3
|
||||
+max
|
||||
+5
|
||||
'
|
||||
|
||||
str2 := ctx.generate_patch(block_header: true)
|
||||
assert str2 == '@@ -1,7 +1,7 @@
|
||||
hi
|
||||
1
|
||||
-5
|
||||
-3
|
||||
+max
|
||||
+5
|
||||
'
|
||||
|
||||
str3 := ctx.generate_patch(block_header: true, unified: 1)
|
||||
assert str3 == '@@ -2,4 +2,4 @@
|
||||
1
|
||||
-5
|
||||
-3
|
||||
+max
|
||||
+5
|
||||
'
|
||||
str4 := ctx.generate_patch(block_header: true, unified: 10)
|
||||
assert str4 == '@@ -1,14 +1,14 @@
|
||||
hi
|
||||
1
|
||||
-5
|
||||
-3
|
||||
+max
|
||||
+5
|
||||
'
|
||||
|
||||
str5 := ctx.generate_patch(block_header: true, unified: -1)
|
||||
assert str5 == '@@ -3,2 +3,2 @@
|
||||
-5
|
||||
-3
|
||||
+max
|
||||
+5
|
||||
'
|
||||
}
|
||||
|
||||
fn test_diff_runes() {
|
||||
mut aa := 'brown fox jumps over the lazy dog'.runes()
|
||||
mut bb := 'brwn faax junps ovver the lay daog'.runes()
|
||||
mut ctx := diff.diff(aa, bb)
|
||||
|
||||
str1 := ctx.generate_patch()
|
||||
assert str1 == 'b
|
||||
r
|
||||
-o
|
||||
w
|
||||
n
|
||||
|
||||
f
|
||||
-o
|
||||
+a
|
||||
+a
|
||||
x
|
||||
|
||||
j
|
||||
u
|
||||
-m
|
||||
+n
|
||||
p
|
||||
s
|
||||
|
||||
o
|
||||
+v
|
||||
v
|
||||
e
|
||||
r
|
||||
|
||||
l
|
||||
a
|
||||
-z
|
||||
-y
|
||||
-
|
||||
-d
|
||||
+y
|
||||
+
|
||||
+d
|
||||
+a
|
||||
o
|
||||
g
|
||||
'
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
module arrays
|
||||
|
||||
// index_of_first returns the index of the first element of `array`, for which the predicate fn returns true.
|
||||
// If predicate does not return true for any of the elements, then index_of_first will return -1.
|
||||
// Example: assert arrays.index_of_first([4,5,0,7,0,9], fn(idx int, x int) bool { return x == 0 }) == 2
|
||||
pub fn index_of_first[T](array []T, predicate fn (idx int, elem T) bool) int {
|
||||
for i, e in array {
|
||||
if predicate(i, e) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// index_of_last returns the index of the last element of `array`, for which the predicate fn returns true.
|
||||
// If predicate does not return true for any of the elements, then index_of_last will return -1.
|
||||
// Example: assert arrays.index_of_last([4,5,0,7,0,9], fn(idx int, x int) bool { return x == 0 }) == 4
|
||||
pub fn index_of_last[T](array []T, predicate fn (idx int, elem T) bool) int {
|
||||
for i := array.len - 1; i >= 0; i-- {
|
||||
e := array[i]
|
||||
if predicate(i, e) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
module arrays
|
||||
|
||||
// map_of_indexes returns a map, where each key is an unique value in `array`.
|
||||
// Each value in that map for that key, is an array, containing the indexes in `array`, where that value has been found.
|
||||
// Example: assert arrays.map_of_indexes([1,2,3,4,4,2,1,4,4,999]) == {1: [0, 6], 2: [1, 5], 3: [2], 4: [3, 4, 7, 8], 999: [9]}
|
||||
pub fn map_of_indexes[T](array []T) map[T][]int {
|
||||
mut result := map[T][]int{}
|
||||
for i, e in array {
|
||||
if _ := result[e] {
|
||||
result[e] << i
|
||||
} else {
|
||||
result[e] = [i]
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// map_of_counts returns a map, where each key is an unique value in `array`.
|
||||
// Each value in that map for that key, is how many times that value occurs in `array`.
|
||||
// It can be useful for building histograms of discrete measurements.
|
||||
// Example: assert arrays.map_of_counts([1,2,3,4,4,2,1,4,4]) == {1: 2, 2: 2, 3: 1, 4: 4}
|
||||
pub fn map_of_counts[T](array []T) map[T]int {
|
||||
mut result := map[T]int{}
|
||||
for e in array {
|
||||
result[e]++
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
module parallel
|
||||
|
||||
import sync
|
||||
import runtime
|
||||
|
||||
// Params contains the optional parameters that can be passed to `run` and `amap`.
|
||||
@[params]
|
||||
pub struct Params {
|
||||
pub mut:
|
||||
workers int // 0 by default, so that VJOBS will be used, through runtime.nr_jobs()
|
||||
}
|
||||
|
||||
fn limited_workers(max_workers int, ilen int) int {
|
||||
// create a limited amount of workers to handle the load
|
||||
workers := if max_workers != 0 { max_workers } else { runtime.nr_jobs() }
|
||||
if ilen < workers {
|
||||
return ilen
|
||||
}
|
||||
return workers
|
||||
}
|
||||
|
||||
// run lets the user run an array of input with a user provided function in parallel.
|
||||
// It limits the number of worker threads to min(num_workers, num_cpu).
|
||||
// The function aborts if an error is encountered.
|
||||
// Example: parallel.run([1, 2, 3, 4, 5], |i| println(i))
|
||||
pub fn run[T](input []T, worker fn (T), opt Params) {
|
||||
if input.len == 0 {
|
||||
return
|
||||
}
|
||||
workers := limited_workers(opt.workers, input.len)
|
||||
ch := chan T{cap: workers * 2}
|
||||
mut wg := sync.new_waitgroup()
|
||||
wg.add(input.len)
|
||||
for _ in 0 .. workers {
|
||||
spawn fn [ch, worker, mut wg] [T]() {
|
||||
for {
|
||||
task := <-ch or { break }
|
||||
worker(task)
|
||||
wg.done()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// put the input into the channel
|
||||
for i in input {
|
||||
ch <- i
|
||||
}
|
||||
|
||||
// wait for all tasks to complete
|
||||
wg.wait()
|
||||
ch.close() // this will signal all the workers to exit, and we can return, without having to wait for them to finish
|
||||
}
|
||||
|
||||
struct Task[T, R] {
|
||||
idx int
|
||||
input T
|
||||
result R
|
||||
}
|
||||
|
||||
// amap lets the user run an array of input with a user provided function in parallel.
|
||||
// It limits the number of worker threads to max number of cpus.
|
||||
// The worker function can return a value. The returning array maintains the input order.
|
||||
// Any error handling should have happened within the worker function.
|
||||
// Example: squares := parallel.amap([1, 2, 3, 4, 5], |i| i * i); assert squares == [1, 4, 9, 16, 25]
|
||||
pub fn amap[T, R](input []T, worker fn (T) R, opt Params) []R {
|
||||
if input.len == 0 {
|
||||
return []
|
||||
}
|
||||
mut tasks := []Task[T, R]{len: input.len}
|
||||
// the tasks array will be passed to the closure of each worker by reference, so that it could
|
||||
// then modify the same tasks:
|
||||
mut tasks_ref := &tasks
|
||||
|
||||
workers := limited_workers(opt.workers, input.len)
|
||||
// use a buffered channel for transfering the tasks, that has enough space to keep all the workers busy,
|
||||
// without blocking the main thread needlessly
|
||||
ch := chan Task[T, R]{cap: workers * 2}
|
||||
mut wg := sync.new_waitgroup()
|
||||
wg.add(input.len)
|
||||
for _ in 0 .. workers {
|
||||
spawn fn [ch, worker, mut wg, mut tasks_ref] [T, R]() {
|
||||
for {
|
||||
mut task := <-ch or { break }
|
||||
unsafe {
|
||||
tasks_ref[task.idx] = Task[T, R]{
|
||||
idx: task.idx
|
||||
input: task.input
|
||||
result: worker(task.input)
|
||||
}
|
||||
}
|
||||
wg.done()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// put the input into the channel
|
||||
for idx, inp in input {
|
||||
ch <- Task[T, R]{
|
||||
idx: idx
|
||||
input: inp
|
||||
}
|
||||
}
|
||||
|
||||
// wait for all tasks to complete
|
||||
wg.wait()
|
||||
ch.close()
|
||||
tasks.sort(a.idx < b.idx)
|
||||
return tasks.map(it.result)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// vtest build: !musl?
|
||||
import arrays.parallel
|
||||
import rand
|
||||
import time
|
||||
|
||||
fn test_parallel_run_with_empty_arrays() {
|
||||
parallel.run([]int{}, fn (x int) {})
|
||||
parallel.run([]u8{}, fn (x u8) {})
|
||||
parallel.run([]u32{}, fn (x u32) {}, workers: 1000)
|
||||
assert true
|
||||
}
|
||||
|
||||
fn test_parallel_amap_with_empty_arrays() {
|
||||
assert parallel.amap([]int{}, fn (x int) u8 {
|
||||
return 0
|
||||
}) == []
|
||||
assert parallel.amap([]u8{}, fn (x u8) int {
|
||||
return 0
|
||||
}) == []
|
||||
assert parallel.amap([]u8{}, fn (x u8) int {
|
||||
return 0
|
||||
}, workers: 1000) == []
|
||||
assert true
|
||||
}
|
||||
|
||||
fn test_parallel_run() {
|
||||
counters := []int{len: 10, init: index}
|
||||
dump(counters)
|
||||
mut res := []string{len: 10}
|
||||
mut pres := &res
|
||||
parallel.run(counters, fn [mut pres] (i int) {
|
||||
delay := rand.intn(250) or { 250 }
|
||||
time.sleep(delay * time.millisecond)
|
||||
unsafe {
|
||||
pres[i] = 'task ${i}, delay=${delay}ms'
|
||||
}
|
||||
assert true
|
||||
})
|
||||
dump(res)
|
||||
assert res.len == counters.len
|
||||
}
|
||||
|
||||
fn test_parallel_amap() {
|
||||
input := [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
dump(input)
|
||||
dump(input.len)
|
||||
output := parallel.amap(input, fn (i int) int {
|
||||
delay := rand.intn(250) or { 250 }
|
||||
time.sleep(delay * time.millisecond)
|
||||
return i * i
|
||||
})
|
||||
dump(output)
|
||||
dump(output.len)
|
||||
assert input.len == output.len
|
||||
|
||||
for i, _ in output {
|
||||
assert output[i] == input[i] * input[i]
|
||||
}
|
||||
|
||||
// unordered output validation
|
||||
assert output.len == input.len
|
||||
op_sorted := output.sorted()
|
||||
dump(op_sorted)
|
||||
for i, op in op_sorted {
|
||||
assert op == input[i] * input[i]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
module arrays
|
||||
|
||||
// ReverseIterator provides a convenient way to iterate in reverse over all elements of an array without allocations.
|
||||
// I.e. it allows you to use this syntax: `for elem in arrays.reverse_iterator(a) {` .
|
||||
pub struct ReverseIterator[T] {
|
||||
mut:
|
||||
a []T
|
||||
i int
|
||||
}
|
||||
|
||||
// reverse_iterator can be used to iterate over the elements in an array.
|
||||
// i.e. you can use this syntax: `for elem in arrays.reverse_iterator(a) {` .
|
||||
pub fn reverse_iterator[T](a []T) ReverseIterator[T] {
|
||||
return ReverseIterator[T]{
|
||||
a: a
|
||||
i: a.len
|
||||
}
|
||||
}
|
||||
|
||||
// next is the required method, to implement an iterator in V.
|
||||
// It returns none when the iteration should stop.
|
||||
// Otherwise it returns the current element of the array.
|
||||
@[direct_array_access]
|
||||
pub fn (mut iter ReverseIterator[T]) next() ?&T {
|
||||
iter.i--
|
||||
if iter.i < 0 {
|
||||
return none
|
||||
}
|
||||
return unsafe { &iter.a[iter.i] }
|
||||
}
|
||||
|
||||
// free frees the iterator resources.
|
||||
pub fn (iter &ReverseIterator[T]) free() {
|
||||
// The array stored in the iterator is not owned by the iterator.
|
||||
// It should not be freed, when the iterator goes out of scope.
|
||||
// This is the reason, that this manual free method exists and is empty.
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import arrays
|
||||
|
||||
struct Compound {
|
||||
mut:
|
||||
s string
|
||||
i int
|
||||
u u64
|
||||
m map[string]i16
|
||||
}
|
||||
|
||||
fn check[T](original []T) {
|
||||
mut result := []T{cap: original.len}
|
||||
for x in arrays.reverse_iterator(original) {
|
||||
result << x
|
||||
}
|
||||
assert result.len == original.len
|
||||
assert result.first() == original.last()
|
||||
assert result.reverse() == original
|
||||
eprintln('> original: ${original}')
|
||||
eprintln('> result: ${result}')
|
||||
}
|
||||
|
||||
fn test_reverse_iterator_basic() {
|
||||
check(['abc', 'def', 'ghi', 'jkl'])
|
||||
check([10, 20, 30, 40])
|
||||
check([
|
||||
Compound{'abc', 123, 444, {
|
||||
'aa': i16(12)
|
||||
'bb': 31
|
||||
}},
|
||||
Compound{'def', 456, 555, {
|
||||
'bb': i16(22)
|
||||
'cc': 32
|
||||
}},
|
||||
Compound{'xyz', 789, 666, {
|
||||
'cc': i16(32)
|
||||
'dd': 33
|
||||
}},
|
||||
])
|
||||
}
|
||||
|
||||
fn test_reverse_iterator_with_mut() {
|
||||
mut original := [10, 20]
|
||||
mut before := []int{cap: original.len}
|
||||
mut after := []int{cap: original.len}
|
||||
for mut x in arrays.reverse_iterator(original) {
|
||||
before << *x
|
||||
(*x)++
|
||||
after << *x
|
||||
}
|
||||
assert before == [20, 10]
|
||||
assert after == [21, 11]
|
||||
assert original == [11, 21]
|
||||
}
|
||||
|
||||
fn test_reverse_iterator_with_mut_compound() {
|
||||
mut original := [Compound{
|
||||
s: 'abc'
|
||||
i: 123
|
||||
}, Compound{
|
||||
s: 'xyz'
|
||||
i: 987
|
||||
}]
|
||||
mut before := []Compound{cap: original.len}
|
||||
mut after := []Compound{cap: original.len}
|
||||
for mut x in arrays.reverse_iterator(original) {
|
||||
before << *x
|
||||
x.i++
|
||||
x.s += ' tail'
|
||||
x.u = 99
|
||||
x.m['modified'] = 1
|
||||
after << *x
|
||||
}
|
||||
assert after[0] == Compound{
|
||||
s: 'xyz tail'
|
||||
i: 988
|
||||
u: 99
|
||||
m: {
|
||||
'modified': i16(1)
|
||||
}
|
||||
}
|
||||
assert before[0] == Compound{
|
||||
s: 'xyz'
|
||||
i: 987
|
||||
u: 0
|
||||
m: {}
|
||||
}
|
||||
assert after.reverse() == original
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
module arrays
|
||||
|
||||
// uniq filters the adjacent matching elements from the given array.
|
||||
// All adjacent matching elements, are merged to their first occurrence,
|
||||
// so the output will have no repeating elements.
|
||||
// Note: `uniq` does not detect repeats, unless they are adjacent.
|
||||
// You may want to call a.sorted() on your array, before passing the result to arrays.uniq().
|
||||
// See also arrays.distinct, which is essentially arrays.uniq(a.sorted()) .
|
||||
// Example: assert arrays.uniq( []int{} ) == []
|
||||
// Example: assert arrays.uniq( [1, 1] ) == [1]
|
||||
// Example: assert arrays.uniq( [2, 1] ) == [2, 1]
|
||||
// Example: assert arrays.uniq( [5, 5, 1, 5, 2, 1, 1, 9] ) == [5, 1, 5, 2, 1, 9]
|
||||
pub fn uniq[T](a []T) []T {
|
||||
mut res := []T{cap: a.len / 10}
|
||||
mut j := -1
|
||||
if a.len > 0 {
|
||||
j = 0
|
||||
res << a[0]
|
||||
}
|
||||
for idx, e in a {
|
||||
if a[j] == e {
|
||||
continue
|
||||
}
|
||||
j = idx
|
||||
res << e
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// uniq_only filters the adjacent matching elements from the given array.
|
||||
// All adjacent matching elements, are removed.
|
||||
// The output will contain only the elements that *did not have* any adjacent matches.
|
||||
// Note: `uniq_only` does not detect repeats, unless they are adjacent.
|
||||
// You may want to call a.sorted() on your array, before passing the result to arrays.uniq_only().
|
||||
// Example: assert arrays.uniq_only( []int{} ) == []
|
||||
// Example: assert arrays.uniq_only( [1, 1] ) == []
|
||||
// Example: assert arrays.uniq_only( [2, 1] ) == [2, 1]
|
||||
// Example: assert arrays.uniq_only( [1, 5, 5, 1, 5, 2, 1, 1, 9] ) == [1, 1, 5, 2, 9]
|
||||
pub fn uniq_only[T](a []T) []T {
|
||||
// simple cases:
|
||||
if a.len == 0 {
|
||||
return []
|
||||
}
|
||||
if a.len == 1 {
|
||||
return a.clone()
|
||||
}
|
||||
if a.len == 2 {
|
||||
if a[0] != a[1] {
|
||||
return a.clone()
|
||||
}
|
||||
return []
|
||||
}
|
||||
mut res := []T{cap: a.len / 20}
|
||||
// head element:
|
||||
if a[0] != a[1] {
|
||||
res << a[0]
|
||||
}
|
||||
// middle elements:
|
||||
for idx := 1; idx + 1 < a.len; idx++ {
|
||||
if a[idx - 1] != a[idx] && a[idx + 1] != a[idx] {
|
||||
res << a[idx]
|
||||
}
|
||||
}
|
||||
// tail element:
|
||||
if a[a.len - 2] != a[a.len - 1] {
|
||||
res << a[a.len - 1]
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// uniq_only_repeated produces the adjacent matching elements from the given array.
|
||||
// Unique elements, with no duplicates are removed.
|
||||
// Adjacent matching elements, are reduced to just 1 element per repeat group.
|
||||
// Note: `uniq_only_repeated` does not detect repeats, unless they are adjacent.
|
||||
// You may want to call a.sorted() on your array, before passing the result to arrays.uniq_only_repeated().
|
||||
// Example: assert arrays.uniq_only_repeated( []int{} ) == []
|
||||
// Example: assert arrays.uniq_only_repeated( [1, 5] ) == []
|
||||
// Example: assert arrays.uniq_only_repeated( [5, 5] ) == [5]
|
||||
// Example: assert arrays.uniq_only_repeated( [5, 5, 1, 5, 2, 1, 1, 9] ) == [5, 1]
|
||||
pub fn uniq_only_repeated[T](a []T) []T {
|
||||
// simple cases:
|
||||
if a.len == 0 || a.len == 1 {
|
||||
return []
|
||||
}
|
||||
mut res := []T{cap: a.len / 20}
|
||||
loop: for i := 0; i + 1 < a.len; i++ {
|
||||
if a[i] == a[i + 1] {
|
||||
// at least 2 match; find the span length:
|
||||
for j := i + 2; j < a.len; j++ {
|
||||
if a[i] != a[j] {
|
||||
// found the right border of the repeated elements
|
||||
if j - i > 1 {
|
||||
res << a[i]
|
||||
i = j - 1
|
||||
continue loop
|
||||
}
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
// tail element:
|
||||
if a[a.len - 2] == a[a.len - 1] {
|
||||
res << a[a.len - 1]
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// uniq_all_repeated produces all adjacent matching elements from the given array.
|
||||
// Unique elements, with no duplicates are removed.
|
||||
// The output will contain all the duplicated elements, repeated just like they were in the original.
|
||||
// Note: `uniq_all_repeated` does not detect repeats, unless they are adjacent.
|
||||
// You may want to call a.sorted() on your array, before passing the result to arrays.uniq_all_repeated().
|
||||
// Example: assert arrays.uniq_all_repeated( []int{} ) == []
|
||||
// Example: assert arrays.uniq_all_repeated( [1, 5] ) == []
|
||||
// Example: assert arrays.uniq_all_repeated( [5, 5] ) == [5,5]
|
||||
// Example: assert arrays.uniq_all_repeated( [5, 5, 1, 5, 2, 1, 1, 9] ) == [5, 5, 1, 1]
|
||||
pub fn uniq_all_repeated[T](a []T) []T {
|
||||
// simple cases:
|
||||
if a.len == 0 || a.len == 1 {
|
||||
return []
|
||||
}
|
||||
if a.len == 2 {
|
||||
if a[0] == a[1] {
|
||||
return a.clone()
|
||||
}
|
||||
}
|
||||
mut res := []T{cap: a.len / 20}
|
||||
loop: for i := 0; i + 1 < a.len; i++ {
|
||||
if a[i] == a[i + 1] {
|
||||
res << a[i]
|
||||
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 - 1
|
||||
continue loop
|
||||
}
|
||||
res << a[i]
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// distinct returns all distinct elements from the given array a.
|
||||
// The results are guaranteed to be unique, i.e. not have duplicates.
|
||||
// See also arrays.uniq, which can be used to achieve the same goal,
|
||||
// but needs you to first sort the array.
|
||||
// Example: assert arrays.distinct( [5, 5, 1, 5, 2, 1, 1, 9] ) == [1, 2, 5, 9]
|
||||
pub fn distinct[T](a []T) []T {
|
||||
return uniq(a.sorted(a < b))
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import arrays
|
||||
|
||||
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()
|
||||
|
||||
fn test_uniq() {
|
||||
assert arrays.uniq([]int{}) == []
|
||||
assert arrays.uniq([1, 1]) == [1]
|
||||
assert arrays.uniq([2, 1]) == [2, 1]
|
||||
assert arrays.uniq(a) == [1, 5, 1, 5, 2, 1, 9, 2]
|
||||
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() {
|
||||
assert arrays.uniq_only([]int{}) == []
|
||||
assert arrays.uniq_only([1, 5]) == [1, 5]
|
||||
assert arrays.uniq_only([5, 5]) == []
|
||||
assert arrays.uniq_only([5, 1, 1]) == [5]
|
||||
assert arrays.uniq_only(a) == [1, 1, 5, 2, 9, 2]
|
||||
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() {
|
||||
assert arrays.uniq_only_repeated([]int{}) == []
|
||||
assert arrays.uniq_only_repeated([1, 5]) == []
|
||||
assert arrays.uniq_only_repeated([5, 5]) == [5]
|
||||
assert arrays.uniq_only_repeated([5, 5, 5]) == [5]
|
||||
assert arrays.uniq_only_repeated([5, 1, 1]) == [1]
|
||||
assert arrays.uniq_only_repeated([1, 1, 5]) == [1]
|
||||
assert arrays.uniq_only_repeated([1, 5, 1]) == []
|
||||
assert arrays.uniq_only_repeated([0, 5, 1, 1]) == [1]
|
||||
assert arrays.uniq_only_repeated([0, 1, 1, 5]) == [1]
|
||||
assert arrays.uniq_only_repeated([0, 1, 5, 1]) == []
|
||||
assert arrays.uniq_only_repeated([5, 1, 1, 0]) == [1]
|
||||
assert arrays.uniq_only_repeated([1, 1, 5, 0]) == [1]
|
||||
assert arrays.uniq_only_repeated([1, 5, 1, 0]) == []
|
||||
assert arrays.uniq_only_repeated([5, 5, 5, 5, 1]) == [5]
|
||||
assert arrays.uniq_only_repeated([1, 5, 5, 5, 5, 1]) == [5]
|
||||
assert arrays.uniq_only_repeated([1, 5, 5, 2, 5, 5, 3]) == [5, 5]
|
||||
assert arrays.uniq_only_repeated([1, 5, 5, 2, 5, 5, 3, 5]) == [5, 5]
|
||||
assert arrays.uniq_only_repeated([1, 5, 5, 2, 5, 5, 3, 5, 5]) == [5, 5, 5]
|
||||
assert arrays.uniq_only_repeated([5, 1, 5, 5, 2, 5, 5, 3, 5, 5]) == [5, 5, 5]
|
||||
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, 2, 5]
|
||||
assert arrays.uniq_only_repeated(many_repeats) == [1, 2, 5, 1, 5]
|
||||
}
|
||||
|
||||
fn test_uniq_all_repeated() {
|
||||
assert arrays.uniq_all_repeated([]int{}) == []
|
||||
assert arrays.uniq_all_repeated([1, 5]) == []
|
||||
assert arrays.uniq_all_repeated([5, 5]) == [5, 5]
|
||||
assert arrays.uniq_all_repeated([5, 5, 5]) == [5, 5, 5]
|
||||
assert arrays.uniq_all_repeated([5, 1, 1]) == [1, 1]
|
||||
assert arrays.uniq_all_repeated([1, 1, 5]) == [1, 1]
|
||||
assert arrays.uniq_all_repeated([1, 5, 1]) == []
|
||||
assert arrays.uniq_all_repeated([0, 5, 1, 1]) == [1, 1]
|
||||
assert arrays.uniq_all_repeated([0, 1, 1, 5]) == [1, 1]
|
||||
assert arrays.uniq_all_repeated([0, 1, 5, 1]) == []
|
||||
assert arrays.uniq_all_repeated([5, 1, 1, 0]) == [1, 1]
|
||||
assert arrays.uniq_all_repeated([1, 1, 5, 0]) == [1, 1]
|
||||
assert arrays.uniq_all_repeated([1, 5, 1, 0]) == []
|
||||
assert arrays.uniq_all_repeated([5, 5, 5, 5, 1]) == [5, 5, 5, 5]
|
||||
assert arrays.uniq_all_repeated([1, 5, 5, 5, 5, 1]) == [5, 5, 5, 5]
|
||||
assert arrays.uniq_all_repeated([1, 5, 5, 2, 5, 5, 3]) == [5, 5, 5, 5]
|
||||
assert arrays.uniq_all_repeated([1, 5, 5, 2, 5, 5, 3, 5]) == [5, 5, 5, 5]
|
||||
assert arrays.uniq_all_repeated([1, 5, 5, 2, 5, 5, 3, 5, 5]) == [5, 5, 5, 5, 5, 5]
|
||||
assert arrays.uniq_all_repeated([5, 1, 5, 5, 2, 5, 5, 3, 5, 5]) == [5, 5, 5, 5, 5, 5]
|
||||
assert arrays.uniq_all_repeated([5, 5, 1, 5, 5, 2, 5, 5, 3, 5, 5]) == [5, 5, 5, 5, 5, 5, 5,
|
||||
5]
|
||||
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, 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]
|
||||
}
|
||||
Reference in new issue
Block a user