cc14: changed to a range.

master
Michael Hope 6 years ago
parent 1178f687a3
commit eaee080303
  1. 33
      cc14.cc

@ -4,9 +4,12 @@
#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) {
@ -14,32 +17,32 @@ bool palindrome(std::experimental::string_view src) {
int nchars = 0;
// TODO(michaelh): try as a range comprehension.
for (auto ch : src) {
if (std::isalpha(ch)) {
count[std::tolower(ch)]++;
nchars++;
}
// 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 range.
for (const auto& c : count) {
if (c.second == 1) {
// TODO(michaelh): try as a filter.
for (auto c : count | view::values) {
if (c == 1) {
singles++;
} else if (is_odd(c.second)) {
}
if (is_odd(c)) {
odds++;
}
}
if (odds != 0) {
return false;
} else if (is_odd(nchars)) {
return singles == 1;
if (is_odd(nchars)) {
return singles == 1 && odds == 1;
} else {
return singles == 0;
return singles == 0 && odds == 0;
}
}

Loading…
Cancel
Save