Skip to content

Instantly share code, notes, and snippets.

@saxbophone
Created October 7, 2023 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saxbophone/2bedd6f6888a595a0182b0f11984b96e to your computer and use it in GitHub Desktop.
Save saxbophone/2bedd6f6888a595a0182b0f11984b96e to your computer and use it in GitHub Desktop.
C++ Lottery Machine implementation
#include <cstddef>
#include <numeric>
#include <random>
#include <stdexcept>
#include <vector>
class LotteryMachine {
public:
LotteryMachine(std::size_t number_of_balls)
: _prng(std::random_device()())
, _balls(number_of_balls)
{
std::iota(_balls.begin(), _balls.end(), 1);
}
std::size_t pick_ball() {
if (_balls.empty()) throw std::runtime_error("No balls left");
std::uniform_int_distribution<std::size_t> gen(0, _balls.size() - 1);
auto pick = _balls.begin() + gen(_prng);
std::size_t ball = *pick;
_balls.erase(pick);
return ball;
}
private:
std::default_random_engine _prng;
std::vector<std::size_t> _balls;
};
#include <iomanip>
#include <iostream>
int main() {
LotteryMachine lotto(59);
for (int j = 0; j < 10; ++j) {
for (int i = 0; i < 6; ++i) {
std::cout << std::setfill('0') << std::setw(2) << lotto.pick_ball() << " ";
std::cout.flush();
}
std::cout << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment