Can someone translate my python/nim sudoku resolver into Rust?

Hi ...

It's not a language war ....

I'm just testing a simple sudoku resolver (it takes 13 lines in python3) : simple bactracking recursive resolver.

I've made a java one and a nim one ... (to compare perf on differents hardwares)
I would like to see the same algorithm (with same func names) into rust one ...

Here is my repo

For me, it will take hours, because I don't know rust ... But for a specialist it could takes minutes, by just translating the nim one into rust.

Here's a more-or-less direct translation:

use std::collections::HashSet;

fn square(g: &str, x: usize, y: usize) -> String {
    let x = (x / 3) * 3;
    let y = (y / 3) * 3;
    g[y*9+x ..= y*9+x+2].to_string() + &g[y*9+x+9 ..= y*9+x+11] + &g[y*9+x+18 ..= y*9+x+20]
}

fn horiz(g: &str, y: usize) -> &str {
    let ligne = y * 9;
    &g[0+ligne ..= 8+ligne]
}

fn vertiz(g: &str, x: usize) -> String {
    let mut result = String::new();
    for y in 0..8 {
        let ligne = y * 9;
        result.push(g.as_bytes()[x + ligne] as char);
    }
    result
}

fn freeset(sg: &str) -> HashSet<u8> {
    let mut s = HashSet::new();
    s.extend(b'1' ..= b'9');
    s.insert(b'.');
    for c in sg.as_bytes() {
        s.remove(&c);
    }
    s
}

fn interset(g: &str, x: usize, y: usize) -> HashSet<u8> {
    let mut a = freeset(&horiz(g,y));
    let b = freeset(&vertiz(g,x));
    let c = freeset(&square(g,x,y));
    a.retain(|v| b.contains(v) && c.contains(v));
    a
}

fn replace(g: &str, pos: usize, c: u8) -> String {
    let mut s = g[0..pos].to_string();
    s.push(c as char);
    s.push_str(&g[1+pos..]);
    s
}

fn resolv(g: &str) -> Option<String> {
    if let Some(i) = g.find('.') {
        for elem in interset(g, i % 9, i/9) {
            if let Some(ng) = resolv(&replace(g,i,elem)) {
                return Some(ng);
            }
        }
        None
    } else {
        Some(g.to_string())
    }
}

Though if you want something that's actually fast, there are quite a few low-hanging fruit to optimize it.

4 Likes

plus, regarding measuring, don't forget the default slow debug vs release mode of Rust program build...! :sunglasses:

1 Like

Fore sure ... When trying Nim, it was terrible ...

The default one (debug) took more than 3m (longer than py3 ?!?) ... While the release mode downs to 16 sec.

I will be vigilant :wink:

Thanks, I will try to Finnish ..

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.