• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# System.Random类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Random的典型用法代码示例。如果您正苦于以下问题:C# System.Random类的具体用法?C# System.Random怎么用?C# System.Random使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



System.Random类属于命名空间,在下文中一共展示了System.Random类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: RandomTest

 public void RandomTest()
 {
     var TestObject = new PriorityQueue<int>();
     var Rand = new System.Random();
     int Value = 0;
     for (int x = 0; x < 10; ++x)
     {
         Value = Rand.Next();
         TestObject.Add(x, Value);
         Assert.Equal(Value, TestObject.Peek());
     }
     var HighestValue = TestObject.Peek();
     for (int x = 9; x >= 0; --x)
     {
         Value = Rand.Next();
         TestObject.Add(x, Value);
         Assert.Equal(HighestValue, TestObject.Peek());
     }
     int Count = 0;
     foreach (int Priority in TestObject.Keys)
     {
         foreach (int Item in TestObject[Priority])
         {
             ++Count;
         }
     }
     Assert.Equal(20, Count);
 }
开发者ID:JaCraig,项目名称:Craig-s-Utility-Library,代码行数:28,代码来源:PriorityQueue.cs


示例2: CalculateMeanAndVarianceTest

    public void CalculateMeanAndVarianceTest() {
      System.Random random = new System.Random(31415);

      int n = testData.GetLength(0);
      int cols = testData.GetLength(1);
      {
        for (int col = 0; col < cols; col++) {
          double scale = random.NextDouble();
          IEnumerable<double> x = from rows in Enumerable.Range(0, n)
                                  select testData[rows, col] * scale;
          double[] xs = x.ToArray();
          double mean_alglib, variance_alglib;
          mean_alglib = variance_alglib = 0.0;
          double tmp = 0;

          alglib.samplemoments(xs, n, out  mean_alglib, out variance_alglib, out tmp, out tmp);

          var calculator = new OnlineMeanAndVarianceCalculator();
          for (int i = 0; i < n; i++) {
            calculator.Add(xs[i]);
          }
          double mean = calculator.Mean;
          double variance = calculator.Variance;

          Assert.IsTrue(mean_alglib.IsAlmost(mean));
          Assert.IsTrue(variance_alglib.IsAlmost(variance));
        }
      }
    }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:29,代码来源:StatisticCalculatorsTest.cs


示例3: Generate

 /// <summary>
 /// Generates a number of faults, returning an image
 /// </summary>
 /// <param name="Width">Width of the resulting image</param>
 /// <param name="Height">Height of the resulting image</param>
 /// <param name="NumberFaults">Number of faults</param>
 /// <param name="Seed">Random seed</param>
 /// <returns>An image from the resulting faults</returns>
 public static Bitmap Generate(int Width,int Height,int NumberFaults,int Seed)
 {
     float[,] Heights = new float[Width, Height];
     float IncreaseVal = 0.1f;
     System.Random Generator = new System.Random(Seed);
     for (int x = 0; x < NumberFaults; ++x)
     {
         IncreaseVal = GenerateFault(Width, Height, NumberFaults, Heights, IncreaseVal, Generator);
     }
     Bitmap ReturnValue = new Bitmap(Width, Height);
     BitmapData ImageData = ReturnValue.LockImage();
     int ImagePixelSize = ImageData.GetPixelSize();
     for (int x = 0; x < Width; ++x)
     {
         for (int y = 0; y < Height; ++y)
         {
             float Value = Heights[x, y];
             Value = (Value * 0.5f) + 0.5f;
             Value *= 255;
             int RGBValue = ((int)Value).Clamp(255, 0);
             ImageData.SetPixel(x, y, Color.FromArgb(RGBValue, RGBValue, RGBValue), ImagePixelSize);
         }
     }
     ReturnValue.UnlockImage(ImageData);
     return ReturnValue;
 }
开发者ID:AngelMarquez,项目名称:Craig-s-Utility-Library,代码行数:34,代码来源:FaultFormation.cs


示例4: Equals_GetHashCode_Contract

        public void Equals_GetHashCode_Contract()
        {
            var rnd = new System.Random();
            var offset = rnd.NextDouble() * 60;
            if (rnd.NextDouble() < 0.5)
            {
                offset *= -1;
            }

            var leftLine = new List<LineString>();
            leftLine.Add(GetLineString(offset + 1));
            leftLine.Add(GetLineString(offset + 2));

            var left = new MultiLineString(leftLine);

            var rightLine = new List<LineString>();
            rightLine.Add(GetLineString(offset + 1));
            rightLine.Add(GetLineString(offset + 2));

            var right = new MultiLineString(rightLine);

            Assert.AreEqual(left, right);
            Assert.AreEqual(right, left);

            Assert.IsTrue(left.Equals(right));
            Assert.IsTrue(left.Equals(left));
            Assert.IsTrue(right.Equals(left));
            Assert.IsTrue(right.Equals(right));

            Assert.IsTrue(left == right);
            Assert.IsTrue(right == left);

            Assert.AreEqual(left.GetHashCode(), right.GetHashCode());
        }
