nodejsdeveloperskh

weighted-average - prevent recalculation for new numbers

Dec 1st, 2021 (edited)
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const arr1 = generateRandomNumbers(20, 5);
  2. const arr2 = generateRandomNumbers(20, 5);
  3. const { result: arr1WeightedAverage, weight: weightArr1WeightedAverage } = calculateWeightedAverage(arr1);
  4. const { result: arr2WeightedAverage, weight: weightArr2WeightedAverage } = calculateWeightedAverage(arr2);
  5.  
  6. console.log(arr1WeightedAverage, weightArr1WeightedAverage);
  7. console.log(arr2WeightedAverage, weightArr2WeightedAverage);
  8.  
  9. const temp = 4;
  10.  
  11. // how to just calculate the new arr1WeightedAverage without pushing temp into arr1 execting the calculateWeightedAverage
  12. // I do not want to do this process:
  13. // arr1.push(4);
  14. // const newArr1WeightedAverage = calculateWeightedAverage(arr1);
  15. // I just want to:
  16. // const newArr1WeightedAverage = calculateNewWeightedAverage(arr1WeightedAverage, temp);
  17. // what should i write inside this function:
  18. function calculateNewWeightedAverage(previousWeightedAverage: number, newNumber: number) {
  19.     // mathematical logic ...
  20.     // note: i want to recaluculate it without the previous weight
  21.     // although i think it is impossible
  22.     // return new weighted average;
  23. }
  24.  
  25. function calculateWeightedAverage(arr: number[]) {
  26.     let result = 0, weight = 0;
  27.    
  28.     for (let i = 1; i <= 5; i++) {
  29.         const weighterAverageCount = arr.filter(item => item === i).length;
  30.  
  31.         if (weighterAverageCount === 0) continue;
  32.  
  33.         const weightedAverage = (weighterAverageCount * i);
  34.  
  35.         weight += (i * weighterAverageCount);
  36.         result += weightedAverage;
  37.     }
  38.    
  39.     return { result: result / arr.length, weight };
  40. }
  41.  
  42. function generateRandomNumbers(howManyNumber: number, to: number): number[] {
  43.     const arrayFullOfRandomNumbers = [];
  44.  
  45.     for (let i = 0; i < howManyNumber; i++) {
  46.         const randomNumberBetweenOneAndTo = Math.round(Math.random() * to);
  47.        
  48.         if (randomNumberBetweenOneAndTo === 0) continue;
  49.        
  50.         arrayFullOfRandomNumbers.push(randomNumberBetweenOneAndTo);
  51.     }
  52.  
  53.     return arrayFullOfRandomNumbers;
  54. }
Add Comment
Please, Sign In to add comment