Skip to content

Instantly share code, notes, and snippets.

@felipealbrecht
Created December 12, 2015 17:43
Show Gist options
  • Save felipealbrecht/6e9cc11aa7b51e847d38 to your computer and use it in GitHub Desktop.
Save felipealbrecht/6e9cc11aa7b51e847d38 to your computer and use it in GitHub Desktop.
Jumping frog
// The frog start at position -1, the river starts at position 0, the frog must go to position river size (path) or bigger
// Compile with c++11, e.g. in clang++: clang++ frog.cpp -std=c++11
#include <vector>
#include <iostream>
#include <tuple>
typedef std::vector<int> Path;
typedef std::vector<std::tuple<int, int> > Visited;
bool walk(const int pos, const int speed, const Path& path, Visited& visited, Visited& walking);
static int ts = 0;
int main() {
Path path = {0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1};
Visited visited;
int pos = -1;
int speed = 0;
Visited walking;
if (walk(pos, speed , path, visited, walking)) {
std::cerr << "#ops: " << ts << std::endl;
std::cerr << "***** " << walking.size() << " ***** " << std::endl;
for (auto w: walking) {
std::cerr << std::get<0>(w) << " " << std::get<1>(w) << std::endl;
}
return 0;
}
return 1;
}
bool walk(const int pos, const int speed, const Path& path, Visited& visited, Visited& walking) {
ts++;
if (std::find(visited.begin(), visited.end(), std::make_tuple(pos, speed)) != visited.end()) {
return false;
}
visited.emplace_back(pos, speed);
// Crossed the river
if (pos >= (signed) (path.size())) {
walking.push_back(std::make_tuple(pos, speed));
return true;
}
// Is on some block?
if (pos >= 0 && !path[pos]) {
return false;
}
// Too far from the river
if (pos <= (-10 * (signed) path.size())) {
return false;
}
std::vector<Visited> walkings;
Visited walking1;
if (walk(pos + (speed + 1), speed + 1, path, visited, walking1)) {
walkings.push_back(walking1);
}
Visited walking2;
if (walk(pos + speed, speed, path, visited, walking2)) {
walkings.push_back(walking2);
}
Visited walking3;
if (walk(pos + (speed - 1), speed - 1, path, visited, walking3)) {
walkings.push_back(walking3);
}
if (walkings.empty()) {
return false;
}
std::sort(walkings.begin(), walkings.end(), [](Visited& a, Visited& b) {
return a.size() < b.size();
});
walking = walkings[0];
walking.push_back(std::make_tuple(pos, speed));
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment