Skip to content

Instantly share code, notes, and snippets.

View adamchalmers's full-sized avatar

Adam Chalmers adamchalmers

View GitHub Profile
@adamchalmers
adamchalmers / const_combinatorics.rs
Created January 2, 2022 04:52
Generate permutations of any N items, where N is a const generic uint.
use array_init::array_init;
fn permutations<T: Copy, const N: usize>(items: &[T; N]) -> Vec<[T; N]> {
permute_naturals::<N>(1, vec![[0; N]])
.into_iter()
.map(|perm| array_init(|i| items[perm[i]]))
.collect()
}
/// Generate all `n!` permutations of the natural numbers 0..n
use std::ffi::OsStr;
use std::io;
use std::fs::{self};
use std::path::{Path, PathBuf};
// Find all files in the given directory with the given extension
fn paths_matching(extension: &str, dir: &Path) -> io::Result<Vec<PathBuf>> {
let mut paths: Vec<PathBuf> = Vec::new();
for entry in fs::read_dir(dir)? {
let entry = entry?;
let array = Array(0..<10)
let slice = array[2..<5]
// Mixing Array/ArraySlice compiles!
print(extend(array, withNewElems: array))
print(extend(array, withNewElems: slice))
print(extend(slice, withNewElems: slice))
// Mixing Ints/Bools doesn't compile!
print(extend(array, withNewElems: [true, false]))
func extend<T>(_: [T], withNewElems: [T]) -> [T]
func extend<T>(_: Collection, withNewElems: Collection) -> [T]
func extend<T: Collection>(_ base: T, withNewElems: T) -> T {
// Ignore the function body for now,
// we’re just trying to make it compile.
return base
}
func extend<T: Collection, U: Collection>(_ base: T, withNewElems: U)
func extend<T: Collection, U: Collection>(_ base: T, withNewElems: U)
where T.Iterator.Element == U.Iterator.Element {
// function body will go here
// also ignoring return type for now
}
func extend<T: Collection, U: Collection>(_ base: T, withNewElems: U) -> [T.Iterator.Element]
where T.Iterator.Element == U.Iterator.Element {
let newElems = withNewElems.filter { !base.contains($0) }
return Array(base) + newElems
}
func extend<T: Collection, U: Collection>(_ base: T, withNewElems: U) -> [T.Iterator.Element]
where T.Iterator.Element == U.Iterator.Element,
T.Iterator.Element: Equatable {
let newElems = withNewElems.filter { !base.contains($0) }
return Array(base) + newElems
}