public void Setup()
 {
     rng = new PcgRandom();
     Console.WriteLine($"Setup with value {ValueToDivideBy}");
     divisorBranching = new UInt32Divisor(ValueToDivideBy);
     divisorOld       = new OldDivisor(ValueToDivideBy);
 }
Exemple #2
0
        public static void LoadGame()
        {
            if (!File.Exists(Constants.SAVE_FILE))
            {
                NewGame();
            }

            System.Diagnostics.Debug.WriteLine("Reading saved file");
            try
            {
                using (Stream saveFile = File.OpenRead(Constants.SAVE_FILE))
                {
                    BinaryFormatter deserializer = new BinaryFormatter();
                    World = (WorldHandler)deserializer.Deserialize(saveFile);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Load failed: {ex.Message}");
                NewGame();
            }

            // TODO: restore rng to saved position
            Random       = new PcgRandom(Option.FixedSeed ? Option.Seed : (int)DateTime.Now.Ticks);
            VisualRandom = new PcgRandom(Random.Next());
            StateHandler.Reset();
        }
Exemple #3
0
        public void Reseed()
        {
            Assert.Equal((int)(TestValues[0] % int.MaxValue), _rng.Next());

            _rng = new PcgRandom(42);
            Assert.Equal((int)(TestValues[0] % int.MaxValue), _rng.Next());
        }
        public static int NextBinomial(this PcgRandom rand, int n, double p)
        {
            if (n <= 30)
            {
                // Run Bernouilli samples for small n.
                int successes = 0;
                for (int i = 0; i < n; i++)
                {
                    if (rand.NextDouble() < p)
                    {
                        successes++;
                    }
                }

                return(successes);
            }
            else
            {
                // Approximate with the normal distribution for large n.
                int normal = (int)rand.NextNormal(n * p, n * p * (1 - p));
                if (normal < 0)
                {
                    return(0);
                }
                else if (normal > n)
                {
                    return(n);
                }
                else
                {
                    return(normal);
                }
            }
        }
        public static double NextGamma(this PcgRandom rand, double a, double b)
        {
            // Marsaliga and Tsang - assumes a > 0
            if (a < 1)
            {
                return(rand.NextGamma(1.0 + a, b) * Math.Pow(rand.NextDouble(), 1.0 / a));
            }

            double d = a - 1.0 / 3.0;
            double c = 1.0 / Math.Sqrt(9.0 * d);
            double z, u, v;

            do
            {
                do
                {
                    z = rand.NextNormal(0, 1.0);
                    v = 1.0 + c * z;
                }while (v <= 0);

                v = v * v * v;
                u = rand.NextDouble();

                if (u < 1 - 0.0331 * z * z * z * z)
                {
                    break;
                }
            }while (Math.Log(u) >= 0.5 * z * z + d * (1 - v + Math.Log(v)));

            return(d * v / b);
        }
Exemple #6
0
 public LognormalDistribution(SimSharp.Simulation environment, double mean, double std, int seed)
 {
     _environment = environment;
     _rng         = new PcgRandom(seed);
     Mean         = mean;
     StdDev       = std;
 }
Exemple #7
0
        //주어진 필드의 크기와 지뢰 갯수로 필드 생성
        public void InitMineField(int width = ConstantsPack.minWidthCells, int height = ConstantsPack.minHeightCells, int mines = ConstantsPack.minMines)
        {
            fieldState      = ConstantsPack.gameState.gameState_Init;
            fieldWidth      = width; fieldHeight = height; fieldMines = mines;
            remainSafeCells = (fieldWidth * fieldHeight) - fieldMines;
            fieldGrid       = new FieldCell[fieldHeight, fieldWidth];

            PcgRandom randObj = new PcgRandom();

            //주어진 지뢰 갯수로 필드에 지뢰를 임의로 배치시킨다.
            int remainMines = fieldMines;

            while (remainMines > 0)
            {
                int setX = randObj.Next(0, fieldWidth);
                int setY = randObj.Next(0, fieldHeight);

                if (fieldGrid[setY, setX].openValue == (sbyte)ConstantsPack.openCellValue.cellValue_mine)
                {
                    continue;
                }

                fieldGrid[setY, setX].openValue = (sbyte)ConstantsPack.openCellValue.cellValue_mine;
                remainMines--;
            }

            //배치가 끝나면 빈 칸들을 탐색하여 주변 지뢰가 있으면 그 갯수를 체크한다.
            int x = 0, y = 0, k = 0;

            for (y = 0; y < fieldHeight; ++y)
            {
                for (x = 0; x < fieldWidth; ++x)
                {
                    FieldCell curCell = fieldGrid[y, x];
                    if (curCell.openValue == (sbyte)ConstantsPack.openCellValue.cellValue_blank)
                    {
                        //빈 칸 주변 8셀에 지뢰가 있는지 체크하여 카운팅
                        sbyte totalAdjMines = 0;
                        for (k = 0; k < 8; ++k)
                        {
                            int adjX = x + adjDx[k], adjY = y + adjDy[k];
                            if (!CellRangeCheck(adjX, adjY))
                            {
                                continue;
                            }
                            if (fieldGrid[adjY, adjX].openValue == (sbyte)ConstantsPack.openCellValue.cellValue_mine)
                            {
                                totalAdjMines++;
                            }
                        }
                        //카운팅된 값을 셀에 대입
                        fieldGrid[y, x].openValue = totalAdjMines;
                    }
                }
            }

            //필드 생성 끝나면 인게임 상태로 전환
            fieldState = ConstantsPack.gameState.gameState_InGame;
        } //InitMineField 함수 끝
Exemple #8
0
 protected MapGenerator(int width, int height, IEnumerable <LevelId> exits, PcgRandom random)
 {
     Width  = width;
     Height = height;
     Exits  = exits;
     Rand   = random;
     Map    = new MapHandler(width, height);
 }
Exemple #9
0
 public TriangularDistribution(SimSharp.Simulation environment, double low, double high, double mode, int seed)
 {
     _environment = environment;
     _rng         = new PcgRandom(seed);
     Low          = low;
     High         = high;
     Mode         = mode;
 }
        public static double NextNormal(this PcgRandom rand, double mean, double variance)
        {
            // Box-Muller transform
            double u1            = 1.0 - rand.NextDouble();
            double u2            = 1.0 - rand.NextDouble();
            double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2);

            return(mean + (Math.Sqrt(variance) * randStdNormal));
        }
