Skip to content

Fixing permutation of small lists, such that [], [x] -> [[]], [[x]] #13783

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

Merged
merged 1 commit into from
Apr 27, 2014
Merged
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
55 changes: 48 additions & 7 deletions src/libstd/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,7 @@ pub struct ElementSwaps {
sdir: ~[SizeDirection],
/// If true, emit the last swap that returns the sequence to initial state
emit_reset: bool,
swaps_made : uint,
}

impl ElementSwaps {
Expand All @@ -319,7 +320,8 @@ impl ElementSwaps {
emit_reset: true,
sdir: range(0, length)
.map(|i| SizeDirection{ size: i, dir: Neg })
.collect::<~[_]>()
.collect::<~[_]>(),
swaps_made: 0
}
}
}
Expand Down Expand Up @@ -358,16 +360,30 @@ impl Iterator<(uint, uint)> for ElementSwaps {
x.dir = match x.dir { Pos => Neg, Neg => Pos };
}
}
self.swaps_made += 1;
Some((i, j))
},
None => if self.emit_reset && self.sdir.len() > 1 {
None => if self.emit_reset {
self.emit_reset = false;
Some((0, 1))
} else {
None
}
if self.sdir.len() > 1 {
// The last swap
self.swaps_made += 1;
Some((0, 1))
} else {
// Vector is of the form [] or [x], and the only permutation is itself
self.swaps_made += 1;
Some((0,0))
}
} else { None }
}
}

#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
// For a vector of size n, there are exactly n! permutations.
let n = range(2, self.sdir.len() + 1).product();
(n - self.swaps_made, Some(n - self.swaps_made))
}
}

/// An Iterator that uses `ElementSwaps` to iterate through
Expand All @@ -388,13 +404,19 @@ impl<T: Clone> Iterator<~[T]> for Permutations<T> {
fn next(&mut self) -> Option<~[T]> {
match self.swaps.next() {
None => None,
Some((0,0)) => Some(self.v.clone()),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you find it necessary to have this case? I think that swap handles the case where the two indices are the same.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@alexcrichton: I had two reasons:

  1. For an empty list, there is no item 0, and that would be bad.
  2. (Not as important) For a non-empty list, AFAICT there is no code in either slice::swap or ptr::swap stopping it from actually performing the swap, i.e. copying item 0 to a temporary value, moving item 0 to item 0, and then copying the temp value back in. That seemed unnecessary...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, of course!

Some((a, b)) => {
let elt = self.v.clone();
self.v.swap(a, b);
Some(elt)
}
}
}

#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
self.swaps.size_hint()
}
}

/// An iterator over the (overlapping) slices of length `size` within
Expand Down Expand Up @@ -2767,19 +2789,33 @@ mod tests {
{
let v: [int, ..0] = [];
let mut it = v.permutations();
let (min_size, max_opt) = it.size_hint();
assert_eq!(min_size, 1);
assert_eq!(max_opt.unwrap(), 1);
assert_eq!(it.next(), Some(v.as_slice().to_owned()));
assert_eq!(it.next(), None);
}
{
let v = ["Hello".to_owned()];
let mut it = v.permutations();
let (min_size, max_opt) = it.size_hint();
assert_eq!(min_size, 1);
assert_eq!(max_opt.unwrap(), 1);
assert_eq!(it.next(), Some(v.as_slice().to_owned()));
assert_eq!(it.next(), None);
}
{
let v = [1, 2, 3];
let mut it = v.permutations();
let (min_size, max_opt) = it.size_hint();
assert_eq!(min_size, 3*2);
assert_eq!(max_opt.unwrap(), 3*2);
assert_eq!(it.next(), Some(~[1,2,3]));
assert_eq!(it.next(), Some(~[1,3,2]));
assert_eq!(it.next(), Some(~[3,1,2]));
let (min_size, max_opt) = it.size_hint();
assert_eq!(min_size, 3);
assert_eq!(max_opt.unwrap(), 3);
assert_eq!(it.next(), Some(~[3,2,1]));
assert_eq!(it.next(), Some(~[2,3,1]));
assert_eq!(it.next(), Some(~[2,1,3]));
Expand All @@ -2789,10 +2825,15 @@ mod tests {
// check that we have N! permutations
let v = ['A', 'B', 'C', 'D', 'E', 'F'];
let mut amt = 0;
for _perm in v.permutations() {
let mut it = v.permutations();
let (min_size, max_opt) = it.size_hint();
for _perm in it {
amt += 1;
}
assert_eq!(amt, it.swaps.swaps_made);
assert_eq!(amt, min_size);
assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
assert_eq!(amt, max_opt.unwrap());
}
}

Expand Down