random.alc 983 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. return cast_integer(random() * cast_float(b - a + 1) + cast_float(a))!
  22. Element function random_choice(list : Element):
  23. if (list_len(list) == 0):
  24. return read_root()!
  25. else:
  26. return list_read(list, random_interval(0, list_len(list) - 1))!
  27. String function random_string(length : Integer):
  28. String result
  29. Element chars
  30. chars = alphabet()
  31. result = ""
  32. while (string_len(result) < length):
  33. result = string_join(result, cast_string(random_choice(chars)))
  34. return result!