using System; using System.Collections.Generic; using System.Text; using Sunweaver.Commands.Attributes; namespace Sunweaver.Commands { [BasePair("Return a random value between 1 and the top value of the integer stack, inclusive. " + @"Preserves sign, eg: ""-3 rand"" produces values in [-1, -2, -3].")] public class rand : Abstracts.UnaryOperation { public override void Operation(long a) { long return_me = 0; ulong range = (ulong)Math.Abs(a); if (range > 0) { //Prevent a modulo bias; see http://stackoverflow.com/a/10984975/238419. ulong ulongRand; do { byte[] buf = new byte[8]; DNASystem.rand.NextBytes(buf); ulongRand = (ulong)BitConverter.ToInt64(buf, 0); } while (ulongRand >= ulong.MaxValue - ulong.MaxValue % range); return_me = (long)(ulongRand % range) + 1; } VM.Stack.Push(Math.Sign(a) * return_me); } } }