random.alc 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. include "primitives.alh"
  2. include "utils.alh"
  3. Integer seed = 1
  4. Float function random():
  5. // Linear Congruential Generator
  6. Integer a
  7. Integer c
  8. Integer m
  9. // Parameters from Numerical Recipes
  10. a = 1664525
  11. c = 1013904223
  12. m = 4294967296
  13. // Do the generation and update the seed
  14. seed = integer_modulo(a * seed + c, m)
  15. // The seed is the new value
  16. return float_division(cast_float(seed), cast_float(m))!
  17. Integer function random_interval(a : Integer, b : Integer):
  18. if (a == b):
  19. return a!
  20. else:
  21. log("Random gives us: " + cast_value(random()))
  22. return cast_integer(random() * cast_float(b - a + 1) + cast_float(a))!
  23. Element function random_choice(list : Element):
  24. if (list_len(list) == 0):
  25. return read_root()!
  26. else:
  27. return list_read(list, random_interval(0, list_len(list) - 1))!
  28. String function random_string(length : Integer):
  29. String result
  30. Element chars
  31. chars = alphabet()
  32. result = ""
  33. while (string_len(result) < length):
  34. result = string_join(result, cast_string(random_choice(chars)))
  35. return result!