Exemple #11
0
        private void InitializeWorldState()
        {
            var rand     = new Random(settings.Seed);
            var initRand = new PcgRandom(rand.Next());

            craneRNG      = new PcgRandom(rand.Next());
            productionRNG = new PcgRandom(rand.Next());
            handoverRNG   = new PcgRandom(rand.Next());
            readyRNG      = new PcgRandom(rand.Next());
            var capacity = World.Buffers.Sum(x => x.MaxHeight);
            var past     = sim.Now;

            for (var i = 0; i < settings.InitialNumberOfBlocks; i++)
            {
                past -= sim.RandLogNormal2(initRand, settings.ArrivalTimeMean, settings.ArrivalTimeStd);
                var b = new Block()
                {
                    Id      = ++blockIds,
                    Release = ToTimeStamp(past),
                    Ready   = false,
                    Due     = ToTimeStamp(past + sim.RandLogNormal2(initRand, settings.DueTimeMean, settings.DueTimeStd))
                };
                while (b.Due < ToTimeStamp(sim.Now + settings.DueTimeMin))
                {
                    b.Due += sim.RandLogNormal2(initRand, settings.DueTimeMean, settings.DueTimeStd);
                }
                var readyFactor = settings.ReadyFactorMin + initRand.NextDouble() * (settings.ReadyFactorMax - settings.ReadyFactorMin);
                b.Ready = (b.Release + TimeSpan.FromSeconds(readyFactor * (b.Due - b.Release).TotalSeconds)) < Now;

                var possibleBuffers = World.Buffers.Where(x => x.BottomToTop.Count < x.MaxHeight).ToList();
                var buf             = possibleBuffers[initRand.Next(possibleBuffers.Count)];
                if (buf.BottomToTop.Count == 0)
                {
                    buf.BottomToTop.Add(b);
                }
                else
                {
                    buf.BottomToTop.Insert(0, b);
                }

                sim.Process(BlockProcess(b, suppressEvent: true));
            }
            BufferUtilization.UpdateTo(World.Buffers.Sum(x => x.Height) / (double)World.Buffers.Sum(x => x.MaxHeight));
            World.KPIs.BufferUtilizationMean = BufferUtilization.Mean;
            World.Production.BottomToTop.Add(new Block()
            {
                Id      = ++blockIds,
                Release = ToTimeStamp(sim.Now),
                Ready   = false,
                Due     = ToTimeStamp(sim.Now + sim.RandLogNormal2(initRand, settings.DueTimeMean, settings.DueTimeStd))
            });
            World.Handover.Ready = true;
            sim.Process(BlockProcess(World.Production.BottomToTop.Single(), suppressEvent: true));
            sim.Process(WorldUpdates());
        }
Exemple #12
0
        public void PcgReproducibilityTest()
        {
            var pcg = new PcgRandom(15);
            var seq = Enumerable.Range(0, 1000).Select(x => pcg.Next()).ToArray();

            Thread.Sleep(100);
            pcg = new PcgRandom(15);
            var seq2 = Enumerable.Range(0, 1000).Select(x => pcg.Next()).ToArray();

            Assert.Equal(seq, seq2);
        }
