Skip to content

Instantly share code, notes, and snippets.

@cjxgm
Last active August 29, 2015 14:05
Show Gist options
  • Save cjxgm/13ffd989f97e8e271be6 to your computer and use it in GitHub Desktop.
Save cjxgm/13ffd989f97e8e271be6 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <sstream>
#include <string>
#include <regex>
using namespace std;
// regular expression
struct match_wrapper
{
match_wrapper() : success{false} {}
match_wrapper(smatch&& m) : success{true}, m{std::move(m)} {}
operator bool() { return success; }
string operator[](int i) { return std::move(m[i].str()); }
private:
bool success;
smatch m;
};
static match_wrapper match(const regex& re, const string& s)
{
smatch m;
if (regex_match(s, m, re))
return {std::move(m)};
return {};
}
// conversion
static int name2addr(const string& name)
{
int addr = 0;
for (auto c: name)
addr = addr * 26 + c - 'A' + 1;
return addr;
}
static string addr2name(int addr)
{
stringstream name;
while (addr--) {
name << char(addr%26 + 'A');
addr /= 26;
}
auto s = name.str();
return string{s.rbegin(), s.rend()};
}
// rc = row-column
// ad = alpha-digit
static regex re_rc{"R(\\d+)C(\\d+)"};
static regex re_ad{"([A-Z]+)(\\d+)"};
struct bad_format {};
int main()
{
string line;
getline(cin, line); // skip first line
while (getline(cin, line)) {
if (auto m = match(re_rc, line))
cout << addr2name(atoi(m[2].c_str())) << m[1] << endl;
else if (auto m = match(re_ad, line))
cout << 'R' << m[2] << 'C' << name2addr(m[1]) << endl;
else throw bad_format{};
}
}
#!/usr/bin/ruby
$ord_A = "A".ord
def name2addr(name)
addr = 0
name.each_char do |c|
addr = addr*26 + c.ord - $ord_A + 1
end
return addr
end
def addr2name(addr)
name = ""
while addr != 0
addr -= 1
name = (addr%26 + $ord_A).chr + name
addr /= 26
end
return name
end
gets # skip first line
while gets
line = $_.chomp
if m = /R(\d+)C(\d+)/.match(line)
puts addr2name(m[2].to_i) + m[1]
elsif m = /([A-Z]+)(\d+)/.match(line)
puts "R" + m[2] + "C" + name2addr(m[1]).to_s
else
abort "bad_format"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment