/Classes/RNG.m

http://github.com/kstenerud/ObjectAL-for-iPhone · Objective C · 73 lines · 53 code · 15 blank · 5 comment · 5 complexity · 654a0e4813b893c5e7ccc31f3894e9c4 MD5 · raw file

  1. //
  2. // RNG.m
  3. //
  4. // Created by Karl Stenerud on 10-02-15.
  5. //
  6. #import "RNG.h"
  7. SYNTHESIZE_SINGLETON_FOR_CLASS_PROTOTYPE(RNG);
  8. @implementation RNG
  9. SYNTHESIZE_SINGLETON_FOR_CLASS(RNG);
  10. - (id) init
  11. {
  12. return [self initWithSeed:time(NULL)];
  13. }
  14. - (id) initWithSeed:(unsigned int) seedValueIn
  15. {
  16. if(nil != (self = [super init]))
  17. {
  18. self.seedValue = seedValueIn;
  19. }
  20. return self;
  21. }
  22. @synthesize seedValue;
  23. - (void) setSeedValue:(unsigned int) value
  24. {
  25. seedValue = value;
  26. srand(seedValue);
  27. }
  28. - (unsigned int) randomUnsignedInt
  29. {
  30. return rand();
  31. }
  32. - (double) randomProbability
  33. {
  34. return rand() / 2147483647.0;
  35. }
  36. - (int) randomNumberFrom: (int) minValue to: (int) maxValue
  37. {
  38. double probability = rand() / 2147483648.0;
  39. double range = maxValue - minValue + 1;
  40. return (int)(range * probability + minValue);
  41. }
  42. - (int) randomNumberFrom: (int) minValue to: (int) maxValue except:(int) exceptValue
  43. {
  44. if(minValue == maxValue)
  45. {
  46. return minValue;
  47. }
  48. int result;
  49. while(exceptValue == (result = [self randomNumberFrom:minValue to:maxValue]))
  50. {
  51. }
  52. return result;
  53. }
  54. - (bool) randomBool
  55. {
  56. return rand() & 1;
  57. }
  58. @end