Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <cassert>
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
std::vector<int> toVector(const std::string& str) {
std::vector<int> result;
for (auto c : str) {
result.push_back(c - '0');
}
return result;
}
#if 0
int sumAdjacent(const std::string& str) {
if (str.size() < 2) return 0;
auto v = toVector(str);
int sum = 0;
int last = v[0];
int curr = 0;
int adjCount = 1;
bool adj = false;
for (auto it = v.begin() + 1; it != v.end(); ++it) {
curr = *it;
adj = curr == last;
printf("last=%d curr=%d adj=%d adjCount=%d\n", last, curr, (int) adj, adjCount);
if (!adj && adjCount > 1) {
printf("changed %d * %d\n", adjCount, curr);
sum += adjCount * last;
}
adjCount = adj ? adjCount + 1 : 1;
last = curr;
}
if (adjCount > 1) {
printf("finish %d * %d\n", adjCount, curr);
sum += adjCount * last;
}
printf("sum of %s = %d\n", str.c_str(), sum);
return sum;
}
#endif
std::vector<std::vector<int>> group(const std::vector<int>& v) {
std::vector<std::vector<int>> result;
std::vector<int> currGroup;
int last = 0;
for (auto n : v) {
if (last == n) {
currGroup.push_back(n);
} else {
if (!currGroup.empty()) {
result.push_back(std::move(currGroup));
}
currGroup.clear();
currGroup.push_back(n);
}
last = n;
}
result.push_back(std::move(currGroup));
if (result.size() > 2) {
auto& f = result.front();
auto& b = result.back();
if (f.front() == b.back()) {
f.insert(f.end(), b.begin(), b.end());
}
result.resize(result.size() - 1);
}
for (auto g : result) {
printf("[");
for (auto n : g) {
printf("%d,", n);
}
printf("] ");
}
return result;
}
int sumAdjacent(const std::string& str) {
if (str.size() < 2) return 0;
auto v = toVector(str);
auto groups = group(v);
int sum = 0;
for (auto& g: groups) {
if (g.size() > 2) {
sum += g.front() * g.size();
} else if (g.size() > 1) {
sum += g.front();
}
}
printf("sum of %s is %d\n", str.c_str(), sum);
return sum;
}
int main() {
assert(sumAdjacent("") == 0);
assert(sumAdjacent("1") == 0);
assert(sumAdjacent("1122") == 3);
assert(sumAdjacent("1111") == 4);
assert(sumAdjacent("1234") == 0);
assert(sumAdjacent("91212129") == 9);
assert(sumAdjacent("991212129") == 27);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment