cxx17/cc14.cc

55 lines
1.2 KiB
C++
Raw Permalink Normal View History

2017-06-26 08:59:24 +02:00
// Determine if a string has all-unique characters.
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <experimental/string_view>
2017-06-26 20:00:23 +02:00
#include <range/v3/all.hpp>
2017-06-26 08:59:24 +02:00
#include <string>
#include <unordered_map>
2017-06-26 20:00:23 +02:00
using namespace ranges;
2017-06-26 08:59:24 +02:00
bool is_odd(int v) { return (v % 2) == 1; }
bool palindrome(std::experimental::string_view src) {
std::unordered_map<char, int> count;
int nchars = 0;
2017-06-26 20:00:23 +02:00
// Done to test range comprehensions. Not really any better than
// the procedural version.
for (auto ch :
src | view::filter([](char ch) { return std::isalpha(ch); }) |
view::transform([](char ch) { return std::tolower(ch); })) {
count[ch]++;
nchars++;
2017-06-26 08:59:24 +02:00
}
int singles = 0;
int odds = 0;
2017-06-26 20:00:23 +02:00
// TODO(michaelh): try as a filter.
for (auto c : count | view::values) {
if (c == 1) {
2017-06-26 08:59:24 +02:00
singles++;
2017-06-26 20:00:23 +02:00
}
if (is_odd(c)) {
2017-06-26 08:59:24 +02:00
odds++;
}
}
2017-06-26 20:00:23 +02:00
if (is_odd(nchars)) {
return singles == 1 && odds == 1;
2017-06-26 08:59:24 +02:00
} else {
2017-06-26 20:00:23 +02:00
return singles == 0 && odds == 0;
2017-06-26 08:59:24 +02:00
}
}
TEST_CASE("cc14", "palindrome") {
REQUIRE(palindrome("Taco Cat") == true);
REQUIRE(palindrome("Tact Coa") == true);
REQUIRE(palindrome("Happy") == false);
REQUIRE(palindrome("Pant") == false);
}