fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstdlib>
  4. #include <ctime>
  5.  
  6. class Item {
  7. public:
  8. Item();
  9. Item(int x, int y);
  10.  
  11. int x, y;
  12. };
  13.  
  14. Item::Item() : x(0), y(0) { }
  15.  
  16. Item::Item(int x, int y) : x(x), y(y) { }
  17.  
  18. std::vector<Item> create_random_items(int m, int n) {
  19. std::vector<Item> chosen_items;
  20.  
  21. std::vector<Item> items;
  22.  
  23. for (int x = 1; x <= m; ++x) {
  24. for (int y = 1; y <= m; ++y) {
  25. items.push_back(Item(x, y));
  26. /* If you have C++11, this will be faster: items.emplace_back(x, y); */
  27. }
  28. }
  29.  
  30. while (n--) {
  31. // Get a random number and make sure that it is within the bounds of the items
  32. // vector. Note that the modulus technique does not guarantee that the
  33. // distribution of random numbers will be uniform.
  34. int offset = std::rand() % items.size();
  35.  
  36. // Get an iterator to this item.
  37. std::vector<Item>::iterator item = items.begin() + offset;
  38.  
  39. // Move the item to the chosen_items list.
  40. chosen_items.push_back(*item);
  41.  
  42. // C++11: chosen_items.emplace_back(*item);
  43.  
  44. // Remove the item from the other list so we don't pick it again.
  45. items.erase(item);
  46. }
  47.  
  48. return chosen_items;
  49. }
  50.  
  51. int main() {
  52. // Seed random number generator with the current time.
  53. std::srand(std::time(0));
  54.  
  55. std::vector<Item> items = create_random_items(5, 4);
  56.  
  57. for (std::vector<Item>::iterator i = items.begin(); i != items.end(); ++i) {
  58. std::cout << '(' << i->x << ',' << i-> y << ')' << std::endl;
  59. }
  60.  
  61. return 0;
  62. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
(2,5)
(1,3)
(2,2)
(5,1)