Last active
April 28, 2019 19:05
-
-
Save outfrost/d113fbc7d06e44047060d20123e949f9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <unordered_set> | |
#include <random> | |
#include <iostream> | |
struct Point final { | |
const int x; | |
const int y; | |
Point() : x(0), y(0) {} | |
Point(int x, int y) : x(x), y(y) {} | |
~Point() = default; | |
bool operator ==(const Point& other) const { | |
return x == other.x && y == other.y; | |
} | |
}; | |
// Hack in a hash implementation for Point | |
namespace std { | |
template<> struct hash<Point> { | |
using argument_type = Point; | |
using result_type = std::size_t; | |
result_type operator ()(const argument_type& v) const noexcept { | |
const result_type hx(std::hash<int>{}(v.x)); | |
const result_type hy(std::hash<int>{}(v.y)); | |
return hx ^ (hy << 8 * (sizeof(std::size_t) - sizeof(int))); | |
} | |
}; | |
} | |
std::unordered_set<Point> positions {}; | |
std::random_device randomDevice; | |
std::mt19937 mt {randomDevice()}; | |
std::uniform_int_distribution<> coordDistribution {0, 15}; | |
const Point& generateFoodPos() { | |
for (;;) { | |
// [iterator, inserted] | |
const auto result = positions.emplace(coordDistribution(mt), | |
coordDistribution(mt)); | |
if (result.second) return *result.first; | |
} | |
} | |
int main() { | |
for (int i = 0; i < 5; ++i) { | |
const auto& point = generateFoodPos(); | |
std::cout << point.x << "," << point.y << "\n"; | |
} | |
std::cout << "\n" << positions.size() << "\n"; | |
return 0; | |
} |
Author
outfrost
commented
Apr 28, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment