Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A solution for some 2010 CodeJam thing, see the file intro for links etc.
//
// codejamt9.cpp - By Arthur Langereis (@zenmumbler)
//
// Crux of the solution is the encodeChar function which builds a string out of the n2s keypad number to character list.
// The resulting string will be 10 sets of 4 characters that the keypad number will refer to,
// the character's rel. offset in the set of 4 is # of key presses - 1.
// I could have just written out the full generated string I guess, but why would I do something the
// computer can do a lot faster?
// Also, a source file without something from <algorithm> or <numeric> is just empty inside. :)
//
// Problem here: http://code.google.com/codejam/contest/351101/dashboard#s=p2
// found via: http://thisthread.blogspot.com/2013/05/t9-spelling.html
//
#include <string>
#include <vector>
#include <numeric>
#include <iostream>
#include <utility>
using namespace std;
string readLine() {
string s;
getline(cin, s);
return s;
}
using token = pair<char, size_t>;
token encodeChar(char c) {
static const vector<const string> n2s = { " ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
static const auto full = std::accumulate(begin(n2s), end(n2s), string{}, [](const string& res, const string& field) {
return res + field + string(4 - field.size(), '_');
});
auto index = full.find(c);
return { '0' + (index / 4), 1 + (index % 4) };
}
int main(int argc, const char * argv[]) {
auto itemCount = stol(readLine()),
counter = 0L;
while (itemCount-- && cin.good()) {
auto chars = readLine();
auto lastChar = 'X';
cout << "Case #" << ++counter << ": ";
for (char c : chars) {
auto tok = encodeChar(c);
if (tok.first == lastChar)
cout << ' ';
lastChar = tok.first;
cout << string(tok.second, tok.first);
}
cout << '\n';
}
}

sehe commented May 14, 2013

Haha. I like your thinking too ! Did you see mine: https://gist.github.com/sehe/5580146

(please tuck tongue firmly in cheek when reading that code)

Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment