; DICE TESTER

; this programs tests a random die generator (values 1 to 6)
; it builds an histogram of the repartition

; registers 1 to 6 accumulate the dice values

; your die generator must be programmed at "dice:" label, it can use the whole
; stack, registers b to e and must return an integer from 1 to 6.

; INPUT: the number of dice you want, RST, RUN
; OUTPUT: a six digits number representing the frequency of each value (6 to 1)
;         digit 9 for a high frequency, digit 0 for a low frequency.
;         If then you exchange X and Y you are reminded of the number of dice desired

; example: 999621 means that values 6,5,4 are frequent, but that 3,2,1 are rare
;          999999 means that your generator is very well balanced
;          909090 means that you only get even values and never 5,3,1 !!


#c3 2		; generate C3 file

#reg 0 n		; for loops and indirect indexing
#reg 7 nsave		; number of dice
#reg 8 ptr		; pointer 
#reg 9 histogram
#reg a maxval

DO
  =nsave		; number of dice
  7 =n			; will loop from 6 to 1
  REPEAT
    1 =(n)		; dec n and DIE(n)=1 (because of the MAX bug)
    @n -		; until n=1
  UNTIL(x=0)

  @nsave =n		; back to number of dice
  For n
     Gosub dice		; one value from the generator
     =ptr		; becomes a pointer
     1 sum (ptr)	; increment DIE(ptr)
  Next
  
  7 =n			; loop from 6 to 1
  1 =maxval		; maxvalue at the lowest possible
  REPEAT
    @maxval @(n) max	; maxval will be max(DIE(n))
    =maxval
    @n 1 -
  UNTIL(x=0)
  
  7 =n			; loop from 6 to 1
  0 =histogram		; histogram empty
  REPEAT
    @histogram
    @(n) 1 - @maxval /	; [DIE(n)-1]/max -> value from 0 to 0.9xx
    +			; added to histogram
    $10 * INT		; shift number to left and keep new digit
    =histogram
    @n 1 -
  UNTIL(x=0)
  @nsave
  @histogram
  STOP
LOOP

dice:
5 @e PI + x^y frac =e	; one possible generator seed=frac((seed+PI)^5)
6 * 1 + int
RTN

; with this generator, starting with seed e=0 and n=100 dice,
; I get 634966 (not so good) -> the histogram would be this:

;       *
;       *
;       *
; *     * * *
; *     * * *
; *   * * * *
; * * * * * *
; * * * * * *
; * * * * * *
;--------------
; 6 5 4 3 2 1

; if I just ask for 100 more dice, I get 698989, much better !
; it took 15 min 45 sec for a 100 dice run...

;   *   *   *
;   * * * * *
;   * * * * *
; * * * * * *
; * * * * * *
; * * * * * *
; * * * * * *
; * * * * * *
; * * * * * *
;--------------
; 6 5 4 3 2 1