Exemple #13
0
        public void MulHiEqualsUnsigned()
        {
            var rng = new PcgRandom();

            for (ulong i = 0; i < RandomTestCount; i++)
            {
                var a = rng.Next();
                var b = rng.Next();
                Assert.AreEqual(MultiplyHigh32(a, b), MultiplyHighCustom32(a, b), $"Testing {a} * {b}");
            }
        }
Exemple #14
0
        private ulong Random64(PcgRandom gen)
        {
            var int1 = (ulong)gen.Next();
            var int2 = (ulong)gen.Next();

            ulong result = int1 << 32;

            result += int2;

            return(result);
        }
Exemple #15
0
        public void CorrectlyDividesRandomNumerators(long divisor)
        {
            var int64Divisor = new Int64Divisor(divisor);
            var rng          = new PcgRandom();

            for (ulong i = 0; i < RandomTestCount; i++)
            {
                var testDividend = unchecked (rng.Next() | ((long)rng.Next() << 32));
                var quotient     = testDividend / int64Divisor;
                Assert.AreEqual(testDividend / divisor, quotient, $"Trying to test {testDividend} / {divisor}");
            }
        }
        public void CorrectlyDividesRandomNumerators(uint divisor)
        {
            var uInt32Divisor = new UInt32Divisor(divisor);
            var rng           = new PcgRandom();

            for (ulong i = 0; i < RandomTestCount; i++)
            {
                var testDividend = rng.Next();
                var quotient     = testDividend / uInt32Divisor;
                Assert.AreEqual(testDividend / divisor, quotient, $"Trying to test {testDividend} / {divisor}");
            }
        }
Exemple #17
0
        public void CalculatesAbsFloorCorrectlyRandomNumerators(long divisor)
        {
            var int64Divisor = new Int64Divisor(divisor);
            var rng          = new PcgRandom();

            for (ulong i = 0; i < RandomTestCount; i++)
            {
                var testDividend = unchecked (rng.Next() | ((long)rng.Next() << 32));
                var rounded      = int64Divisor.AbsFloor(testDividend);
                Assert.AreEqual(testDividend / divisor * divisor, rounded, $"Trying to test {testDividend} / {divisor} * {divisor}");
            }
        }
Exemple #18
0
        public void CalculatesModulusCorrectlyRandomNumerators(long divisor)
        {
            var int64Divisor = new Int64Divisor(divisor);
            var rng          = new PcgRandom();

            for (ulong i = 0; i < RandomTestCount; i++)
            {
                var testDividend = unchecked (rng.Next() | ((long)rng.Next() << 32));
                var remainder    = testDividend % int64Divisor;
                Assert.AreEqual(testDividend % divisor, remainder, $"Trying to test {testDividend} % {divisor}");
            }
        }
        public void CalculatesModulusCorrectlyRandomNumerators(uint divisor)
        {
            var uInt32Divisor = new UInt32Divisor(divisor);
            var rng           = new PcgRandom();

            for (ulong i = 0; i < RandomTestCount; i++)
            {
                var testDividend = rng.Next();
                var remainder    = testDividend % uInt32Divisor;
                Assert.AreEqual(testDividend % divisor, remainder, $"Trying to test {testDividend} % {divisor}");
            }
        }
        public void CalculatesFloorCorrectlyRandomNumerators(uint divisor)
        {
            var uInt32Divisor = new UInt32Divisor(divisor);
            var rng           = new PcgRandom();

            for (ulong i = 0; i < RandomTestCount; i++)
            {
                var testDividend = rng.Next();
                var rounded      = uInt32Divisor.Floor(testDividend);
                Assert.AreEqual(testDividend / divisor * divisor, rounded, $"Trying to test {testDividend} / {divisor} * {divisor}");
            }
        }
Exemple #21
0
        public void DivRemReturnsCorrectlyRandomNumerators(long divisor)
        {
            var int64Divisor = new Int64Divisor(divisor);
            var rng          = new PcgRandom();

            for (ulong i = 0; i < RandomTestCount; i++)
            {
                var testDividend = unchecked (rng.Next() | ((long)rng.Next() << 32));
                var remainder    = int64Divisor.DivRem(testDividend, out var quotient);
                Assert.AreEqual(testDividend % divisor, remainder, $"Trying to test {testDividend} % {divisor}");
                Assert.AreEqual(testDividend / divisor, quotient, $"Trying to test {testDividend} / {divisor}");
            }
        }