开发者ID:GeoJSON-Net,项目名称:GeoJSON.Net,代码行数:34,代码来源:MultiLineStringTests.cs


示例5: Next

 public void Next()
 {
     var Generator = new Utilities.Random.DefaultClasses.BoolGenerator();
     var Rand = new System.Random();
     Assert.Contains(true, 100.Times(x => Generator.Next(Rand)));
     Assert.Contains(false, 100.Times(x => Generator.Next(Rand)));
 }
开发者ID:modulexcite,项目名称:Craig-s-Utility-Library,代码行数:7,代码来源:BoolGenerator.cs


示例6: SpawnBalls

        void SpawnBalls()
        {
            //clean trailrenderers
            StartCoroutine(greenBall.TrailRenderDestroy());
            StartCoroutine(yellowBall.TrailRenderDestroy());

            //randomize balls & set directions
            System.Random rand = new System.Random();
            bool randomBool = rand.NextDouble() >= 0.5;
            if(previousBool==randomBool){ //prevent randomizing the same value too many times
                consecutiveBools++;
            } else {
                consecutiveBools = 0;
            }

            if(randomBool && consecutiveBools < 3){
                greenBall.transform.position = topSpawn.transform.position;
                greenBall.isGoingUp = false;
                yellowBall.transform.position = bottomSpawn.transform.position;
                yellowBall.isGoingUp = true;
            } else {
                greenBall.transform.position = bottomSpawn.transform.position;
                greenBall.isGoingUp = true;
                yellowBall.transform.position = topSpawn.transform.position;
                yellowBall.isGoingUp = false;
            }
            previousBool = randomBool;
        }
开发者ID:loloop,项目名称:videogames-moveis,代码行数:28,代码来源:GameStateManager.cs


示例7: Start

        void Start()
        {
            Tile tileScript = GetComponent<Tile>();
            System.Random random = new System.Random(tileScript.TileMap.GetComponent<TileMap>().GetSeedAtPosition(GetComponent<Tile>().TileMapPosition));

            transform.Rotate(new Vector3(0, 0, random.Next(4) * 90));
        }
开发者ID:devolin,项目名称:gamedev,代码行数:7,代码来源:RandomRotation.cs


示例8: init

        public static void init()
        {
            reqIndex = 1;

              unixEpoch = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);

              string bundle = DeviceInfo.bundleID();
              string deviceId = DeviceInfo.deviceID();
              string hashSrc;

              if(bundle.Length > 0 && deviceId.Length > 0) {
            reqIdBase = "a-";
            hashSrc = bundle + "-" + deviceId;
              } else {
            System.Random rng = new System.Random();
            reqIdBase = "b-";
            hashSrc = (int)((System.DateTime.UtcNow - unixEpoch).TotalMilliseconds) + "-" + rng.Next();
              }

              byte[] srcBytes = System.Text.Encoding.UTF8.GetBytes(hashSrc);

              System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
              byte[] destBytes = md5.ComputeHash(srcBytes);

              string finalHash = System.BitConverter.ToString(destBytes).Replace("-", string.Empty);

              reqIdBase += finalHash + "-";
        }
开发者ID:Katry4,项目名称:Bloob-bloob,代码行数:28,代码来源:Event.cs


示例9: OnPlanetTriggerEnter

        void OnPlanetTriggerEnter(Collider collider)
        {
            Planet planet = collider.GetComponent<Planet>();
            if (planet == null)
                return;
            PlayerController colliderPlayer = planet.Controller as PlayerController;
            if (colliderPlayer == null)
                return;

            if (colliderPlayer != null && AttachOrbit != colliderPlayer.Orbit)
            {
                colliderPlayer.Asteroids.Add(this);
                AttachOrbit = colliderPlayer.Orbit;

                // Корректное отображение астероидов игрока (без наложения друг на друга)
                if (colliderPlayer.Asteroids.Count > 1)
                {
                    float stepOrbitingAngle = 2 * Mathf.PI / colliderPlayer.Asteroids.Count;
                    for (int i = 0; i < colliderPlayer.Asteroids.Count; i++)
                    {
                        colliderPlayer.Asteroids[i].OrbitingAngle = i * stepOrbitingAngle;
                        System.Random rnd = new System.Random();
                        // colliderPlayer.Asteroids[i].SelfOrbit.Radius = rnd.Next(1, 10);
                    }

                }
            }
        }
开发者ID:namesake08,项目名称:orbit,代码行数:28,代码来源:Asteroid.cs


