Browse Source

Add Problem 2 solution

trunk
Shanti Chellaram 4 years ago
parent
commit
62092ac4a2
  1. 15
      c++/main.cpp
  2. 39
      c++/problem2.cpp
  3. 2
      c++/solutions.hpp

15
c++/main.cpp

@ -6,14 +6,20 @@
using namespace std;
int main() {
auto x = solve1;
int main(int argc, char *argv[]) {
if (argc < 2) {
return 0;
}
int problem_number = stoi(string(argv[1]));
solution_fn solutions[] = {solve1, solve2};
auto x = solutions[problem_number-1];
auto answer = x(cin);
cout << "Solution 1: " << answer.first << endl;
cout << "Solution 2: " << answer.second << endl;
return 0;
}
//istream get_input() {
// CURL *curl;
// CURLcode res;
@ -28,3 +34,8 @@ int main() {
//
// curl_global_cleanup();
//}
// TODO: automatically download input files and stuff
// char *home_dir = getenv("HOME");
// if (home_dir != NULL) {
//
// }

39
c++/problem2.cpp

@ -0,0 +1,39 @@
#include <sstream>
#include <cstdint>
#include <stdexcept>
#include "solutions.hpp"
using namespace std;
pair<string, string> solve2(istream& input) {
uint64_t part1 = 0, part2 = 0;
for (string line; getline(input, line); ) {
stringstream line_stream(line);
int64_t min_count, max_count;
char target;
string password;
line_stream >> min_count;
if (line_stream.get() != (int) '-') {
throw domain_error("input incorrect");
}
line_stream >> max_count;
if (line_stream.get() != (int) ' ') {
throw domain_error("input incorrect");
}
line_stream >> target;
if (line_stream.get() != (int) ':') {
throw domain_error("input incorrect");
}
if (line_stream.get() != (int) ' ') {
throw domain_error("input incorrect");
}
line_stream >> password;
size_t count = 0;
for (char c : password) {
count+=(int)(c == target);
}
part1 += (int)(count >= min_count && count <= max_count);
part2 += (int)((password[min_count - 1] == target) != (password[max_count - 1] == target));
}
return pair(to_string(part1), to_string(part2));
}

2
c++/solutions.hpp

@ -4,6 +4,8 @@
#include <utility>
#include <string>
typedef std::pair<std::string, std::string> (*solution_fn)(std::istream&);
#define DECL_SOLUTION(x) std::pair<std::string, std::string> solve##x(std::istream&);
DECL_SOLUTION(1)
DECL_SOLUTION(2)
Loading…
Cancel
Save