我是铁锈的初学者。我有简单的脚本,但是我必须使用太多的类型转换。脚本要点:在矩阵中搜索具有相同值的相邻cels群集(使用具有队列https://en.wikipedia.org/wiki/Flood_fill的泛洪填充算法)。
这是完整的代码:
fn find_clusters(playground: [[u8; SIZE]; SIZE]) -> Vec<Cluster> {
let directions_cluster: [[i8; 2]; 4] = [[0, 1], [0, -1], [1, 0], [-1, 0]];
let mut clusters: Vec<Cluster> = Vec::new();
let mut queue: Vec<[usize; 2]> = Vec::new();
let mut marked_cells: [[u8; SIZE]; SIZE] = [[0; SIZE]; SIZE];
for i in 0..SIZE {
for j in 0..SIZE {
if marked_cells[i][j] == 1 { continue; }
let code = playground[i][j];
let mut cluster = Cluster::new();
queue.push([i, j]);
marked_cells[i][j] = 1;
while !queue.is_empty() {
let coords = queue.pop().unwrap();
cluster.coords.push(coords);
for direction in &directions_cluster {
let check_i = coords[0] as i8 + direction[0];
if check_i < 0 || check_i as usize >= SIZE {continue;}
let check_j = coords[1] as i8 + direction[1];
if check_j < 0 || check_j as usize >= SIZE {continue;}
let ni = check_i as usize;
let nj = check_j as usize;
if playground[ni][nj] == code && marked_cells[ni][nj] == 0 {
queue.push([ni, nj]);
marked_cells[ni][nj] = 1;
}
}
}
if cluster.coords.len() >= 5 {
cluster.code = code;
clusters.push(cluster);
}
};
};
return clusters;
}但我不喜欢这部分:
for direction in &directions_cluster {
let check_i = coords[0] as i8 + direction[0];
if check_i < 0 || check_i as usize >= SIZE {continue;}
let check_j = coords[1] as i8 + direction[1];
if check_j < 0 || check_j as usize >= SIZE {continue;}
let ni = check_i as usize;
let nj = check_j as usize;
if playground[ni][nj] == code && marked_cells[ni][nj] == 0 {
queue.push([ni, nj]);
marked_cells[ni][nj] = 1;
}
}我甚至不得不定义额外的变量(check_i,check_j),以便以后每次都不使用ni/nj的强制转换。在大小写的情况下,最好的类型转换方式是什么?
发布于 2020-10-10 00:03:47
您可以使用标准库中的TryInto特征来抽象溢出检查。这就是我将如何实现它:
use std::convert::TryInto;
type Pos = [usize; 2];
fn add_to_coords(coords: Pos, offset: [i8; 2]) -> Option<Pos> {
let ni: usize = (coords[0] as i8 + direction[0]).try_into().ok()?;
let nj: usize = (coords[1] as i8 + direction[1]).try_into().ok()?;
[ni, nj]
}
// ...
for [ni, nj] in directions.flat_map(|dir| add_to_coords(coords, dir)) {
// ...
}
// ... 调用flat_map会过滤掉所有为None的返回值,以防您想知道continue到哪里去了。
https://stackoverflow.com/questions/64276590
复制相似问题