Quantcast
Channel: SIGKILL in PALIN (rust language)
Viewing all articles
Browse latest Browse all 6

SIGKILL in PALIN (rust language)

$
0
0

@coeuvre wrote:

The code seems ok but I don't know why it is SIGKILL? Help me, pls!

use std::io::{self, BufRead};

fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();

    let t = lines.next().unwrap().unwrap().parse::<usize>().unwrap();

    for _ in 0..t {
        let digits: Vec<char> = lines.next().unwrap().unwrap().chars().collect();
        let mut palindrome = make_palindrome(&digits);

        while !is_less(&digits, &palindrome) {
            palindrome = next_palindrome(palindrome);
        }

        let result: String = palindrome.into_iter().collect();
        println!("{}", result);
    }
}

fn center(digits: &Vec<char>) -> (usize, usize) {
    if digits.len() % 2 == 0 {
        let c = digits.len() / 2;
        (c - 1, c)
    } else {
        let c = digits.len() / 2;
        (c, c)
    }
}

fn make_palindrome(digits: &Vec<char>) -> Vec<char> {
    let (pos1, pos2) = center(digits);

    let mut palindrome = Vec::with_capacity(digits.len());

    for ch in digits.iter().take(pos1 + 1) {
        palindrome.push(*ch);
    }

    for i in pos2..digits.len() {
        let j = digits.len() - i - 1;
        if i == j {
            continue;
        }
        let ch = palindrome[j];
        palindrome.push(ch);
    }

    palindrome
}

fn next_palindrome(palindrome: Vec<char>) -> Vec<char> {
    let (pos1, pos2) = center(&palindrome);

    fn next(mut palindrome: Vec<char>, pos1: i32, pos2: i32) -> Vec<char> {
        if pos1 < 0 {
            *palindrome.last_mut().unwrap() = '1';
            palindrome.insert(0, '1');
            palindrome
        } else if palindrome[pos1 as usize] < '9' {
            let n = (palindrome[pos1 as usize] as u8 + 1) as char;
            palindrome[pos1 as usize] = n;
            palindrome[pos2 as usize] = n;
            palindrome
        } else {
            palindrome[pos1 as usize] = '0';
            palindrome[pos2 as usize] = '0';
            next(palindrome, pos1 - 1, pos2 + 1)
        }
    };

    next(palindrome, pos1 as i32, pos2 as i32)
}

fn is_less(v1: &Vec<char>, v2: &Vec<char>) -> bool {
    if v1.len() != v2.len() {
        return v1.len() < v2.len();
    }

    for (ch1, ch2) in v1.iter().zip(v2.iter()) {
        if ch1 != ch2 {
            return ch1 < ch2;
        }
    }

    // v1 is equal to v2
    false
}

Read full topic


Viewing all articles
Browse latest Browse all 6