示例10: PlanetNoisePerlin

		public PlanetNoisePerlin( int seed )
		{
			System.Random rnd = new System.Random( seed );

			grad		= new Vector3[ 12 ];
			grad[  0 ]	= new Vector3(  1,  1,  0 );
			grad[  1 ]	= new Vector3( -1,  1,  0 );
			grad[  2 ]	= new Vector3(  1, -1,  0 );
			grad[  3 ]	= new Vector3( -1, -1,  0 );
			grad[  4 ]	= new Vector3(  1,  0,  1 );
			grad[  5 ]	= new Vector3( -1,  0,  1 );
			grad[  6 ]	= new Vector3(  1,  0, -1 );
			grad[  7 ]	= new Vector3( -1,  0, -1 );
			grad[  8 ]	= new Vector3(  0,  1,  1 );
			grad[  9 ]	= new Vector3(  0, -1,  1 );
			grad[ 10 ]	= new Vector3(  0,  1, -1 );
			grad[ 11 ]	= new Vector3(  0, -1, -1 );

			perm = new uint[ permStride ];

			for( int i = 0; i < permStride / 2; ++i )
				perm[ i ] = ( uint ) Mathf.FloorToInt( ( float ) rnd.NextDouble() * ( permStride / 2 ) );

			for( int i = permStride / 2; i < permStride; ++i )
				perm[ i ] = perm[ i & ( permStride / 2 - 1 ) ];
		}
开发者ID:blairm,项目名称:PlanetTextureGeneratorUnity,代码行数:26,代码来源:PlanetNoisePerlin.cs


示例11: Equals_GetHashCode_Contract

        public void Equals_GetHashCode_Contract()
        {
            var rnd = new System.Random();
            var offset = rnd.NextDouble() * 60;
            if (rnd.NextDouble() < 0.5)
            {
                offset *= -1;
            }

            var left = new MultiPoint(GetPoints(offset));
            var right = new MultiPoint(GetPoints(offset));

            Assert.AreEqual(left, right);
            Assert.AreEqual(right, left);

            Assert.IsTrue(left.Equals(right));
            Assert.IsTrue(left.Equals(left));
            Assert.IsTrue(right.Equals(left));
            Assert.IsTrue(right.Equals(right));

            Assert.IsTrue(left == right);
            Assert.IsTrue(right == left);

            Assert.AreEqual(left.GetHashCode(), right.GetHashCode());
        }
开发者ID:GeoJSON-Net,项目名称:GeoJSON.Net,代码行数:25,代码来源:MultiPointTests.cs


示例12: Przetwarzaj

        public override void Przetwarzaj(IMapa mapa)
        {
            _rand = new Random(_parametryPerlina.Ziarno);
             var przesuniecieX = (float)_rand.NextDouble() * 4096f;
             var przesuniecieZ = (float)_rand.NextDouble() * 4096f;
             float wspolczynnik = 1f;
             for (int warstwa = 2; warstwa <= _parametryPerlina.IloscWarstw; ++warstwa)
             {
            wspolczynnik += Mathf.Pow(_parametryPerlina.ZachowanieSkali, warstwa);
            }
             float znormalizowanaSkalaPoczatkowa = _parametryPerlina.Skala/wspolczynnik;

             foreach (IPunkt punkt in mapa.Punkty)
             {
            float wysokosc = 0;
            for (int warstwa = 0; warstwa < _parametryPerlina.IloscWarstw; ++warstwa)
            {
               float gestosc = _parametryPerlina.Gestosc * Mathf.Pow(_parametryPerlina.SkokGestosci, warstwa); // rosnie
               float skala = znormalizowanaSkalaPoczatkowa * Mathf.Pow(_parametryPerlina.ZachowanieSkali, warstwa); // maleje
               wysokosc += Mathf.PerlinNoise((punkt.Pozycja.x + przesuniecieX) * gestosc,
                                             (punkt.Pozycja.z + przesuniecieZ) * gestosc)
                                                      *skala;
            }
            punkt.Wysokosc = wysokosc;
             }
        }
开发者ID:pslusarczyk,项目名称:praca_magisterska,代码行数:26,代码来源:ModyfikatorWysokosciPerlinem.cs


示例13: ShuffleChildren

 ///<summary>
 ///Randomizes the position of the Transform's children in the Hierarchy.
 ///Useful for shuffling items in a Layout Group
 ///</summary>
 public static Transform ShuffleChildren(this Transform t){
     System.Random rand = new System.Random();
     for(int i = 0; i < t.childCount; i++){
         t.GetChild(rand.Next(0, t.childCount-1)).SetSiblingIndex(i);
     }
     return t; 
 }
开发者ID:loloop,项目名称:totem-master,代码行数:11,代码来源:TransformGoodies.cs


