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
Rearranging cards into groups in JavaScript
We are required to write a JavaScript function that takes in an array of numbers, arr, as the first argument and a number, num, as the second argument.
The numbers in the array are in the range [1, 13], limits inclusive, representing the 1-based index of playing cards.
Our function should determine whether there exists a way to rearrange the cards into groups so that each group is size num, and consists of num consecutive cards.
Problem Example
For example, if the input to the function is:
const arr = [1, 4, 3, 2]; const num = 2;
Expected Output: true
Explanation: The cards can be rearranged as [1, 2], [3, 4] - two groups of 2 consecutive cards each.
Solution Approach
The algorithm works by:
- Creating a frequency map of all cards
- For each card, trying to form a consecutive group starting from that card
- Reducing the count of used cards from the frequency map
- Returning true if all cards can be grouped successfully
Implementation
const arr = [1, 4, 3, 2];
const num = 2;
const canRearrange = (arr = [], num = 1) => {
const find = (map, n, num) => {
let j = 0;
while(j < num) {
if(!map[n + j]) return false;
else map[n + j] -= 1;
j++;
}
return true;
};
let map = {};
arr.sort(function(a, b) {return a - b});
// Create frequency map
for(let n of arr) {
map[n] = map[n] ? map[n] + 1 : 1;
}
// Try to form consecutive groups
for(let n of arr) {
if(map[n] === 0 || find(map, n, num)) continue;
else return false;
}
return true;
};
console.log(canRearrange(arr, num));
true
Testing with Different Examples
// Test case 1: Can form groups
console.log("Test 1:", canRearrange([1, 2, 3, 4, 5, 6], 3)); // [1,2,3], [4,5,6]
// Test case 2: Cannot form groups
console.log("Test 2:", canRearrange([1, 2, 4, 5], 3)); // Missing 3 or 6
// Test case 3: Single card groups
console.log("Test 3:", canRearrange([1, 3, 5], 1)); // [1], [3], [5]
Test 1: true Test 2: false Test 3: true
How It Works
The find helper function attempts to form a consecutive group of num cards starting from card n. It checks if all required consecutive cards are available and decrements their count from the frequency map.
The main function processes cards in sorted order, ensuring that for each remaining card, we can form a valid consecutive group. If any card cannot be part of a valid group, the function returns false.
Conclusion
This solution efficiently determines if playing cards can be rearranged into consecutive groups using a frequency map approach. The time complexity is O(n log n) due to sorting, where n is the number of cards.
