Browse code

Switch from C to C++ stdlib for randomness

Robert Cranston authored on 21/05/2025 21:54:38
Showing 2 changed files

... ...
@@ -10,7 +10,7 @@ Features:
10 10
     -   Hunt And Kill
11 11
         -   Handles mazes of any size
12 12
         -   Random with seed (time in seconds since the epoch by default)
13
-        -   Fairly fast (10000*10000 cells in ~1100ms)
13
+        -   Fairly fast (10000*10000 cells in ~900ms)
14 14
 
15 15
 [`cxx-maze`]: https://git.rcrnstn.net/rcrnstn/cxx-maze
16 16
 
... ...
@@ -19,7 +19,7 @@ Features:
19 19
 ```
20 20
 $ make
21 21
 $ ./maze dummy
22
-1154ms
22
+885ms
23 23
 $ ./maze
24 24
 ██  ████████████████████████████████████████████████████████████████████████████
25 25
 ██  ██                          ██              ██      ██          ██      ████
... ...
@@ -1,6 +1,6 @@
1 1
 #include <chrono>
2
-#include <cstdlib>
3 2
 #include <iostream>
3
+#include <random>
4 4
 #include <sstream>
5 5
 #include <thread>
6 6
 #include <vector>
... ...
@@ -51,7 +51,7 @@ template<typename C = void(*)(Maze &)>
51 51
 Maze hunt_and_kill(int w, int h, unsigned seed, C callback = [](Maze &){})
52 52
 {
53 53
     auto maze = Maze(w, h, Maze::WALL);
54
-    std::srand(seed);
54
+    auto rand = std::default_random_engine(seed);
55 55
     // Entrance.
56 56
     maze(1, 0) = maze(1, 1) = Maze::PATH;
57 57
     // Interior.
... ...
@@ -79,7 +79,7 @@ Maze hunt_and_kill(int w, int h, unsigned seed, C callback = [](Maze &){})
79 79
         // If we have neighbors, carve path to random one.
80 80
         if (n != 0)
81 81
         {
82
-            n = std::rand() % n;
82
+            n = (int)rand() % n;
83 83
             FOR_NEIGHBOR(
84 84
                 if (maze(cx+nx, cy+ny) == Maze::WALL && n-- == 0)
85 85
                 {