Skip to content

Instantly share code, notes, and snippets.

@maretekent
Last active September 13, 2018 08:02
Show Gist options
  • Save maretekent/1b81dbe591961242f3e93024689ffe10 to your computer and use it in GitHub Desktop.
Save maretekent/1b81dbe591961242f3e93024689ffe10 to your computer and use it in GitHub Desktop.
Rust algorithm to get permutations in a number
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()
}
@michaelkamau
Copy link

michaelkamau commented Sep 12, 2018

Using the the cycle iterator adaptor:

fn main() {
    let nums = vec![1,1,9,7];
    
    print_rotations(nums);
}

fn print_rotations(num_list: Vec<u32>) {
   
    let mut num_iter = num_list.iter().cycle();
    let mut rotated_nums = Vec::new();
    for _i in 0..num_list.len() {
        let mut rot = Vec::new();
        for _j in 0..num_list.len() {
            let next_num = num_iter.next().unwrap();
            rot.push(next_num);
        }
        let _spacer = num_iter.next().unwrap();
        rotated_nums.push(rot);
    }
    println!("Rotations: {:?} ", rotated_nums);
}

This gives the following output:
Rotations: [[1, 1, 9, 7], [1, 9, 7, 1], [9, 7, 1, 1], [7, 1, 1, 9]]

@mattgathu
Copy link

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