Skip to content

Commit

Permalink
fix: make permutation types generic
Browse files Browse the repository at this point in the history
  • Loading branch information
wfee2000 committed Dec 23, 2024
1 parent 9d0c4a0 commit 89c25cc
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
18 changes: 9 additions & 9 deletions iter/perm.v
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,31 @@ module iter
import vsl.util
import math

pub struct PermutationsIter {
pub struct PermutationsIter[T] {
mut:
pos u64
idxs []int
cycles []int
pub:
repeat int
size u64
data []f64
data []T
}

// PermutationsIter.new will return an iterator that allows
// lazy computation for all length `r` permutations of `data`
pub fn PermutationsIter.new(data []f64, r int) PermutationsIter {
pub fn PermutationsIter.new[T](data []T, r int) PermutationsIter[T] {
n := data.len
if r > n {
return PermutationsIter{
return PermutationsIter[T]{
data: data
repeat: r
}
}
size := u64(math.factorial(n) / math.factorial(n - r))
idxs := util.arange(n)
cycles := util.range(n, n - r, step: -1)
return PermutationsIter{
return PermutationsIter[T]{
data: data
repeat: r
size: size
Expand All @@ -37,7 +37,7 @@ pub fn PermutationsIter.new(data []f64, r int) PermutationsIter {
}

// next will return next permutation if possible
pub fn (mut o PermutationsIter) next() ?[]f64 {
pub fn (mut o PermutationsIter[T]) next[T]() ?[]T {
// base case for every iterator
if o.pos == o.size {
return none
Expand Down Expand Up @@ -69,9 +69,9 @@ pub fn (mut o PermutationsIter) next() ?[]f64 {
}

// permutations returns successive `r` length permutations of elements in `data`
pub fn permutations(data []f64, r int) [][]f64 {
mut perms := PermutationsIter.new(data, r)
mut result := [][]f64{cap: int(perms.size)}
pub fn permutations[T](data []T, r int) [][]T {
mut perms := PermutationsIter.new[T](data, r)
mut result := [][]T{cap: int(perms.size)}
for perm in perms {
result << perm
}
Expand Down
17 changes: 16 additions & 1 deletion iter/perm_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,22 @@ fn test_permutations_simple_5() {
assert assert_permutation(expected, result)
}

fn assert_permutation(a [][]f64, b [][]f64) bool {
fn test_permutations_generic_type_string() {
data := ['a', 'b', 'c']
expected := [['a', 'b'], ['a', 'c'], ['b', 'a'], ['b', 'c'],
['c', 'a'], ['c', 'b']]
result := permutations(data, 2)
assert assert_permutation(expected, result)
}

fn test_permutations_generic_type_int() {
data := [1, 2, 3]
expected := [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]
result := permutations(data, 2)
assert assert_permutation(expected, result)
}

fn assert_permutation[T](a [][]T, b [][]T) bool {
if a.len != b.len {
return false
}
Expand Down

0 comments on commit 89c25cc

Please sign in to comment.