一种选择是利用IntList() 将值动态附加到:
void setup(){
int[] src = {6, 3, 1};
IntList dst = new IntList();
for(int i = 0; i < src.length; i++){
// from 0 to the current index value in the array
for(int j = 0; j < src[i]; j++){
// add the index to the list
dst.append(i);
}
}
println(sum(src));
println(dst.size());
println(dst);
println(sum(dst));
}
int sum(int[] array){
int total = 0;
for(int i : array){
total += i;
}
return total;
}
int sum(IntList list){
int total = 0;
for(int i : list){
total += i;
}
return total;
}
您也可以使用ArrayList<Integer> 或者也可以使用int[] 来完成所有操作,因为总和是第二个数组中元素的数量:
void setup(){
int[] src = {6, 3, 1};
int[] dst = new int[sum(src)];
int dstIndex = 0;
for(int i = 0; i < src.length; i++){
// from 0 to the current index value in the array
for(int j = 0; j < src[i]; j++){
// add the index to the list
dst[dstIndex++] = i;
}
}
println(sum(src));
println(dst);
}
int sum(int[] array){
int total = 0;
for(int i : array){
total += i;
}
return total;
}
Bare in mind Processing 有其他形式,例如 Python 或 JavaScript
在 Python 中,您可以执行以下操作:
import itertools
a = [6, 3, 1]
b = list(itertools.chain(*[ [index] * value for index, value in enumerate(a)]))
print(b) # prints [0, 0, 0, 0, 0, 0, 1, 1, 1, 2]
上面是通过列表理解创建一个嵌套列表,然后通过 itertools 展平列表
在 JS 中你也可以这样做:
a = [6, 3, 1];
b = a.map((value, index) => new Array(value).fill(index)).flat();
console.log(b); //prints [0, 0, 0, 0, 0, 0, 1, 1, 1, 2]
有了这些,我还会仔细检查边缘情况(如果你有像 0 或 -1 这样的值会与索引混淆等),否则如果这需要简单地处理从 1 开始的整数将指令包装在一个函数中,该函数首先检查输入并拒绝无效输入。
例如
void setup(){
int[] src = {6, 3, 1};
try{
println(weightedProbabilities(src));
}catch(Exception e){
println(e.getMessage());
}
}
int[] weightedProbabilities(int[] src) throws Exception{
// validate input data
for(int i = 0; i < src.length; i++){
if(src[i] <= 0){
throw new Exception(String.format("invalid element %d at index %d",src[i],i));
}
}
// process data
int[] dst = new int[sum(src)];
int dstIndex = 0;
for(int i = 0; i < src.length; i++){
// from 0 to the current index value in the array
for(int j = 0; j < src[i]; j++){
// add the index to the list
dst[dstIndex++] = i;
}
}
// return result
return dst;
}
int sum(int[] array){
int total = 0;
for(int i : array){
total += i;
}
return total;
}