问题描述
我对 Processing 很陌生(来自 R),并且在使用某个加权概率函数时遇到了问题。
然后使用所有这些数字的总和来创建一个长度为数字总和的数组。
新数组中的每个数字都初始化为零。
我想做什么:
-
将第二个数组中的前 6 个(因为这是当前数字)项的长度总和设置为 6 的索引号。因此,第二个数组中的前六个项将为 {0,0}。
-
对所有数字重复。例如,数组 {6,3,1} 应该创建数组 {0,1,2}
有没有人有任何想法如何做到这一点?我已经尝试了很多解决方案,但以前从未做过这样的加权概率。
解决方法
一种选择是利用 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,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,1]
b = list(itertools.chain(*[ [index] * value for index,value in enumerate(a)]))
print(b) # prints [0,1,2]
以上是通过列表理解创建嵌套列表,然后通过 itertools 将列表展平
在 JS 中你也可以这样做:
a = [6,1];
b = a.map((value,index) => new Array(value).fill(index)).flat();
console.log(b); //prints [0,2]
有了这些,我还会仔细检查边缘情况(如果您有像 0
或 -1
这样的值可能会干扰索引等),否则如果这需要处理整数从 1 开始,只需将指令包装在一个函数中,该函数首先检查输入并拒绝无效输入。
例如
void setup(){
int[] src = {6,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;
}