The Mean Average Distribution (MAD) is a math concept which is taught before Standard Deviation and then mostly forgotten. Like a standard deviation, the MAD is a value which shows the variability or spread for a dataset around the mean.
The steps to calculate the MAD are as follows:
-
Determine the average
-
For each datapoint determine the distance from the average.
-
Sum all of the distances
-
Take an average of the sum
For instance for the followings datasets:
(2,2,4,4) has an Average of 3 and a MAD of 1
(1,1,4,6) has an Average of 3 and a MAD of 2
Therefore the data in the second dataset is more spread out.
Write a function to calculate the Mean Average Distribution of a dataset of arbitrary length.
function mad(array) {
if(array.length === 0){return null}
if(array.length === 1){return 0}
let average = (array.reduce((acc, cV) => acc + cV))/array.length
let array2 = array.map((item,index,arr)=> Math.abs(item-average))
return (array2.reduce((acc, cV) => acc + cV))/array2.length;
}
const assert = require("chai").assert;
// If the failure output for deep equality is truncated, `chai.config.truncateThreshold` can be adjusted.
describe("Solution", function() {
it("Simple and Edge Cases", function() {
Test.assertDeepEquals(mad([1,1,4,6]), 2);
Test.assertDeepEquals(mad([2,2,4,4]), 1);
});
it("Variable Length Arrays", function() {
Test.assertDeepEquals(mad([4,6]), 1);
Test.assertDeepEquals(mad([2,2,2,4,4,4]), 1);
Test.assertDeepEquals(mad([]), null);
Test.assertDeepEquals(mad([5223]),0);
});
it("Random Test", function() {
function madTest(array) {
if(array.length === 0){return null}
if(array.length === 1){return 0}
let average = (array.reduce((acc, cV) => acc + cV))/array.length
let array2 = array.map((item,index,arr)=> Math.abs(item-average))
return (array2.reduce((acc, cV) => acc + cV))/array2.length;
}
for (let i=0;i<100;i++){
arrLen=1+Math.floor(Math.random()*100)
let testArray=[]
for(let j=0;j<arrLen;j++){
testArray.push(Math.floor(Math.random()*100))
}
console.log('testing...',testArray)
Test.assertDeepEquals(mad(testArray), madTest(testArray));
};
});
});