微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

处理加权概率

如何解决处理加权概率

我对 Processing 很陌生(来自 R),并且在使用某个加权概率函数时遇到了问题。

我有一个包含 100 个数字的数组。

然后使用所有这些数字的总和来创建一个长度为数字总和的数组。

新数组中的每个数字都初始化为零。

我想做什么:

  1. 遍历第一个数组中的每个数字(例如,从第一个数组的第一个数字开始,例如 6)。

  2. 将第二个数组中的前 6 个(因为这是当前数字)项的长度总和设置为 6 的索引号。因此,第二个数组中的前六个项将为 {0,0}。

  3. 对所有数字重复。例如,数组 {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 有其他形式,例如 PythonJavaScript

在 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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。