fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <vector>
  4. #include <random>
  5. #include <functional>
  6.  
  7.  
  8. using row_type = std::vector<unsigned>;
  9. using grid_type = std::vector<row_type>;
  10.  
  11. std::function<unsigned()> get_rng(unsigned min, unsigned max)
  12. {
  13. std::mt19937 generator((std::random_device())());
  14. return [=] () mutable
  15. {
  16. return std::uniform_int_distribution<unsigned>(min, max)(generator);
  17. };
  18. }
  19.  
  20.  
  21. // note that max_value is treated as a bit of a suggestion.
  22. // modify rnd_non_multiple if that isn't satisfactory.
  23. grid_type generate_grid(unsigned target, unsigned n_target_values,
  24. unsigned width, unsigned height, unsigned max_value)
  25. {
  26. grid_type grid(height, row_type(width));
  27.  
  28. // convenience functions:
  29. auto rnd_width = get_rng(0, width - 1);
  30. auto rnd_height = get_rng(0, height - 1);
  31.  
  32. auto factor = get_rng(1, max_value / target);
  33. auto rnd_multiple = [target, &factor] { return factor() * target; };
  34.  
  35. auto lt_target = get_rng(1, target - 1); // less than target
  36. auto rnd_non_multiple = [&rnd_multiple, &lt_target]
  37. { return rnd_multiple() + lt_target(); };
  38.  
  39. {
  40. // place multiples randomly
  41. unsigned targets_assigned = 0;
  42. while (targets_assigned < n_target_values)
  43. {
  44. unsigned y = rnd_height();
  45. unsigned x = rnd_width();
  46.  
  47. if (!grid[y][x])
  48. {
  49. grid[y][x] = rnd_multiple();
  50. ++targets_assigned;
  51. }
  52. }
  53. }
  54.  
  55. // fill the rest of the grid with non-multiples:
  56. for (auto& row : grid)
  57. for (auto & cell : row)
  58. if (!cell) cell = rnd_non_multiple();
  59.  
  60. return grid;
  61. }
  62.  
  63. void display(const grid_type& grid)
  64. {
  65. for (auto& row : grid)
  66. {
  67. for (auto& cell : row)
  68. std::cout << std::setw(3) << cell;
  69.  
  70. std::cout << '\n';
  71. }
  72. }
  73.  
  74. void display(const std::vector<unsigned>& v)
  75. {
  76. for (auto& e : v)
  77. std::cout << e << ' ';
  78. std::cout << '\n';
  79. }
  80.  
  81. std::vector<unsigned> extract_multiples(const grid_type& grid, unsigned val)
  82. {
  83. std::vector<unsigned> mults;
  84.  
  85. for (auto& row : grid)
  86. for (auto& cell : row)
  87. if (cell % val == 0) mults.push_back(cell);
  88.  
  89. return mults;
  90. }
  91.  
  92. int main()
  93. {
  94. unsigned target = 7 ;
  95. auto grid = generate_grid(target, 10, 5, 5, target*9);
  96. display(grid);
  97. std::cout << "\nMultiples are:\n\t";
  98. display(extract_multiples(grid, target));
  99. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
 62 14 12 14 10
 35 28 21 31 67
 11 42  7 35 58
 55 26 53 20 65
 47 14 21 64 17

Multiples are:
	14 14 35 28 21 42 7 35 14 21