Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Checking the intensity of shuffle of an array - JavaScript
An array of numbers is 100% shuffled if no two consecutive numbers appear together in ascending order. It is 0% shuffled if all adjacent pairs are in ascending order. The shuffle intensity measures how much an array deviates from a perfectly sorted ascending sequence.
For an array of length n, there are n-1 adjacent pairs to examine. We calculate the percentage of pairs that are NOT in ascending order.
How It Works
The algorithm counts pairs where the first element is greater than the second element (descending pairs). The shuffle intensity is calculated as:
Shuffle Intensity = (Number of descending pairs / Total pairs) × 100
Example
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
40
Step-by-Step Analysis
Let's analyze the array [4, 23, 1, 23, 35, 78, 4, 45, 7, 34, 7] with pairs:
const arr = [4, 23, 1, 23, 35, 78, 4, 45, 7, 34, 7];
console.log("Analyzing pairs:");
for(let i = 0; i arr[i+1];
console.log(`${arr[i]} -> ${arr[i+1]}: ${isDescending ? 'Descending' : 'Ascending'}`);
}
console.log(`\nTotal pairs: ${arr.length - 1}`);
console.log(`Descending pairs: 4`);
console.log(`Shuffle intensity: ${(4/10) * 100}%`);
Analyzing pairs:
4 -> 23: Ascending
23 -> 1: Descending
1 -> 23: Ascending
23 -> 35: Ascending
35 -> 78: Ascending
78 -> 4: Descending
4 -> 45: Ascending
45 -> 7: Descending
7 -> 34: Ascending
34 -> 7: Descending
Total pairs: 10
Descending pairs: 4
Shuffle intensity: 40%
Testing Different Cases
const shuffleIntensity = arr => {
let incorrectPairs = 0;
if(arr.length arr[i+1]){
incorrectPairs++;
}
}
return (incorrectPairs / (arr.length - 1)) * 100;
};
// Test cases
console.log("Sorted array:", shuffleIntensity([1, 2, 3, 4, 5])); // 0%
console.log("Reverse sorted:", shuffleIntensity([5, 4, 3, 2, 1])); // 100%
console.log("Mixed array:", shuffleIntensity([3, 1, 4, 2, 5])); // 50%
console.log("Single element:", shuffleIntensity([42])); // 0%
Sorted array: 0
Reverse sorted: 100
Mixed array: 50
Single element: 0
Conclusion
The shuffle intensity function measures array randomness by counting descending adjacent pairs. A 0% intensity indicates perfect ascending order, while 100% means complete reverse order.
