BSTSanityCheck.cxx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <algorithm>
  2. #include <cassert>
  3. #include <iostream>
  4. #include <random>
  5. #include <vector>
  6. #include "BST.h"
  7. #define SAMPLE_SIZE 1000
  8. #define NUM_TESTS 10000
  9. int main() {
  10. // C++11 random number tutorial: https://gist.github.com/PhDP/5289449
  11. // Seed random number generator
  12. std::mt19937_64 rng(time(0));
  13. // Create uniform distribution
  14. std::uniform_int_distribution<int> unif(
  15. std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
  16. std::uniform_int_distribution<int> op(0,10);
  17. std::vector<int> sampleData, BSTSortedData;
  18. sampleData.reserve(SAMPLE_SIZE);
  19. BSTSortedData.reserve(SAMPLE_SIZE);
  20. std::cout << "Running tests..." << std::flush;
  21. for (unsigned int sample = 0; sample < NUM_TESTS; sample++) {
  22. BST T;
  23. // On size_t usage here: https://stackoverflow.com/questions/131803/unsigned-int-vs-size-t
  24. for (size_t i = 0; i < SAMPLE_SIZE; i++) {
  25. if (op(rng) == 0 && !T.empty()) {
  26. T.Delete(sampleData.back());
  27. sampleData.pop_back();
  28. } else {
  29. // Add random integer to array
  30. int x = unif(rng);
  31. T.Insert(x);
  32. sampleData.push_back(x);
  33. }
  34. }
  35. while (!T.empty()) {
  36. BSTSortedData.push_back(T.DeleteMin());
  37. }
  38. std::sort(sampleData.begin(), sampleData.end());
  39. assert(sampleData == BSTSortedData);
  40. BSTSortedData.clear();
  41. sampleData.clear();
  42. if (sample % (NUM_TESTS / 10) == 0) {
  43. std::cout << "." << std::flush;
  44. }
  45. }
  46. std::cout << "Tests complete.\n";
  47. }