查找不同数字数组中的平均值

时间:2018-07-25 14:32:16

标签: javascript arrays sorting

我觉得我的标题说得不太好,如果您理解我的问题,有人可以改正它吗?

我有一个数组

arr = [1,2,3,4,5,
       6,7,8,9,0,
       3,4,7,2,1,
       4,6,1,2,3,
       5,6,8,9,3
       2,3,4,5,6
      ]

我想做几件事

  1. 将其拆分为大小为5的块
  2. 计算块数。在这种情况下,应该是6个大块。
  3. 计算每个位置中所有块的总数,然后将其除以块总数。在这种情况下,

    (1+6+3+4+5+2)/6, (2+7+4+6+6+3)/6, ..., (5+0+1+3+3+6)/6

  4. 以数组形式返回结果

    var result = [3.5, 4.66, ..., 3]

我有这个主意,但不确定如何实现。

谢谢

5 个答案:

答案 0 :(得分:1)

我相信这段代码可以满足您的要求。

function averageValues (arr) {
    var chunks = Math.ceil(arr.length / 5); // find the number of chunks
    var sums = [0, 0, 0, 0, 0]; // keep a running tally
    for (var i = 0; i < arr.length; i ++) {
        sums[i % 5] += arr[i]; // add each element to the proper part of the sum
    }
    for (var i = 0; i < sums.length; i ++) {
        sums[i] /= chunks; // divide each part of the sum by the number of chunks
    }
    return sums;
}

答案 1 :(得分:0)

您可以通过维护五个单独的总和以五个单独的平均值结尾来解决此问题。

准备长度为5的sums数组:

for (var x = 0; x < arr.length; x++)
  sums[x % 5] += arr[x];

对于您集合中的每个数字,将相应的总和增加该数字。

var numbers = arr.length / 5; // 6 numbers each
var result = sums.map(
  function(s) {
    return s / numbers; // divide each sum by 6
  }
);

将每个总和除以使用多少个数字:

{  
  "fulfillmentText":"This is a text response",
  "fulfillmentMessages":[  ],
  "source":"example.com",
  "payload":{  
    "google":{  },
    "facebook":{  },
    "slack":{  }
  },
  "outputContexts":[  
    {  
      "name":"<Context Name>",
      "lifespanCount":5,
      "parameters":{  
        "<param name>":"<param value>"
      }
    }
  ],
  "followupEventInput":{  }
}

这假设您的设置长度始终是5的倍数。

答案 2 :(得分:0)

这可能很有用:

TextView

答案 3 :(得分:0)

这是解决问题的一种更实用的方法。假设您的设置长度始终是5的倍数。

// add extra array helpers
Array.prototype.eachSlice = function (n, fn) {
  let slices = [];
  
  for (let i = 0; i < this.length; i += n) {
    let slice = this.slice(i, i + n);
    slices.push(slice);
  }
  
  if (fn) slices.forEach(fn);
  
  return slices;
}

Array.prototype.sum = function (fn) {
  let fnReduce = fn ? (acc, ...args) => acc + fn(...args) : (acc, v) => acc + v;
  return this.reduce(fnReduce, 0);
}

Array.prototype.avg = function (fn) {
  return this.sum(fn) / this.length;
}

// actual solution
let arr = [
  1,2,3,4,5,
  6,7,8,9,0,
  3,4,7,2,1,
  4,6,1,2,3,
  5,6,8,9,3,
  2,3,4,5,6,
];

let chunkSize = 5;

console.log('--- question #1 ---');
console.log('Split it into chunks with the size of 5.');
console.log('-------------------');

let chunks = arr.eachSlice(chunkSize);
console.log(chunks);



console.log('--- question #2 ---');
console.log('Calculate the number of chunks. In this case, it should be 6 chunks.');
console.log('-------------------');

console.log(chunks.length);



console.log('--- question #3 ---');
console.log('Calculate the sum of numbers of all chunks in each position and divide it by the total number of chunks.');
console.log('-------------------');

let avgChunks = new Array(chunkSize).fill()
                .map((_, i) => chunks.avg(chunk => chunk[i]));
console.log('See the result under question #4.');



console.log('--- question #4 ---');
console.log('Return results as an array.');
console.log('-------------------');

console.log(avgChunks);

答案 4 :(得分:0)

我认为@ Aplet123具有最直接,最容易理解的方法,尽管我做了一些修改以满足自己的需求。

var chunks = Math.ceil(arr.length / 5) // Find the number of chunks
var sums = new Array(5).fill(0) // Keeps a running tally and fill values 0  
arr.map((x, i) => sums[i%5] += arr[i]) // add each element to the proper part of the sum
var avgs = sums.map((x) => x/chunks /divide each part of the sum by the number of chunks