Guest User

ciq-compress

a guest
Aug 3rd, 2025
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Toybox.Lang;
  2. import Toybox.System;
  3.  
  4. function compressArrayData(data as Array<Numeric>, newSize as Number)  as Array<Numeric> {
  5.     if (newSize >= data.size()) {
  6.         return data;
  7.     }
  8.  
  9.     // bucketSize > 1. e.g. if data.size() is 480 and newSize is 240, bucket size is 2
  10.     var bucketSize = data.size() * 1.0 / newSize;
  11.     var outputArray = new Array<Numeric>[newSize];
  12.     var outputIndex = 0;
  13.  
  14.     var bucketPositioninInput = 0.0; // the fractional index of the bucket in the input data
  15.     while (outputIndex < newSize) {
  16.         var numDataElements = (bucketSize + 0.5).toNumber(); // round up
  17.         var startDataIndex = bucketPositioninInput.toNumber(); // round down
  18.         var endDataIndex = startDataIndex + numDataElements - 1;
  19.         var nextPositionInInput = bucketPositioninInput + bucketSize;
  20.  
  21.         // take the weighted average
  22.         var sum = 0;
  23.         for (var i = startDataIndex; i <= endDataIndex; i++) {
  24.             var weight = 1;
  25.  
  26.             // the first and last elements in the bucket may have weights
  27.             // less than 1, in the case that the bucket size is fractional
  28.             if (i == startDataIndex) {
  29.                 // the weight is the width of the start of the bucket to the start of the next data point
  30.                 weight = (startDataIndex + 1) - bucketPositioninInput;
  31.             } else if (i == endDataIndex) {
  32.                 // the weight is the width of the start of the current point to the end of the bucket
  33.                 weight = nextPositionInInput - i;
  34.             }
  35.             sum += data[i] * weight;
  36.         }
  37.         var avg = sum * 1.0 / bucketSize;
  38.         outputArray[outputIndex] = avg;
  39.         bucketPositioninInput = nextPositionInInput;
  40.         outputIndex++;
  41.     }
  42.     return outputArray;
  43. }
  44.  
  45. function test() {
  46.     System.println(compressArrayData([1,2,3,4,5,6,7,8], 4)); // "[1.500000, 3.500000, 5.500000, 7.500000]"
  47.     System.println(compressArrayData([1,2,3,4,5,6,7,8], 5)); // "[1.375000, 2.750000, 4.500000, 5.875000, 7.624999]"
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment