1

RustでDIMACS CNF ファイルを読み込みたいです。

Rubyで書くと以下のようなコードになるのですがRustだとどう書けばいいでしょうか?
特に、Rubyのscanに当たる関数が見つかってないです。

#Ruby code

def read_dimacs_cnf_file(file_name)
    cnf=[]
    clause=[]
    open(file_name,"r").readlines.reject{|line| line=~/^c/ || line=~/^p/}.join().scan(/-?\d+/).collect{|literal| literal.to_i}.each{|literal|
        if literal==0
        then
            cnf<<clause
            clause=[]
        else
            clause<<literal
        end
    }
    cnf
end

入力例

c
c comment
c
p cnf 3 3
1 2 0
2 -3 0
3 0

出力例

[[1,2],[2,-3],[3]]

RustのコードはFileを読み込むところまでしか書けてないです。

use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;

fn read_dimacs_cnf_file(file_name:&str)->String{
    let path=Path::new(file_name);
    let mut file=match File::open(&path){
        Err(msg) => panic!("couldn't open file. {}",msg),
        Ok(file) => file,
    };

    let mut s=String::new();
    match file.read_to_string(&mut s){
        Err(msg) => panic!("couldn't read file. {}",msg),
        Ok(_) => return s,
    };
}

fn main() {
    println!("{}",read_dimacs_cnf_file("test.cnf"));
}

2 件の回答 2

2

特に、Rubyのscanに当たる関数が見つかってないです。

Rubyのscanなどで/-?\d+/といった正規表現が使われていますが、Rustの標準ライブラリー(stdクレート)には正規表現の機能がありません。正規表現を使う場合は、regexクレートを使う必要があります。

Cargo.toml

[dependencies]
regex = "1.7.0"

regexクレートのcaptures_iterメソッドを使うと、scanのようにマッチした部分文字列を取り出すことができます。

use std::{
    fs::File,
    io::{prelude::*, BufReader},
};

use regex::Regex;

fn read_dimacs_cnf_file(file_name: &str) -> Vec<Vec<i32>> {
    let file = File::open(file_name).expect("couldn't open file.");
    let file = BufReader::new(file);

    let re = Regex::new(r"-?\d+").unwrap();
    let mut clause = Vec::new();
    let mut cnf = Vec::new();

    // 1行ずつ読み込む
    for line in file.lines() {
        let line = line.expect("couldn't read file.");

        // c または p で始まる行は無視する
        if line.starts_with("c") || line.starts_with("p") {
            continue;
        }

        // 行の中で、マッチした部分文字列を1つずつ処理する
        for token in re.captures_iter(&line) {
            // 部分文字列を整数に変換する
            let literal = token[0].parse::<i32>().expect("couldn't parse number.");

            if literal == 0 {
                // 0なら、clauseをcnfに追加して、clauseを空にする
                cnf.push(clause);
                clause = Vec::new();
            } else {
                // 0以外なら、clauseに追加する
                clause.push(literal);
            }
        }
    }

    cnf
}

fn main() {
    println!("{:?}", read_dimacs_cnf_file("test.cnf"));
}

なお、このデーター形式ですと数値が空白文字で区切られていますので、正規表現を使わずにstdstr::split_whitespaceメソッドを使うこともできます。以下のように2行書き換えるとregexクレートが不要になります。

        // 行の中で、空白文字で区切られた部分文字列を1つずつ処理する
        for token in line.split_whitespace() {
            // 部分文字列を整数に変換する
            let literal = token.trim().parse::<i32>().expect("couldn't parse number.");
1

rustにはdimacsというクレートがあってDIMACS CNFファイルをパースできるみたいです。

https://docs.rs/dimacs/latest/dimacs/index.html

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。