permutohedron-0.2.4/.travis.yml 0100644 0001751 0001751 00000000700 12660633450 0014746 0 ustar 00 0000000 0000000 language: rust
sudo: false
matrix:
include:
- rust: stable
- rust: beta
- rust: nightly
env:
- BENCH=1
branches:
only:
- master
script:
- |
cargo build --verbose --features "$FEATURES"
cargo build --verbose --no-default-features
cargo test --verbose --features "$FEATURES"
[ "$BENCH" != 1 ] || cargo bench --verbose --features "$FEATURES"
cargo doc --verbose --features "$FEATURES"
permutohedron-0.2.4/Cargo.toml.orig 0100644 0001751 0001751 00000001070 13201543366 0015523 0 ustar 00 0000000 0000000 [package]
name = "permutohedron"
version = "0.2.4"
authors = ["bluss"]
license = "MIT/Apache-2.0"
repository = "https://github.com/bluss/permutohedron"
documentation = "https://docs.rs/permutohedron/"
description = "Generate permutations of sequences. Either lexicographical order permutations, or a minimal swaps permutation sequence implemented using Heap's algorithm."
keywords = ["permutations", "heaps-algorithm", "lexicographic", "no_std"]
[profile.bench]
debug = true
[features]
std = []
default = ["std"]
[package.metadata.release]
no-dev-version = true
permutohedron-0.2.4/Cargo.toml 0000644 00000002077 0010755 0 ustar 00 # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g. crates.io) dependencies
#
# If you believe there's an error in this file please file an
# issue against the rust-lang/cargo repository. If you're
# editing this file be aware that the upstream Cargo.toml
# will likely look very different (and much more reasonable)
[package]
name = "permutohedron"
version = "0.2.4"
authors = ["bluss"]
description = "Generate permutations of sequences. Either lexicographical order permutations, or a minimal swaps permutation sequence implemented using Heap's algorithm."
documentation = "https://docs.rs/permutohedron/"
keywords = ["permutations", "heaps-algorithm", "lexicographic", "no_std"]
license = "MIT/Apache-2.0"
repository = "https://github.com/bluss/permutohedron"
[package.metadata.release]
no-dev-version = true
[profile.bench]
debug = true
[features]
default = ["std"]
std = []
permutohedron-0.2.4/LICENSE-APACHE 0100644 0001751 0001751 00000025137 13201537243 0014567 0 ustar 00 0000000 0000000 Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
permutohedron-0.2.4/LICENSE-MIT 0100644 0001751 0001751 00000002057 13201537264 0014276 0 ustar 00 0000000 0000000 Copyright (c) 2015-2017 Ulrik Sverdrup "bluss"
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
permutohedron-0.2.4/Makefile 0100644 0001751 0001751 00000001465 12777306741 0014317 0 ustar 00 0000000 0000000 DOCCRATES = permutohedron
# deps to delete the generated docs
RMDOCS =
FEATURES =
VERSIONS = $(patsubst %,target/VERS/%,$(DOCCRATES))
docs: mkdocs subst $(RMDOCS)
# https://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html
$(VERSIONS): Cargo.toml
mkdir -p $(@D)
cargo pkgid $(@F) | sed -e "s/.*#\(\|.*:\)//" > "$@"
$(DOCCRATES): %: target/VERS/%
# Put in the crate version into the docs
find ./doc/$@ -name "*.html" -exec sed -i -e "s/
\(.*\) - Rust/$@ $(shell cat $<) - \1 - Rust/g" {} \;
subst: $(DOCCRATES)
mkdocs: Cargo.toml
cargo doc --features=$(FEATURES)
rm -rf ./doc
cp -r ./target/doc ./doc
- cat ./custom.css >> doc/main.css
$(RMDOCS): mkdocs
rm -r ./doc/$@
sed -i "/searchIndex\['$@'\]/d" doc/search-index.js
.PHONY: docs mkdocs subst $(DOCCRATES) $(RMDOCS)
permutohedron-0.2.4/README.rst 0100644 0001751 0001751 00000003400 13201543361 0014315 0 ustar 00 0000000 0000000
permutohedron
=============
Generate permutations of sequences.
Please read the `API documentation here`__
__ https://docs.rs/permutohedron/
|build_status|_ |crates|_
.. |build_status| image:: https://travis-ci.org/bluss/permutohedron.svg?branch=master
.. _build_status: https://travis-ci.org/bluss/permutohedron
.. |crates| image:: http://meritbadge.herokuapp.com/permutohedron
.. _crates: https://crates.io/crates/permutohedron
How to use with cargo::
[dependencies]
permutohedron = "0.2"
Recent Changes
--------------
- 0.2.4
- Document a panic case in ``Heap::new`` that was not mentioned before
- 0.2.3
- Add license files to the repo and package, thanks to @ignatenkobrain
- 0.2.2
- Add trait ``ControlFlow`` and allow optionally terminating ``heap_recursive``
early.
- 0.2.1
- Add feature ``std`` (enabled by default) that allows you to opt out of
using libstd.
- 0.2.0
- Add trait LexicalPermutation for lexicographical order of permutations,
from Rust's libcore
- 0.1.6
- Small optimization of heap_recursive
- 0.1.5
- Cache-use / data layout optimizations for Heap
- 0.1.4
- Optimizations for Heap
- 0.1.3
- Fix an error in heap_recursive
- 0.1.1
- Add heap_recursive, a faster callback-based version of Heap's algorithm
that can compute permutations of a sequence.
- 0.1.0
- Add Heap, an iterative walker & iterator using Heap's algorithm to
compute permutations of a sequence.
License
-------
Dual-licensed to be compatible with the Rust project.
Licensed under the Apache License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0 or the MIT license
http://opensource.org/licenses/MIT, at your
option. This file may not be copied, modified, or distributed
except according to those terms.
permutohedron-0.2.4/benches/bench.rs 0100644 0001751 0001751 00000001437 12777306741 0015712 0 ustar 00 0000000 0000000 #![feature(test)]
extern crate permutohedron;
extern crate test;
use test::{Bencher, black_box};
use permutohedron::{
Heap,
heap_recursive,
};
#[bench]
fn heap_iterative_7(b: &mut Bencher) {
let mut data = [0; 7];
b.iter(|| {
let mut heap = Heap::new(&mut data);
while let Some(elt) = heap.next_permutation() {
black_box(elt[0]);
}
});
}
#[bench]
fn heap_iterative_7_iter(b: &mut Bencher) {
let mut data = [0; 7];
b.iter(|| {
let heap = Heap::new(&mut data);
for elt in heap {
black_box(elt[0]);
}
});
}
#[bench]
fn heap_recursive_7(b: &mut Bencher) {
let mut data = [0; 7];
b.iter(|| {
heap_recursive(&mut data, |elt| {
black_box(elt[0]);
});
});
}
permutohedron-0.2.4/custom.css 0100644 0001751 0001751 00000001025 12777306741 0014673 0 ustar 00 0000000 0000000
.docblock pre.rust { background: #eeeeff; }
pre.trait, pre.fn, pre.struct, pre.enum, pre.typedef { background: #fcfefc; }
/* Small “example” label for doc examples */
.docblock pre.rust::before {
content: "example";
float: right;
font-style: italic;
font-size: 0.8em;
margin-top: -10px;
margin-right: -5px;
}
/* Fixup where display in trait listing */
pre.trait .where::before {
content: '\a ';
}
.docblock code {
background-color: inherit;
font-weight: bold;
padding: 0 0.1em;
}
permutohedron-0.2.4/src/control.rs 0100644 0001751 0001751 00000002411 12777306741 0015464 0 ustar 00 0000000 0000000 //! Control flow for callbacks.
macro_rules! try_control {
($e:expr) => {
match $e {
x => if x.should_break() {
return x;
}
}
}
}
/// Control flow for callbacks.
///
/// `Break` can carry a value.
#[derive(Copy, Clone, Debug)]
pub enum Control {
Continue,
Break(B),
}
impl Control {
pub fn breaking() -> Control<()> { Control::Break(()) }
/// Get the value in `Control::Break(_)`, if present.
pub fn break_value(self) -> Option {
match self {
Control::Continue => None,
Control::Break(b) => Some(b),
}
}
}
/// Control flow for callbacks.
///
/// The empty return value `()` is equivalent to continue.
pub trait ControlFlow {
fn continuing() -> Self;
#[inline]
fn should_break(&self) -> bool { false }
}
impl ControlFlow for () {
fn continuing() { }
}
impl ControlFlow for Control {
fn continuing() -> Self { Control::Continue }
fn should_break(&self) -> bool {
if let Control::Break(_) = *self { true } else { false }
}
}
impl ControlFlow for Result<(), E> {
fn continuing() -> Self { Ok(()) }
fn should_break(&self) -> bool {
if let Err(_) = *self { true } else { false }
}
}
permutohedron-0.2.4/src/lexical.rs 0100644 0001751 0001751 00000006346 12777306741 0015440 0 ustar 00 0000000 0000000 /// Permute a slice into its next or previous permutation (in lexical order).
///
/// ```
/// use permutohedron::LexicalPermutation;
///
/// let mut data = [1, 2, 3];
/// let mut permutations = Vec::new();
///
/// loop {
/// permutations.push(data.to_vec());
/// if !data.next_permutation() {
/// break;
/// }
/// }
///
/// assert_eq!(permutations, &[&[1, 2, 3], &[1, 3, 2],
/// &[2, 1, 3], &[2, 3, 1],
/// &[3, 1, 2], &[3, 2, 1]]);
///
/// // `data` has been mutated in-place:
/// assert_eq!(data, [3, 2, 1]);
/// ```
pub trait LexicalPermutation {
/// Return `true` if the slice was permuted, `false` if it is already
/// at the last ordered permutation.
fn next_permutation(&mut self) -> bool;
/// Return `true` if the slice was permuted, `false` if it is already
/// at the first ordered permutation.
fn prev_permutation(&mut self) -> bool;
}
impl LexicalPermutation for [T] where T: Ord {
/// Original author in Rust: Thomas Backman
fn next_permutation(&mut self) -> bool {
// These cases only have 1 permutation each, so we can't do anything.
if self.len() < 2 { return false; }
// Step 1: Identify the longest, rightmost weakly decreasing part of the vector
let mut i = self.len() - 1;
while i > 0 && self[i-1] >= self[i] {
i -= 1;
}
// If that is the entire vector, this is the last-ordered permutation.
if i == 0 {
return false;
}
// Step 2: Find the rightmost element larger than the pivot (i-1)
let mut j = self.len() - 1;
while j >= i && self[j] <= self[i-1] {
j -= 1;
}
// Step 3: Swap that element with the pivot
self.swap(j, i-1);
// Step 4: Reverse the (previously) weakly decreasing part
self[i..].reverse();
true
}
fn prev_permutation(&mut self) -> bool {
// These cases only have 1 permutation each, so we can't do anything.
if self.len() < 2 { return false; }
// Step 1: Identify the longest, rightmost weakly increasing part of the vector
let mut i = self.len() - 1;
while i > 0 && self[i-1] <= self[i] {
i -= 1;
}
// If that is the entire vector, this is the first-ordered permutation.
if i == 0 {
return false;
}
// Step 2: Reverse the weakly increasing part
self[i..].reverse();
// Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
let mut j = self.len() - 1;
while j >= i && self[j-1] < self[i-1] {
j -= 1;
}
// Step 4: Swap that element with the pivot
self.swap(i-1, j);
true
}
}
#[test]
fn lexical() {
let mut data = [1, 2, 3];
data.next_permutation();
assert_eq!(&data, &[1, 3, 2]);
data.next_permutation();
assert_eq!(&data, &[2, 1, 3]);
data.prev_permutation();
assert_eq!(&data, &[1, 3, 2]);
data.prev_permutation();
assert_eq!(&data, &[1, 2, 3]);
assert!(!data.prev_permutation());
let mut c = 0;
while data.next_permutation() {
c += 1;
}
assert_eq!(c, 5);
}
permutohedron-0.2.4/src/lib.rs 0100644 0001751 0001751 00000023274 13201543270 0014543 0 ustar 00 0000000 0000000 #![cfg_attr(not(feature = "std"), no_std)]
//!
//! ## Crate Feature Flags
//!
//! - `std`
//! + Default. Disabling `std` requires Rust 1.6 or later
//! + Disabling `std` makes the crate a `#![no_std]` crate (works with core)
#[cfg(not(feature = "std"))]
extern crate core as std;
use std::marker::PhantomData;
pub use lexical::LexicalPermutation;
mod lexical;
#[macro_use]
pub mod control;
use control::ControlFlow;
/// Heap's algorithm for generating permutations, recursive version.
///
/// The recursive algorithm supports slices of any size (even though
/// only a small number of elements is practical), and is generally
/// a bit faster than the iterative version.
///
/// The closure `f` may return either `()` to simply run through all
/// permutations, or a `Control` value that permits breaking the
/// iteration early.
///
/// ```
/// use permutohedron::heap_recursive;
///
/// let mut data = [1, 2, 3, 4, 5, 6];
/// let mut permutations = Vec::new();
/// heap_recursive(&mut data, |permutation| {
/// permutations.push(permutation.to_vec())
/// });
///
/// assert_eq!(permutations.len(), 720);
/// ```
pub fn heap_recursive(xs: &mut [T], mut f: F) -> C
where F: FnMut(&mut [T]) -> C,
C: ControlFlow,
{
match xs.len() {
0 | 1 => f(xs),
2 => {
// [1, 2], [2, 1]
try_control!(f(xs));
xs.swap(0, 1);
f(xs)
}
n => heap_unrolled_(n, xs, &mut f),
}
}
// TODO: Find a more parallel version with less data dependencies:
// i.e. don't swap the same items (for example index 0) every time.
/// Unrolled version of heap's algorithm due to Sedgewick
fn heap_unrolled_(n: usize, xs: &mut [T], f: &mut F) -> C
where F: FnMut(&mut [T]) -> C,
C: ControlFlow,
{
debug_assert!(n >= 3);
match n {
3 => {
// [1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]
try_control!(f(xs));
xs.swap(0, 1);
try_control!(f(xs));
xs.swap(0, 2);
try_control!(f(xs));
xs.swap(0, 1);
try_control!(f(xs));
xs.swap(0, 2);
try_control!(f(xs));
xs.swap(0, 1);
f(xs)
}
n => {
for i in 0..n - 1 {
try_control!(heap_unrolled_(n - 1, xs, f));
let j = if n % 2 == 0 { i } else { 0 };
// One swap *between* each iteration.
xs.swap(j, n - 1);
}
heap_unrolled_(n - 1, xs, f)
}
}
}
/// Maximum number of elements we can generate permutations for using
/// Heap's algorithm (iterative version).
pub const MAXHEAP: usize = 16;
/// Heap's algorithm for generating permutations.
///
/// An iterative method of generating all permutations of a sequence.
///
/// Note that for *n* elements there are *n!* (*n* factorial) permutations.
///
/// ```
/// use permutohedron::Heap;
///
/// let mut data = vec![1, 2, 3];
/// let heap = Heap::new(&mut data);
///
/// let mut permutations = Vec::new();
/// for data in heap {
/// permutations.push(data.clone());
/// }
///
/// assert_eq!(permutations.len(), 6);
/// ```
// lock the repr since it performs the best in this order..(?)
#[repr(C)]
pub struct Heap<'a, Data: 'a + ?Sized, T: 'a> {
data: &'a mut Data,
// c, and n: u8 is enough range.
// u32 performs better for n, u8 for c.
// n: == !0 at start, 0 after first permutation is emitted
n: u32,
// c[x] is the counter for the (x + 1) th location
c: [u8; MAXHEAP - 1],
_element: PhantomData<&'a mut T>
}
impl<'a, T, Data: ?Sized> Heap<'a, Data, T>
where Data: AsMut<[T]>
{
/// Create a new `Heap`.
///
/// ***Panics*** if the number of elements is too large (see `MAXHEAP`)
///
/// The `heap_recursive` function has no length limit, but
/// note that for *n* elements there are *n!* (*n* factorial) permutations,
/// which gets impractical for surprisingingly small values of *n* anyway.
pub fn new(data: &'a mut Data) -> Self {
assert!(data.as_mut().len() <= MAXHEAP);
Heap {
data: data,
c: [0; MAXHEAP - 1],
n: !0,
_element: PhantomData,
}
}
/// Return a reference to the inner data
pub fn get(&self) -> &Data {
self.data
}
/// Return a mutable reference to the inner data
pub fn get_mut(&mut self) -> &mut Data {
self.data
}
/// Reset the permutations walker, without changing the data. It allows
/// generating permutations again with the current state as starting
/// point.
pub fn reset(&mut self) {
self.n = !0;
for c in &mut self.c[..] { *c = 0; }
}
/// Step the internal data into the next permutation and return
/// a reference to it. Return `None` when all permutations
/// have been visited.
///
/// Note that for *n* elements there are *n!* (*n* factorial) permutations.
pub fn next_permutation(&mut self) -> Option<&mut Data> {
if self.n == !0 {
self.n = 0;
Some(self.data)
} else {
while 1 + (self.n as usize) < self.data.as_mut().len() {
let n = self.n as u8;
let nu = self.n as usize;
let c = &mut self.c;
if c[nu] <= n {
// `n` acts like the current length - 2 of the slice we are permuting
// `c[n]` acts like `i` in the recursive algorithm
let j = if nu % 2 == 0 { c[nu] as usize } else { 0 };
self.data.as_mut().swap(j, nu + 1);
c[nu] += 1;
self.n = 0;
return Some(self.data);
} else {
c[nu] = 0;
self.n += 1;
}
}
None
}
}
}
#[cfg(feature = "std")]
/// Iterate the permutations
///
/// **Note:** You can also generate the permutations lazily by using
/// `.next_permutation()`.
impl<'a, Data: ?Sized, T> Iterator for Heap<'a, Data, T>
where Data: AsMut<[T]> + ToOwned,
{
type Item = Data::Owned;
fn next(&mut self) -> Option {
match self.next_permutation() {
None => None,
Some(perm) => Some(perm.to_owned()),
}
}
}
/// Compute *n!* (*n* factorial)
pub fn factorial(n: usize) -> usize {
(1..n + 1).fold(1, |a, b| a * b)
}
#[cfg(all(test, feature = "std"))]
mod tests {
use super::*;
use control::Control;
#[test]
fn first_and_reset() {
let mut data = [1, 2, 3];
let mut heap = Heap::new(&mut data);
let mut perm123 = vec![[1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]];
assert_eq!(heap.by_ref().collect::>(), perm123);
// test reset
heap.reset();
// for the 1,2,3 case this happens to work out to the reverse order
perm123.reverse();
assert_eq!(heap.by_ref().collect::>(), perm123);
}
#[test]
fn permutations_0_to_6() {
let mut data = [0; 6];
for n in 0..data.len() {
let count = factorial(n);
for (index, elt) in data.iter_mut().enumerate() {
*elt = index + 1;
}
let mut permutations = Heap::new(&mut data[..n]).collect::>();
assert_eq!(permutations.len(), count);
permutations.sort();
permutations.dedup();
assert_eq!(permutations.len(), count);
// Each permutation contains all of 1 to n
assert!(permutations.iter().all(|perm| perm.len() == n));
assert!(permutations.iter().all(|perm| (1..n + 1).all(|i| perm.iter().position(|elt| *elt == i).is_some())));
}
}
#[test]
fn count_permutations_iter() {
let mut data = [0; 10];
for n in 0..data.len() + 1 {
let count = factorial(n);
let mut permutations = Heap::new(&mut data[..n]);
let mut i = 0;
while let Some(_) = permutations.next_permutation() {
i += 1;
}
assert_eq!(i, count);
println!("{}! = {} ok", n, count);
}
}
#[test]
fn count_permutations_recur() {
let mut data = [0; 10];
for n in 0..data.len() + 1 {
let count = factorial(n);
let mut i = 0;
heap_recursive(&mut data[..n], |_| i += 1);
assert_eq!(i, count);
println!("{}! = {} ok", n, count);
}
}
#[test]
fn permutations_0_to_6_recursive() {
let mut data = [0; 6];
for n in 0..data.len() {
let count = factorial(n);
for (index, elt) in data.iter_mut().enumerate() {
*elt = index + 1;
}
let mut permutations = Vec::with_capacity(count);
heap_recursive(&mut data[..n], |elt| permutations.push(elt.to_owned()));
println!("{:?}", permutations);
assert_eq!(permutations.len(), count);
permutations.sort();
permutations.dedup();
assert_eq!(permutations.len(), count);
// Each permutation contains all of 1 to n
assert!(permutations.iter().all(|perm| perm.len() == n));
assert!(permutations.iter().all(|perm| (1..n + 1).all(|i| perm.iter().position(|elt| *elt == i).is_some())));
}
}
#[test]
fn permutations_break() {
let mut data = [0; 8];
let mut i = 0;
heap_recursive(&mut data, |_perm| {
i += 1;
if i >= 10_000 {
Control::Break(i)
} else {
Control::Continue
}
});
assert_eq!(i, 10_000);
}
}