Skip to content

Add vec::permute to the standard library #1121

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/lib/vec.rs
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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