Skip to content

Commit

Permalink
Add vec::permute to the standard library (#1013)
Browse files Browse the repository at this point in the history
  • Loading branch information
mbrubeck authored and brson committed Nov 2, 2011
1 parent 558ca9b commit 5970e9c
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/lib/vec.rs
Expand Up @@ -734,6 +734,31 @@ fn riter2<T>(v: [mutable? T], f: block(uint, T)) {
};
}

/*
Function: permute
Iterate over all permutations of vector `v`. Permutations are produced in
lexicographic order with respect to the order of elements in `v` (so if `v`
is sorted then the permutations are lexicographically sorted).
The total number of permutations produced is `len(v)!`. If `v` contains
repeated elements, then some permutations are repeated.
*/
fn permute<T>(v: [mutable? T], put: block([T])) {
let ln = len(v);
if ln == 0u {
put([]);
} else {
let i = 0u;
while i < ln {
let elt = v[i];
let rest = slice(v, 0u, i) + slice(v, i+1u, ln);
permute(rest) {|permutation| put([elt] + permutation)}
i += 1u;
}
}
}

/*
Function: to_ptr
Expand Down
21 changes: 21 additions & 0 deletions src/test/stdtest/vec.rs
Expand Up @@ -366,6 +366,27 @@ fn riter2() {
assert i == 3;
}

#[test]
fn test_permute() {
let results: [[int]];

results = [];
permute([]) {|v| results += [v]; }
assert results == [[]];

results = [];
permute([7]) {|v| results += [v]; }
assert results == [[7]];

results = [];
permute([1,1]) {|v| results += [v]; }
assert results == [[1,1],[1,1]];

results = [];
permute([5,2,0]) {|v| results += [v]; }
assert results == [[5,2,0],[5,0,2],[2,5,0],[2,0,5],[0,5,2],[0,2,5]];
}

#[test]
fn test_any_and_all() {
assert (vec::any(is_three, [1u, 2u, 3u]));
Expand Down

0 comments on commit 5970e9c

Please sign in to comment.