Last active
September 13, 2018 08:02
-
-
Save maretekent/1b81dbe591961242f3e93024689ffe10 to your computer and use it in GitHub Desktop.
Rust algorithm to get permutations in a number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fmt; | |
pub struct JoinMyVec { | |
myvec : Vec<u32>, | |
} | |
impl fmt::Display for JoinMyVec { | |
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | |
let s = fmt.write_str(&join(&self.myvec[..], &""))?; | |
Ok(s) | |
} | |
} | |
fn main() { | |
let n: u32 = 197; | |
let mut array = number_to_vec(n); | |
generate(array.len(), &mut array); | |
} | |
fn generate(n : usize, a : &mut Vec<u32>) { | |
if n == 1 { | |
let join_this = JoinMyVec { | |
myvec : a.to_vec(), | |
}; | |
println!("{}", join_this); | |
// if a[0] == 9 { | |
// println!("starts with {}",a[0]); | |
// } | |
// println!("{:?}", a); | |
} | |
else { | |
for i in 0 .. n - 1 { | |
generate(n - 1, a); | |
if n % 2 == 0 { | |
a.swap(i, n - 1); | |
} | |
else { | |
a.swap(0, n - 1); | |
} | |
} | |
generate(n - 1, a); | |
} | |
} | |
fn number_to_vec(n: u32) -> Vec<u32> { | |
n.to_string() | |
.chars() | |
.map(|c| c.to_digit(10).unwrap()) | |
.collect() | |
} |
Here is another implementation using VecDeque
use std::collections::VecDeque;
fn main() {
let num = 197;
let mut buf: VecDeque<_> = num.to_string().chars().map(|d| d.to_digit(10).unwrap()).collect();;
for _ in 0..buf.len() {
println!("{:?}", buf);
let n = buf.pop_front().unwrap();
buf.push_back(n);
}
}
The output is:
[1, 9, 7]
[9, 7, 1]
[7, 1, 9]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using the the
cycle
iterator adaptor:This gives the following output:
Rotations: [[1, 1, 9, 7], [1, 9, 7, 1], [9, 7, 1, 1], [7, 1, 1, 9]]