// author: Leonardone @ NEETSDKASU struct Perm { u: Vec<bool>, x: Vec<usize>, init: bool, } impl Perm { fn new(size: usize, sel: usize) -> Perm { Perm { u: vec![false; size], x: vec![0; sel], init: false, } } fn next(&mut self) -> Option<&[usize]> { if !self.init { let k = self.u.len() - self.x.len(); for i in 0..self.x.len() { self.x[i] = i; self.u[k + i] = false; self.u[i] = true; } self.init = true; return Some(&self.x); } let mut i = self.x.len() - 1; let mut x = self.x[i]; self.u[x] = false; loop { x += 1; if x >= self.u.len() { if i == 0 { self.init = false; return None; } i -= 1; x = self.x[i]; self.u[x] = false; continue; } if self.u[x] { continue; } self.u[x] = true; self.x[i] = x; i += 1; break; } x = 0; while i < self.x.len() && x < self.u.len() { if !self.u[x] { self.u[x] = true; self.x[i] = x; i += 1; } x += 1; } Some(&self.x) } } fn main() { let mut p = Perm::new(5, 3); while let Some(x) = p.next() { println!("{:?}", x); } }
Standard input is empty
[0, 1, 2] [0, 1, 3] [0, 1, 4] [0, 2, 1] [0, 2, 3] [0, 2, 4] [0, 3, 1] [0, 3, 2] [0, 3, 4] [0, 4, 1] [0, 4, 2] [0, 4, 3] [1, 0, 2] [1, 0, 3] [1, 0, 4] [1, 2, 0] [1, 2, 3] [1, 2, 4] [1, 3, 0] [1, 3, 2] [1, 3, 4] [1, 4, 0] [1, 4, 2] [1, 4, 3] [2, 0, 1] [2, 0, 3] [2, 0, 4] [2, 1, 0] [2, 1, 3] [2, 1, 4] [2, 3, 0] [2, 3, 1] [2, 3, 4] [2, 4, 0] [2, 4, 1] [2, 4, 3] [3, 0, 1] [3, 0, 2] [3, 0, 4] [3, 1, 0] [3, 1, 2] [3, 1, 4] [3, 2, 0] [3, 2, 1] [3, 2, 4] [3, 4, 0] [3, 4, 1] [3, 4, 2] [4, 0, 1] [4, 0, 2] [4, 0, 3] [4, 1, 0] [4, 1, 2] [4, 1, 3] [4, 2, 0] [4, 2, 1] [4, 2, 3] [4, 3, 0] [4, 3, 1] [4, 3, 2]