WeightedTable.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "stdafx.h"
  6. // This is a rather simplistic implementation of a weighted probability table.
  7. // If the weights are large, it will use a lot of memory.
  8. // It would be nice if we could use std::vector here, but leveraging STL with Chakra seems to cause problems.
  9. template <class T>
  10. class WeightedTable
  11. {
  12. public:
  13. WeightedTable() :
  14. entries(nullptr), size(0)
  15. {
  16. }
  17. void AddWeightedEntry(T value, unsigned int weight)
  18. {
  19. T * newEntries = static_cast<T *>(realloc(entries, (size + weight) * sizeof(T)));
  20. if (newEntries == nullptr)
  21. {
  22. // Should throw something better
  23. throw "OOM in AddWeightedEntry realloc";
  24. }
  25. entries = newEntries;
  26. for (unsigned int i = 0; i < weight; i++)
  27. {
  28. entries[size + i] = value;
  29. }
  30. size += weight;
  31. }
  32. T GetRandomEntry()
  33. {
  34. if (size == 0)
  35. {
  36. // Should throw something better
  37. throw "Illegal GetRandomEntry on empty WeightedTable";
  38. }
  39. return entries[GetRandomInteger(size)];
  40. }
  41. unsigned int GetSize()
  42. {
  43. return size;
  44. }
  45. T GetEntry(unsigned int index)
  46. {
  47. if (index >= size)
  48. {
  49. // Should throw something better
  50. throw "Illegal GetEntry beyond table end";
  51. }
  52. return entries[index];
  53. }
  54. private:
  55. T * entries;
  56. unsigned int size;
  57. };