Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Toybox.Lang;
- import Toybox.System;
- function compressArrayData(data as Array<Numeric>, newSize as Number) as Array<Numeric> {
- if (newSize >= data.size()) {
- return data;
- }
- // bucketSize > 1. e.g. if data.size() is 480 and newSize is 240, bucket size is 2
- var bucketSize = data.size() * 1.0 / newSize;
- var outputArray = new Array<Numeric>[newSize];
- var outputIndex = 0;
- var bucketPositioninInput = 0.0; // the fractional index of the bucket in the input data
- while (outputIndex < newSize) {
- var numDataElements = (bucketSize + 0.5).toNumber(); // round up
- var startDataIndex = bucketPositioninInput.toNumber(); // round down
- var endDataIndex = startDataIndex + numDataElements - 1;
- var nextPositionInInput = bucketPositioninInput + bucketSize;
- // take the weighted average
- var sum = 0;
- for (var i = startDataIndex; i <= endDataIndex; i++) {
- var weight = 1;
- // the first and last elements in the bucket may have weights
- // less than 1, in the case that the bucket size is fractional
- if (i == startDataIndex) {
- // the weight is the width of the start of the bucket to the start of the next data point
- weight = (startDataIndex + 1) - bucketPositioninInput;
- } else if (i == endDataIndex) {
- // the weight is the width of the start of the current point to the end of the bucket
- weight = nextPositionInInput - i;
- }
- sum += data[i] * weight;
- }
- var avg = sum * 1.0 / bucketSize;
- outputArray[outputIndex] = avg;
- bucketPositioninInput = nextPositionInInput;
- outputIndex++;
- }
- return outputArray;
- }
- function test() {
- System.println(compressArrayData([1,2,3,4,5,6,7,8], 4)); // "[1.500000, 3.500000, 5.500000, 7.500000]"
- System.println(compressArrayData([1,2,3,4,5,6,7,8], 5)); // "[1.375000, 2.750000, 4.500000, 5.875000, 7.624999]"
- }
Advertisement
Add Comment
Please, Sign In to add comment