Skip to content

Instantly share code, notes, and snippets.

@outfrost
Last active April 28, 2019 19:05
Show Gist options
  • Save outfrost/d113fbc7d06e44047060d20123e949f9 to your computer and use it in GitHub Desktop.
Save outfrost/d113fbc7d06e44047060d20123e949f9 to your computer and use it in GitHub Desktop.
#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;
}
@outfrost
Copy link
Author

c++ -g -std=c++17 -Wall -Wextra -pedantic -o pointgenerator pointgenerator.cpp

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