- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Hand of Straights in C++
Suppose Rima has a hand of cards, given as an array of integers. Now she wants to shuffle the cards into groups so that each group is size W, and consists of W consecutive cards. We have to check whether it is possible or not.
So if the cards are [1,2,3,6,2,3,4,7,8], and W = 3, then the answer will be true, as she can rearrange them like [1,2,3],[2,3,4],[6,7,8]
To solve this, we will follow these steps −
- Define a map m, and store frequency of each element in hands into m
- while size of hand is not 0
- prev := 0
- it := pointer to the first key-value pair in m
- for i in range 0 to W – 1
- while value of it is 0, it := point to next pair
- if i > 0 and key of it – 1 = prev or i = 0, then
- decrease it value by 1
- prev := key of it
- otherwise return false
- it := point to next pair
- n := n – W
- return true.
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: bool isNStraightHand(vector<int>& hand, int W) { map <int, int> m; int n = hand.size(); if(n % W != 0) return false; for(int i = 0; i < n; i++){ m[hand[i]]++; } while(n){ map <int, int> :: iterator it = m.begin(); int prev = 0; for(int i = 0; i < W; i++){ while(it->second == 0) it++; if((i > 0 && it->first - 1 == prev) || i == 0){ it->second--; prev = it->first; }else{ return false; } it++; } n -= W; } return true; } }; main(){ vector<int> v = {1,2,3,6,2,3,4,7,8}; Solution ob; cout << (ob.isNStraightHand(v, 3)); }
Input
[1,2,3,6,2,3,4,7,8] 3
Output
1
Advertisements