Checking the intensity of shuffle of an array - JavaScript



An array of numbers is 100% shuffled if no two consecutive numbers appear together in the array (we only consider the ascending order case here). And it is 0% shuffled if pairs are of consecutive numbers.

For an array of length n there will be n-1 pairs of elements (without distorting its order).

We are required to write a JavaScript function that takes in an array of numbers and returns a number between [0, 100] representing the intensity of shuffle in the array

Example

Following is the code −

const arr = [4, 23, 1, 23, 35, 78, 4, 45, 7, 34, 7]; // this function calculates deviation from ascending sort const shuffleIntensity = arr => {    let inCorrectPairs = 0;    if(arr.length <= 1){       return 0;    };    for(let i = 0; i < arr.length - 1; i++){       if(arr[i] - arr[i+1] <= 0){          continue;       };       inCorrectPairs++;    };    return (inCorrectPairs / (arr.length -1)) * 100; }; console.log(shuffleIntensity(arr));

Output

Following is the output in the console −

40

It means that 40% chunk of this array is shuffled.

Updated on: 2020-09-18T08:54:18+05:30

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements