问题描述
目标:并行生成排列并索引到每个排列中。
尝试:使用 Itertools
将所有排列分配给结果向量,然后使用 rayon
处理每个排列。
最小可重复代码:
use rayon::iter::ParallelIterator;
use rayon::iter::IntoParallelIterator;
use itertools::Itertools;
fn main() {
let data: Vec<u128> = [0,1,2,3,4,5,6].to_vec();
let k = 4;
let vector = data.into_iter().permutations(k).map_into::<Vec<u128>>
().collect_vec();
(vector).into_par_iter().for_each(move |x| index_vec(x));
}
fn index_vec(i: Vec<u128>) -> () {
let mut colour_code: String = String::from("");
let mut index_position = 0;
for _ in 0..4 {
colour_code.push_str(COLOURS[i[index_position]]);
colour_code.push(' ');
index_position += 1;
}
println!("Colour code: {}",colour_code);
}
const COLOURS: [&str; 7] = [
"red","yellow","blue","green","pink","grey","orange",];
错误:切片索引的类型为 usize
或范围为 usize
但是,如果我将所有向量更改为类型 usize
,那么 Itertools 会在 map_into
方法上引发错误:From<Vec<u128>>
未实现特征 Vec<usize>
。
如何让 Itertools 和切片索引协同工作?
解决方法
要使发布的代码编译并运行,您只需将 u128
转换为用于索引数组的 usize
。
我目前认为这是“安全的”,因为我知道没有指针大小 > 128 字节的系统。但是请注意,这种转换可能fail in theory
所以固定代码看起来像这样:
use rayon::iter::ParallelIterator;
use rayon::iter::IntoParallelIterator;
use itertools::Itertools;
fn main() {
let data: Vec<u128> = [0,1,2,3,4,5,6].to_vec();
let k = 4;
let vector = data.into_iter().permutations(k).map_into::<Vec<u128>>
().collect_vec();
(vector).into_par_iter().for_each(move |x| index_vec(x));
}
fn index_vec(i: Vec<u128>) -> () {
let mut colour_code: String = String::from("");
let mut index_position = 0;
for _ in 0..4 {
colour_code.push_str(COLOURS[i[index_position] as usize]);
colour_code.push(' ');
index_position += 1;
}
println!("Colour code: {}",colour_code);
}
const COLOURS: [&str; 7] = [
"red","yellow","blue","green","pink","grey","orange",];
游乐场链接是 here。