Skip to content

Instantly share code, notes, and snippets.

@jtsagata
Last active August 27, 2019 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtsagata/933c9d0e537d8653c2a6bed3c6378ec8 to your computer and use it in GitHub Desktop.
Save jtsagata/933c9d0e537d8653c2a6bed3c6378ec8 to your computer and use it in GitHub Desktop.
Risk Card Set Kata
#include <algorithm>
#include <cassert>
#include <vector>
//#include <set>
using namespace std;
using card_t=char;
const card_t Jocker = 'J';
// Check if vector contains element
template <typename T>
bool contains(const vector<T> &hand, T card) {
return find(hand.begin(), hand.end(), card) != hand.end();
}
// Get vector cardinality
template <typename T>
auto getCardinality(vector<T> hand) {
// set<T> set(begin(hand), end(hand));
sort(hand.begin(), hand.end());
hand.erase(unique(hand.begin(), hand.end()), hand.end());
return hand.size();
}
// Is equal distribution ?
bool eqDistr(const vector<card_t> &hand) {
assert(hand.size() == 4);
// is it X-X-Y-Y or X-Y-Y-Y ?
auto cnt = count_if(hand.begin(), hand.end(), [&](char c) { return c == hand[0]; });
return cnt == 2;
}
auto isValid(const vector<card_t> &hand) {
if (hand.size() < 3) return false;
if (hand.size() > 4) return true;
if (contains(hand, Jocker)) return true; // 3 cards. Did vector contains 'J' ?
if ((hand.size() == 4) && (!eqDistr(hand))) return true;
auto crd = getCardinality(hand);
if (crd >= 3) return true; // different cards
if (crd == 1) return true; // all cards the same
return false; // X-Y-Y, no jocker case
}
auto main() -> int {
// Invalid: less cards
assert(!isValid({}));
assert(!isValid({'C', 'C'}));
// Valid: different cards
assert(isValid({'C', 'S', 'H'}));
assert(isValid({'C', 'H', 'J'}));
assert(isValid({'C', 'S', 'H', 'J'}));
// Valid: same cards
assert(isValid({'C', 'C', 'C'}));
assert(isValid({'J', 'J', 'J'}));
// Use of 'J'
assert(isValid({'S', 'S', 'J'}));
assert(isValid({'S', 'J', 'S'}));
assert(!isValid({'S', 'S', 'C'}));
assert(isValid({'S', 'J', 'J'}));
assert(isValid({'S', 'H', 'J'}));
// Invalid cases
assert(!isValid({'S', 'C', 'C'}));
// 4 cards
assert(isValid({'H', 'H', 'C', 'H'}));
assert(isValid({'H', 'H', 'J', 'H'}));
assert(isValid({'J', 'H', 'J', 'H'}));
assert(!isValid({'H', 'H', 'C', 'C'}));
// 5 cards
assert(isValid({'H', 'H', 'C', 'H', 'C'}));
assert(isValid({'H', 'H', 'C', 'H', 'H'}));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment