Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const arr1 = generateRandomNumbers(20, 5);
- const arr2 = generateRandomNumbers(20, 5);
- const { result: arr1WeightedAverage, weight: weightArr1WeightedAverage } = calculateWeightedAverage(arr1);
- const { result: arr2WeightedAverage, weight: weightArr2WeightedAverage } = calculateWeightedAverage(arr2);
- console.log(arr1WeightedAverage, weightArr1WeightedAverage);
- console.log(arr2WeightedAverage, weightArr2WeightedAverage);
- const temp = 4;
- // how to just calculate the new arr1WeightedAverage without pushing temp into arr1 execting the calculateWeightedAverage
- // I do not want to do this process:
- // arr1.push(4);
- // const newArr1WeightedAverage = calculateWeightedAverage(arr1);
- // I just want to:
- // const newArr1WeightedAverage = calculateNewWeightedAverage(arr1WeightedAverage, temp);
- // what should i write inside this function:
- function calculateNewWeightedAverage(previousWeightedAverage: number, newNumber: number) {
- // mathematical logic ...
- // note: i want to recaluculate it without the previous weight
- // although i think it is impossible
- // return new weighted average;
- }
- function calculateWeightedAverage(arr: number[]) {
- let result = 0, weight = 0;
- for (let i = 1; i <= 5; i++) {
- const weighterAverageCount = arr.filter(item => item === i).length;
- if (weighterAverageCount === 0) continue;
- const weightedAverage = (weighterAverageCount * i);
- weight += (i * weighterAverageCount);
- result += weightedAverage;
- }
- return { result: result / arr.length, weight };
- }
- function generateRandomNumbers(howManyNumber: number, to: number): number[] {
- const arrayFullOfRandomNumbers = [];
- for (let i = 0; i < howManyNumber; i++) {
- const randomNumberBetweenOneAndTo = Math.round(Math.random() * to);
- if (randomNumberBetweenOneAndTo === 0) continue;
- arrayFullOfRandomNumbers.push(randomNumberBetweenOneAndTo);
- }
- return arrayFullOfRandomNumbers;
- }
Add Comment
Please, Sign In to add comment