Code:
  while (%i <= %y) {
    if ($r(1,4) == 1) var %x = $r(a,z) 
    if ($r(1,4) == 2) var %x = $r(A,Z)
    if ($r(1,4) == 3) var %x = $r(0,9)
    if ($r(1,4) == 4) var %x = $r(a,Z)
    var %res = %res $+ %x
    inc %i
  }
Your code is picking a new random number for each if-random-number-is something-condition, thus it is "likely" (a 0.31 to 1 chance) that each if-condition is not met, and the "old" %x will be added to %res.
compare your code to:
Code:
  while (%i <= %y) {
  var %r = $r(1,4)
    if (%r == 1) var %x = $r(a,z) 
    elseif (%r == 2) var %x = $r(A,Z)
    elseif (%r == 3) var %x = $r(0,9)
    else var %x = $r(a,Z)
    var %res = %res $+ %x
    inc %i
  }