Exemple #22
0
        public void CalculatesAbsFloorRemCorrectlyRandomNumerators(int divisor)
        {
            var int32Divisor = new Int32Divisor(divisor);
            var rng          = new PcgRandom();

            for (ulong i = 0; i < RandomTestCount; i++)
            {
                var testDividend = unchecked ((int)rng.Next());
                var remainder    = int32Divisor.AbsFloorRem(testDividend, out var rounded);
                Assert.AreEqual(testDividend % divisor, remainder, $"Trying to test {testDividend} % {divisor}");
                Assert.AreEqual(testDividend / divisor * divisor, rounded, $"Trying to test {testDividend} / {divisor} * {divisor}");
            }
        }
Exemple #23
0
        public static Option <T> Random <T>(this IEnumerable <T> enumerable, PcgRandom rand)
        {
            var list = enumerable.ToList();

            if (list.Count == 0)
            {
                return(Option.None <T>());
            }
            else
            {
                return(Option.Some(list[rand.Next(list.Count)]));
            }
        }
        public void DivRemReturnsCorrectlyRandomNumerators(uint divisor)
        {
            var uInt32Divisor = new UInt32Divisor(divisor);
            var rng           = new PcgRandom();

            for (ulong i = 0; i < RandomTestCount; i++)
            {
                var testDividend = rng.Next();
                var remainder    = uInt32Divisor.DivRem(testDividend, out var quotient);
                Assert.AreEqual(testDividend % divisor, remainder, $"Trying to test {testDividend} % {divisor}");
                Assert.AreEqual(testDividend / divisor, quotient, $"Trying to test {testDividend} / {divisor}");
            }
        }
        public void CalculatesFloorRemCorrectlyRandomNumerators(ulong divisor)
        {
            var uInt64Divisor = new UInt64Divisor(divisor);
            var rng           = new PcgRandom();

            for (ulong i = 0; i < RandomTestCount; i++)
            {
                var testDividend = rng.Next() | ((ulong)rng.Next() << 32);
                var remainder    = uInt64Divisor.FloorRem(testDividend, out var rounded);
                Assert.AreEqual(testDividend % divisor, remainder, $"Trying to test {testDividend} % {SerializeDivisor(uInt64Divisor)}");
                Assert.AreEqual(testDividend / divisor * divisor, rounded, $"Trying to test {testDividend} / {SerializeDivisor(uInt64Divisor)} * {SerializeDivisor(uInt64Divisor)}");
            }
        }
Exemple #26
0
        public override void LoadContent(InitState state)
        {
            base.LoadContent(state);

            ScreenSize   = new Point(renderTarget.Width, renderTarget.Height);
            State        = GameState.GameOver;
            Random       = new PcgRandom(new Random().Next());
            score1       = score2 = 0;
            ScoreText1   = ScoreText2 = "Score: 0";
            ballSize     = 6;
            ballSize2    = ballSize * 0.5f;
            paddleSize   = new Point(8, 32);
            paddleSize2  = new Vector2(paddleSize.X * 0.5f, paddleSize.Y * 0.5f);
            paddleSpeed  = 3;
            paddleIndent = 4;
            GameScreenY  = 16;
            velInc       = 0.2f;
            cpu1         = cpu2 = true;
        }
Exemple #27
0
        public override void LoadContent(InitState state)
        {
            base.LoadContent(state);
            renderer = (TotalRoboRenderer)Renderer;

            // todo - create rendertarget 304x255
            ScreenSize = new Point(renderTarget.Width, renderTarget.Height);

            State               = GameState.GameOver;
            Random              = new PcgRandom(new Random().Next());
            wave                = 0;
            score               = 0;
            ScoreText           = "0";
            entityData          = new EntityData[(int)EntityType.zLast];
            entityData[1].Speed = 1;
            entityData[2].Speed = 6;
            entityData[3].Speed = 0.3f;

            Entities         = new Entity[100];
            Entities[0].Type = EntityType.Player;
        }
Exemple #28
0
        public static void NewGame()
        {
            Random       = new PcgRandom(Option.FixedSeed ? Option.Seed : (int)DateTime.Now.Ticks);
            VisualRandom = new PcgRandom(Random.Next());

            Player = new Player(new ActorParameters("Player")
            {
                Awareness = 10,
                MaxHp     = 100,
                MaxSp     = 50
            });

            StateHandler.Reset();
            MessageHandler.Clear();
            EventScheduler.Clear();
            Overlay.Clear();
            Threatened.Clear();
            Animations.Clear();

            WorldParameter worldParameter = Program.LoadData <WorldParameter>("world");

            World = new WorldHandler(worldParameter);
            World.Initialize();
        }
Exemple #29
0
 internal static void SetRandomState(uint state)
 {
     s_Random = new PcgRandom(state);
 }
Exemple #30
0
 public BspMapGenerator(int width, int height, IEnumerable <LevelId> exits, PcgRandom random)
     : base(width, height, exits, random)
 {
 }