cxx17/cc14.cc

55 lines
1.2 KiB
C++

// Determine if a string has all-unique characters.
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <experimental/string_view>
#include <range/v3/all.hpp>
#include <string>
#include <unordered_map>
using namespace ranges;
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;
// 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++;
}
int singles = 0;
int odds = 0;
// TODO(michaelh): try as a filter.
for (auto c : count | view::values) {
if (c == 1) {
singles++;
}
if (is_odd(c)) {
odds++;
}
}
if (is_odd(nchars)) {
return singles == 1 && odds == 1;
} else {
return singles == 0 && odds == 0;
}
}
TEST_CASE("cc14", "palindrome") {
REQUIRE(palindrome("Taco Cat") == true);
REQUIRE(palindrome("Tact Coa") == true);
REQUIRE(palindrome("Happy") == false);
REQUIRE(palindrome("Pant") == false);
}