DEV Community

Cover image for Solution evolution
Antonov Mike
Antonov Mike

Posted on

Solution evolution

Me solving the same level 6 problem on Codewars few months later

1) March 2022

fn solution(s: &str) -> Vec<String> {
    let mut result = vec![];
    let mut tmp = s.to_owned();
    let mut index = 0;

    if s.len() == 0 { return result }
    else if s.len() == 1 {
        tmp.push_str("_");
        result.push(tmp.to_string());
    }
    else {
        if s.len() % 2 == 1 { tmp.push_str("_") }
        while index < tmp.len() {
            if tmp.len() < 2 { result.push((&s[index..index+1]).to_string()); }
            else { result.push((&tmp[index..index+2]).to_string()); }
        index += 2
        }
    }
    return result
}
Enter fullscreen mode Exit fullscreen mode

2) December 2022

fn solution(s: &str) -> Vec<String> {
    let mut vec: Vec<String> = vec![];
    let mut index = 0;

    for _i in 0..(s.len() / 2) {
        let part = &s[ (index)..=(index + 1) ];
        vec.push( part.to_string() );
        index += 2
    }

    if s.len() % 2 == 1 {
        let last_str = format!("{}_", &s[ (s.len() - 1 )..]);
        vec.push( last_str )
    }

    vec
}
Enter fullscreen mode Exit fullscreen mode

3) July 2023

fn solution(s: &str) -> Vec<String> {
    let mut result = vec![];
    let mut chars = s.chars().peekable();
    while let Some(c1) = chars.next() {
        let c2 = chars.next().unwrap_or('_');
        result.push(format!("{}{}", c1, c2));
    }
    result
}
Enter fullscreen mode Exit fullscreen mode

Surely this problem can be solved even more effectively

Top comments (0)