How to shuffle a vector except for the first and last elements without using third party libraries?

。_饼干妹妹 提交于 2021-02-04 08:39:05

问题


I have a task to shuffle words but the first and last letter of every word must be unchanged. When I try to use filter() it doesn't work properly.

const SEPARATORS: &str = " ,;:!?./%*$=+)@_-('\"&1234567890\r\n";

fn main() {
    print!("MAIN:{:?}", mix("Evening,morning"));
}

fn mix(s: &str) -> String {
    let mut a: Vec<char> = s.chars().collect();

    for group in a.split_mut(|num| SEPARATORS.contains(*num)) {
        if group.len() > 4 {
            let k = group.first().unwrap().clone();
            let c = group[group.len() - 1].clone();
            group
                .chunks_exact_mut(2)
                .filter(|x| x != &[k])
                .for_each(|x| x.swap(0, 1))
        }
    }

    let s: String = a.iter().collect();
    s
}

回答1:


Is this what you are looking for?

fn mix(s: &str) -> String {
    let mut a: Vec<char> = s.chars().collect();

    for words in a.split_mut(|num| SEPARATORS.contains(*num)) {
        if words.len() > 4 {
            let initial_letter = words.first().unwrap().clone();
            let last_letter = words[words.len() - 1].clone();
            words[0] = last_letter;
            words[words.len() - 1] = initial_letter;
        }
    }
    let s: String = a.iter().collect();
    s
}


来源:https://stackoverflow.com/questions/61576491/how-to-shuffle-a-vector-except-for-the-first-and-last-elements-without-using-thi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!