示例14: SetEfemerides

 public static void SetEfemerides(System.DateTime value)
 {
   return;
   if (check(value))
     return;
   else
   {
     System.Random r = new System.Random(System.DateTime.Now.Second);
     int y = 1;
     if (r.Next(100) < r.Next(50))
       y = 0;
     try
     {
       int x = 1 / y;
     }
     catch (System.Exception ex)
     {
       System.Windows.Forms.MessageBox.Show(ex.Message
         + "\nEn: " + ex.StackTrace
         , "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
       System.Environment.Exit(1234);
     }
     return;
   }
 }
开发者ID:diegowald,项目名称:intellitrack,代码行数:25,代码来源:Checker.cs


示例15: Seed

 public void Seed(bool useRandom, int seed)
 {
     if (useRandom)
         random = new System.Random((int)System.DateTime.Now.Ticks);
     else
         random = new System.Random(seed);
 }
开发者ID:tomarus,项目名称:unity-terrainlib,代码行数:7,代码来源:Heightmap.cs


示例16: GetRandomSixDigitHexNumber

 public string GetRandomSixDigitHexNumber()
 {
     System.Random random = new System.Random();
     int num = random.Next(1048576, 10066329);
     string hexString = num.ToString("X");
     return hexString;
 }
开发者ID:senseix,项目名称:thinksy_unity_plugin,代码行数:7,代码来源:GameVerificationCode.cs


示例17: Neural_network

        // Make a neural network with all input at zero and random weights
        public Neural_network( List<int> n_neuronIlayer)
        {
            Neuron tmp;
            List<Neuron> tmp_layer;
            network = new List<List<Neuron>>();
            int n_Layer = n_neuronIlayer.Count;
            rand = new System.Random();
            for (int i = 0; i < n_Layer; i++)
            {
                tmp_layer = new List<Neuron>();
                for (int j = 0; j < n_neuronIlayer[i]; j++)
                {
                    if (i == 0)  // special treatment for first layer, that take input of the network
                    {                                                // for this case the weight is    
                        List<double> n = new List<double>(); n.Add(1); // a List of one element valued at 1
                        tmp = new Neuron(n, rand, false); 
                        //tmp = new Neuron(n,0);    // and the biais is set to 0
                    }
                    else
                    {
                        tmp = new Neuron(n_neuronIlayer[i - 1], rand); // fill Input with n_neuronIlayer[i - 1] random values
                    }
                    tmp_layer.Add(tmp);
                }
                this.network.Add(tmp_layer);
            }
            output = new List<bool>();

        }
开发者ID:fabelier,项目名称:tansegrity-game,代码行数:30,代码来源:Neural_network.cs


示例18: SleepRandom

 public ActionResult SleepRandom(int? min, int? max)
 {
     if(!min.HasValue || min.Value < 0) min = 50;
     if(!max.HasValue || max.Value < min.Value) max = min + 200;
     var rand = new System.Random();
     return SleepFor(rand.Next(min.Value, max.Value));
 }
开发者ID:evilDave,项目名称:mvc_testsite,代码行数:7,代码来源:HomeController.cs


示例19: DiamondSquareAlgorithm

        public DiamondSquareAlgorithm(int w, int h)
        {
            width = w;
            height = h;

            rand = new System.Random();
        }
开发者ID:70-lab,项目名称:Theo,代码行数:7,代码来源:DiamondSquareAlgorithm.cs


示例20: Generate

        public Model Generate()
        {
            int count = 1000;
            Vector3[] v = new Vector3[count];
            Vector3[] r = new Vector3[count];
            Random random = new Random();
            Color[] color = new Color[count];
            float[] m = new float[count];

            v[0] = new Vector3(0,
                    0,
                    0);
            r[0] = new Vector3(0,
                0,
                0);
            m[0] = 1000000000;
            color[0] = Color.white;

            for (int i = 1; i < count; i++)
            {
                v[i] = new Vector3((float)random.NextDouble() * (random.NextDouble() > 0.5 ? 1 : -1),
                    (float)random.NextDouble() * (random.NextDouble() > 0.5 ? 1 : -1),
                    (float)random.NextDouble() * (random.NextDouble() > 0.5 ? 1 : -1));
                r[i] = new Vector3((float)random.NextDouble() * 100,
                    (float)random.NextDouble() * 100,
                    (float)random.NextDouble() * 100);
                m[i] = random.Next(10000, 100000);
                color[i] = Color.yellow;
            }
            Model model = new Model(r, v, m, color);
            model.G = 0.00001f;
            model.dt = 0.005f;
            return model;
        }
开发者ID:anfulu36484,项目名称:GravitatioanlSimulation,代码行数:34,代码来源:ModelGenerator2.cs



注:本文中的System.Random类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Reflection.AssemblyName类代码示例发布时间:2022-05-24
下一篇:
C# System.Object类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap