C# (CSharp) Класс System. Random Code Examples

C# (CSharp) System.Random - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для класса System.Random, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
Пример #1
0
 static void Main(string[] args)
 {
     int num = 10;
     var matrix = new int[num, num];
     Console.WriteLine("Before : ");
     for (int i = 0; i < num; ++i)
     {
         for (int j = 0; j < num; ++j)
         {
             Random rand = new Random();
             matrix[i, j] = -i + j + rand.Next(0, 80);
             Console.Write(matrix[i, j]);
             Console.Write(' ');
         }
         Console.WriteLine();
     }
     Console.WriteLine("After : ");
     matrix = BubbleSort(matrix, num);
     for (int i = 0; i < num; ++i)
     {
         for (int j = 0; j < num; ++j)
         {
             Console.Write(matrix[i, j]);
             Console.Write(' ');
         }
         Console.WriteLine();
     }
     Console.ReadKey();
 }
Пример #2
0
        protected void LinkButton3_Click(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AppendHeader("Content-encoding", "");

            Random random = new Random();
            imgCaptcha.ImageUrl = imgCaptcha.ImageUrl + "?" + random.ToString();
        }
Пример #3
0
	public void GetReady ()
	{
		dataTable = new DataTable ("itemTable");
		dc1 = new DataColumn ("itemId");
		dc2 = new DataColumn ("itemName");
		dc3 = new DataColumn ("itemPrice");
		dc4 = new DataColumn ("itemCategory");
		
		dataTable.Columns.Add (dc1);
		dataTable.Columns.Add (dc2);
		dataTable.Columns.Add (dc3);
		dataTable.Columns.Add (dc4);
		DataRow dr;
		seed = 123;
		rowCount = 5;
		rndm = new Random (seed);
		for (int i = 1; i <= rowCount; i++) {
			dr = dataTable.NewRow ();
			dr["itemId"] = "item " + i;
			dr["itemName"] = "name " + rndm.Next ();
			dr["itemPrice"] = "Rs. " + (rndm.Next () % 1000);
			dr["itemCategory"] = "Cat " + ((rndm.Next () % 10) + 1);
			dataTable.Rows.Add (dr);
		}
		dataTable.AcceptChanges ();
		dataView = new DataView (dataTable);
		dataView.ListChanged += new ListChangedEventHandler (OnListChanged);
		listChangedArgs = null;
	}
        public void TestConcurrentQueueDeclare()
        {
            string x = GenerateExchangeName();
            Random rnd = new Random();

            List<Thread> ts = new List<Thread>();
            System.NotSupportedException nse = null;
            for(int i = 0; i < 256; i++)
            {
                Thread t = new Thread(() =>
                        {
                            try
                            {
                                // sleep for a random amount of time to increase the chances
                                // of thread interleaving. MK.
                                Thread.Sleep(rnd.Next(5, 500));
                                Model.ExchangeDeclare(x, "fanout", false, false, null);
                            } catch (System.NotSupportedException e)
                            {
                                nse = e;
                            }
                        });
                ts.Add(t);
                t.Start();
            }

            foreach (Thread t in ts)
            {
                t.Join();
            }

            Assert.IsNotNull(nse);
            Model.ExchangeDelete(x);
        }
Пример #5
0
		public void Initialise()
		{
			_primitives = new List<Cube>();
			var random = new Random();
			for (int i = 0; i < Constants.CubeCount; i++)
			{
				_primitives.Add(new Cube
					{
						Color = Color.Red,
						Position = new Vector3(random.Next(100) - 50, random.Next(100) - 50, -random.Next(100)),
						Radius = random.Next(100),
						Rotation = Vector3.Zero
					});
			}
            //How to create a kernel and a channel?
//			_kernel = 
//		    _channel = 

			

			_colour = Color.Beige;
			
			_kernel.Factory.NewCoroutine(ChangePosition);
			_kernel.Factory.NewCoroutine(ChangeColour);
		    
		}
Пример #6
0
        /// <summary>
        /// Submatrix expression operations
        /// </summary>
        private void RowColOperation()
        {
            Mat src = Cv2.ImRead(FilePath.Image.Lenna);

            Random rand = new Random();
            for (int i = 0; i < 200; i++)
            {
                int c1 = rand.Next(100, 400);
                int c2 = rand.Next(100, 400);
                Mat temp = src.Row[c1];
                src.Row[c1] = src.Row[c2];
                src.Row[c2] = temp;
            }

            src.Col[0, 50] = ~src.Col[450, 500];
            
            // set constant value (not recommended)
            src.Row[450,460] = src.Row[450,460] * 0 + new Scalar(0,0,255);
            // recommended way
            //src.RowRange(450, 460).SetTo(new Scalar(0, 0, 255));

            using (new Window("RowColOperation", src))
            {
                Cv2.WaitKey();
            }
        }
 /// <summary>
 ///   Initializes the strategy with the specified nodes and cluster configuration
 /// </summary>
 /// <param name="nodes"> The nodes. </param>
 /// <param name="config"> The config. </param>
 public ExclusiveConnectionStrategy(Ring nodes, ClusterConfig config)
 {
     _nodes = nodes;
     _config = config;
     _connections = new ConcurrentStack<Connection>();
     _rndGen = new Random((int)DateTime.Now.Ticks);
 }
Пример #8
0
        public void RandomDatagramTest()
        {
            Random random = new Random();

            for (int i = 0; i != 1000; ++i)
            {
                Datagram datagram = random.NextDatagram(random.Next(1024));

                Assert.AreEqual(datagram, new Datagram(new List<byte>(datagram).ToArray()));
                Assert.AreEqual(datagram.GetHashCode(), new Datagram(new List<byte>(datagram).ToArray()).GetHashCode());

                Assert.AreNotEqual(datagram, random.NextDatagram(random.Next(10 * 1024)));
                Assert.AreNotEqual(datagram.GetHashCode(), random.NextDatagram(random.Next(10 * 1024)).GetHashCode());

                if (datagram.Length != 0)
                {
                    Assert.AreNotEqual(datagram, Datagram.Empty);
                    Assert.AreNotEqual(datagram, random.NextDatagram(datagram.Length));
                    if (datagram.Length > 2)
                        Assert.AreNotEqual(datagram.GetHashCode(), random.NextDatagram(datagram.Length).GetHashCode());
                }
                else
                    Assert.AreEqual(datagram, Datagram.Empty);

                // Check Enumerable
                IEnumerable enumerable = datagram;
                int offset = 0;
                foreach (byte b in enumerable)
                    Assert.AreEqual(datagram[offset++], b);
            }
        }
        public void TestPriorityQueue()
        {
            int operationsCount = 100000;

            Random rand = new Random(0);

            PriorityQueue<double> queue = new PriorityQueue<double>();

            for (int op = 0; op < operationsCount; ++op)
            {
                int opType = rand.Next(0, 2);

                if (opType == 0) // Enqueue
                {
                    double item = (100.0 - 1.0) * rand.NextDouble() + 1.0;
                    queue.Enqueue(item);

                    Assert.IsTrue(queue.IsConsistent(), "Test fails after enqueue operation # " + op);
                }
                else // Dequeue
                {
                    if (queue.Count > 0)
                    {
                        double item = queue.Dequeue();
                        Assert.IsTrue(queue.IsConsistent(), "Test fails after dequeue operation # " + op);
                    }
                }
            }
        }
Пример #10
0
        private void btnAddPID_Click(object sender, EventArgs e)
        {
            if (tbPID.EditValue == null || tbPID.EditValue.ToString().Trim() == string.Empty)
            {
                return;
            }
            if (!dxvp.Validate(ccbProxy))
                return;
            string[] PIDs = tbPID.EditValue.ToString().Split('\n');
            string[] proxies = ccbProxy.EditValue.ToString().Split(',');
            Random rnd = new Random();
            foreach (string pid in PIDs)
            {
                if (pid.Trim() == string.Empty)
                   continue;
                _flagList.Add(new Datasource.FlagUnit("", 0, "", pid.Trim(), "Unknown", "Unknown"));
                foreach (string proxy in proxies)
                {
                    int id = rnd.Next(0, dsData.UserAgent.Count);
                    Datasource.FlagUnit data = new Datasource.FlagUnit(proxy, dsData.UserAgent[id].UserAgentId, dsData.UserAgent[id].UserAgentName, pid.Trim(), "Unknown", "Unknown");
                    _flagQue.Enqueue(data);
                    gridControlPID.RefreshDataSource();
                }
            }

            tbPID.EditValue = null;
        }
Пример #11
0
        public User(StateManager stateMgr, API.Geo.World world)
        {
            this.mStateMgr = stateMgr;
            this.mWorld = world;
            this.mTimeSinceGUIOpen = new Timer();

            this.mCameraMan = null;
            this.IsAllowedToMoveCam = true;
            this.IsFreeCamMode = true;
            Camera cam = this.mStateMgr.Camera;
            cam.Position = new Vector3(-203, 633, -183);
            cam.Orientation = new Quaternion(0.3977548f, -0.1096644f, -0.8781486f, -0.2421133f);
            this.mCameraMan = new CameraMan(cam);
            this.mSelectedAllies = new HashSet<VanillaNonPlayer>();
            this.mRandom = new Random();

            this.mFigures = new MOIS.KeyCode[10];
            for (int i = 0; i < 9; i++)
                this.mFigures[i] = (MOIS.KeyCode)System.Enum.Parse(typeof(MOIS.KeyCode), "KC_" + (i + 1));
            this.mFigures[9] = MOIS.KeyCode.KC_0;

            this.mWireCube = this.mStateMgr.SceneMgr.RootSceneNode.CreateChildSceneNode();
            this.mWireCube.AttachObject(StaticRectangle.CreateRectangle(this.mStateMgr.SceneMgr, Vector3.UNIT_SCALE * Cst.CUBE_SIDE));
            this.mWireCube.SetVisible(false);

            this.Inventory = new Inventory(10, 4, new int[] { 3, 0, 1, 2 }, true);
        }
Пример #12
0
 public void ProcessRequest(HttpContext context)
 {
     context.Response.ContentType = "text/plain";
     context.Response.Clear();
     if (context.Request.Files.Count > 0)
     {
         try
         {
             HttpPostedFile httpPostFile = context.Request.Files[0];
             string file = context.Request.Form["Filename"].ToString();
             string fileType = file.Substring(file.LastIndexOf('.')).ToLower();
             Random r = new Random();
             string fileName = DateTime.Now.ToString("yyyyMMdd-HHmmss-ms") + r.Next(100, 999) + fileType;
             string serverPath = System.Configuration.ConfigurationSettings.AppSettings["ImageUploadPath"];
             httpPostFile.SaveAs(context.Server.MapPath(serverPath + fileName));
             context.Application["ImageUrl"] = serverPath + fileName;
             context.Response.Write("UP_OK");
         }
         catch
         {
             context.Response.Write("UP_FAILE");
         }
     }
     else
     {
         context.Response.Write("UP_FAILE");
     }
 }
Пример #13
0
        static void Main(string[] args)
        {
            const int NumberOfAnimals = 10;
            Stack<Animal> animalStack = new Stack<Animal>();
            Queue<Animal> animalQueue = new Queue<Animal>();

            Console.WriteLine("/// ORDER OF ENTRY...");
            Random r = new Random();
            for (int index = 0; index < NumberOfAnimals; index++)
            {
                var animalShouldBeCat = (r.Next(2) == 0);
                uint nextWeight = (uint)r.Next(10, 40);
                Animal nextAnimal = animalShouldBeCat ? (Animal)(new Cat(nextWeight, "John")) : (Animal)(new Dog(nextWeight, "Dave"));
                animalStack.Push(nextAnimal);
                animalQueue.Enqueue(nextAnimal);
                Console.WriteLine(nextAnimal);
            }

            Console.WriteLine();
            Console.WriteLine("/// OUTPUT FROM STACK...");
            foreach (Animal animal in animalStack)
            {
                Console.WriteLine(animal);
            }

            Console.WriteLine();
            Console.WriteLine("/// OUTPUT FROM QUEUE...");
            foreach (Animal animal in animalQueue)
            {
                Console.WriteLine(animal);
            }
        }
        protected void Arrange()
        {
            var random = new Random();
            _subsystemName = random.Next().ToString(CultureInfo.InvariantCulture);
            _operationTimeout = TimeSpan.FromSeconds(30);
            _encoding = Encoding.UTF8;
            _disconnectedRegister = new List<EventArgs>();
            _errorOccurredRegister = new List<ExceptionEventArgs>();
            _channelDataEventArgs = new ChannelDataEventArgs(
                (uint)random.Next(0, int.MaxValue),
                new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) });

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelMock = new Mock<IChannelSession>(MockBehavior.Strict);

            _sequence = new MockSequence();
            _sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object);
            _channelMock.InSequence(_sequence).Setup(p => p.Open());
            _channelMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true);

            _subsystemSession = new SubsystemSessionStub(
                _sessionMock.Object,
                _subsystemName,
                _operationTimeout,
                _encoding);
            _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args);
            _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args);
            _subsystemSession.Connect();
        }
Пример #15
0
        private EntityCollection GenerateRandomAccountCollection()
        {
            var collection = new List<Entity>();
            for (var i = 0; i < 10; i++)
            {
                var rgn = new Random((int)DateTime.Now.Ticks);
                var entity = new Entity("account");
                entity["accountid"] = entity.Id = Guid.NewGuid();
                entity["address1_addressid"] = Guid.NewGuid();
                entity["modifiedon"] = DateTime.Now;
                entity["lastusedincampaign"] = DateTime.Now;
                entity["donotfax"] = rgn.NextBoolean();
                entity["new_verybignumber"] = rgn.NextInt64();
                entity["exchangerate"] = rgn.NextDecimal();
                entity["address1_latitude"] = rgn.NextDouble();
                entity["numberofemployees"] = rgn.NextInt32();
                entity["primarycontactid"] = new EntityReference("contact", Guid.NewGuid());
                entity["revenue"] = new Money(rgn.NextDecimal());
                entity["ownerid"] = new EntityReference("systemuser", Guid.NewGuid());
                entity["industrycode"] = new OptionSetValue(rgn.NextInt32());
                entity["name"] = rgn.NextString(15);
                entity["description"] = rgn.NextString(300);
                entity["statecode"] = new OptionSetValue(rgn.NextInt32());
                entity["statuscode"] = new OptionSetValue(rgn.NextInt32());
                collection.Add(entity);
            }

            return new EntityCollection(collection);
        }
Пример #16
0
        /// <summary>
        /// If there is no real life data between seasons,
        /// change some match dates to around now for testing purposes
        /// </summary>
        private static void ChangeMatchDates(TtcDbContext context)
        {
            bool endOfSeason = !context.Matches.Any(match => match.Date > DateTime.Now);
            if (true || endOfSeason)
            {
                var passedMatches = context.Matches
                    .Where(x => x.FrenoySeason == Constants.FrenoySeason)
                    //.Where(x => x.Date < DateTime.Today)
                    .OrderByDescending(x => x.Date)
                    .Take(42);

                var timeToAdd = DateTime.Today - passedMatches.First().Date;
                foreach (var match in passedMatches.Take(20))
                {
                    match.Date = match.Date.Add(timeToAdd);
                }

                var rnd = new Random();
                foreach (var match in passedMatches.Take(20))
                {
                    match.Date = DateTime.Today.Add(TimeSpan.FromDays(rnd.Next(1, 20))).AddHours(rnd.Next(10, 20));
                    match.Description = "";
                    match.AwayScore = null;
                    match.HomeScore = null;
                    //match.IsSyncedWithFrenoy = true;
                    match.WalkOver = false;

                    context.MatchComments.RemoveRange(match.Comments.ToArray());
                    context.MatchGames.RemoveRange(match.Games.ToArray());
                    context.MatchPlayers.RemoveRange(match.Players.ToArray());
                }
            }
        }
Пример #17
0
        public ViewModel()
        {
            mgt = new ManagementClass("Win32_Processor");
            procs = mgt.GetInstances();

            CPU = new ObservableCollection<Model>();
            timer = new DispatcherTimer();
            random = new Random();
            time = DateTime.Now;
            cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";
            ramCounter = new PerformanceCounter("Memory", "Available MBytes");
            ProcessorID = GetProcessorID();
            processes = Process.GetProcesses();
            Processes = processes.Length;
            MaximumSpeed = GetMaxClockSpeed();
            LogicalProcessors = GetNumberOfLogicalProcessors();
            Cores = GetNumberOfCores();
            L2Cache = GetL2CacheSize();
            L3Cache = GetL3CacheSize();
            foreach (ManagementObject item in procs)
                L1Cache = ((UInt32)item.Properties["L2CacheSize"].Value / 2).ToString() + " KB";

            timer.Interval = TimeSpan.FromMilliseconds(1000);
            timer.Tick += timer_Tick;
            timer.Start();
            for (int i = 0; i < 60; i++)
            {
                CPU.Add(new Model(time, 0,0));
                time = time.AddSeconds(1);
            }
        }
Пример #18
0
        public void RandomPacketTest()
        {
            int seed = new Random().Next();
            Console.WriteLine("Seed: " + seed);
            Random random = new Random(seed);

            for (int i = 0; i != 1000; ++i)
            {
                Packet packet = random.NextPacket(random.Next(10 * 1024));

                // Check Equals
                Assert.AreEqual(packet, new Packet(packet.Buffer, packet.Timestamp.AddHours(1), packet.DataLink));
                Assert.AreNotEqual(packet, random.NextPacket(random.Next(10 * 1024)));
                if (packet.Length != 0)
                    Assert.AreNotEqual(packet, random.NextPacket(packet.Length));

                // Check GetHashCode
                Assert.AreEqual(packet.GetHashCode(), new Packet(packet.Buffer, packet.Timestamp.AddHours(1), packet.DataLink).GetHashCode());
                Assert.AreNotEqual(packet.GetHashCode(), random.NextPacket(random.Next(10 * 1024)).GetHashCode());
                if (packet.Length != 0)
                    Assert.AreNotEqual(packet.GetHashCode(), random.NextPacket(packet.Length).GetHashCode());

                // Check ToString
                Assert.IsNotNull(packet.ToString());

                Assert.IsFalse(new Packet(packet.Buffer, DateTime.Now, (DataLinkKind)((int)DataLinkKind.Ethernet + 1)).IsValid);

                // Check Enumerable
                IEnumerable enumerable = packet;
                int offset = 0;
                foreach (byte b in enumerable)
                    Assert.AreEqual(packet[offset++], b);

            }
        }
Пример #19
0
        public Forest(string name, int minEnemies, int maxEnemies)
        {
            Random rand = new Random();
              this.name = name;
              this.genericName = "forest";
              this.genericPlural = "forests";
              this.genericDescription = new List<string>();
              this.genericDescription.Add("{0} surrounds you and you hear birds chirping in the trees above.");
              this.genericDescription.Add("{0} spreads out before you, beams of sunlight piercing through the canopy of leaves above.");
              this.genericDescription.Add("{0} appears to be more of a plain with a few trees here and there.");

              int enemies = rand.Next(minEnemies, maxEnemies);

              for (int i = 0; i < enemies; i++)
              {
            int randomName = rand.Next(0, CharacterNames.namesEnemies.Count);
            int minValue = Math.Max((Program.currentGame.player.level - 1), 1);
            int maxValue = Program.currentGame.player.level + 1;
            int randomFortitude = rand.Next(minValue, maxValue);
            int randomStrength = rand.Next(minValue, maxValue);
            int randomSpeed = rand.Next(minValue, maxValue);
            int randomDexterity = rand.Next(minValue, maxValue);

            this.enemies.Add(new Enemy(CharacterNames.namesEnemies[randomName], randomFortitude, randomStrength, randomSpeed, randomDexterity));
              }
        }
        protected void Arrange()
        {
            var random = new Random();
            _path = random.Next().ToString(CultureInfo.InvariantCulture);
            _handle = new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) };
            _fileAttributes = SftpFileAttributes.Empty;
            _bufferSize = (uint)random.Next(0, 1000);
            _readBufferSize = (uint)random.Next(0, 1000);
            _writeBufferSize = (uint)random.Next(0, 1000);

            _sftpSessionMock = new Mock<ISftpSession>(MockBehavior.Strict);

            var sequence = new MockSequence();
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.RequestOpen(_path, Flags.Write | Flags.Truncate, true))
                .Returns(_handle);
            _sftpSessionMock.InSequence(sequence).Setup(p => p.RequestFStat(_handle)).Returns(_fileAttributes);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.CalculateOptimalReadLength(_bufferSize))
                .Returns(_readBufferSize);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle))
                .Returns(_writeBufferSize);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.IsOpen)
                .Returns(true);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.RequestClose(_handle));

            _sftpFileStream = new SftpFileStream(_sftpSessionMock.Object, _path, FileMode.Create, FileAccess.Write, (int)_bufferSize);
        }
Пример #21
0
        public static void Main(string[] args)
        {
            OrderedMultiDictionary<double, Article> articles = new OrderedMultiDictionary<double, Article>(true);
            Random randomNumberGenerator = new Random();
            double randomNumber;
            for (int i = 0; i < 2000000; i++)
            {
                randomNumber = randomNumberGenerator.NextDouble() * MaxValue;
                Article article = new Article("barcode" + i, "vendor" + i, "article" + i, randomNumber);
                articles.Add(article.Price, article);
            }

            Console.Write("from = ");
            double from = double.Parse(Console.ReadLine());
            Console.Write("to = ");
            double to = double.Parse(Console.ReadLine());
            var articlesInRange = articles.Range(from, true, to, true);
            foreach (var pair in articlesInRange)
            {
                foreach (var article in pair.Value)
                {
                    Console.WriteLine("{0} => {1}", Math.Round(article.Price, 2), article);
                }
            }
        }
        public ActionResult Create(Post post)
        {

            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            var stringChars = new char[8];
            var random = new Random();

            for (int i = 0; i < stringChars.Length; i++)
            {
                stringChars[i] = chars[random.Next(chars.Length)];
            }

            var finalString = new String(stringChars);//this is random key

            post.ID = finalString;
            //ViewBag.data = post.ID;
            if (ModelState.IsValid)
            {
                db.Posts.Add(post);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

           
            return View(post);
        }
Пример #23
0
        public static void ApplySetPieces(World world)
        {
            var map = world.Map;
            int w = map.Width, h = map.Height;

            Random rand = new Random();
            HashSet<Rect> rects = new HashSet<Rect>();
            foreach (var dat in setPieces)
            {
                int size = dat.Item1.Size;
                int count = rand.Next(dat.Item2, dat.Item3);
                for (int i = 0; i < count; i++)
                {
                    IntPoint pt = new IntPoint();
                    Rect rect;

                    int max = 50;
                    do
                    {
                        pt.X = rand.Next(0, w);
                        pt.Y = rand.Next(0, h);
                        rect = new Rect() { x = pt.X, y = pt.Y, w = size, h = size };
                        max--;
                    } while ((Array.IndexOf(dat.Item4, map[pt.X, pt.Y].Terrain) == -1 ||
                             rects.Any(_ => Rect.Intersects(rect, _))) &&
                             max > 0);
                    if (max <= 0) continue;
                    dat.Item1.RenderSetPiece(world, pt);
                    rects.Add(rect);
                }
            }
        }
Пример #24
0
 internal Address Next(Random r)
 {
     var pref = addresses.prefecture[r.Next(addresses.prefecture.Count)];
     var city = addresses.city[r.Next(addresses.city.Count)];
     var town = addresses.town[r.Next(addresses.town.Count)];
     return new Address
     {
         Prefecture = new JapaneseText
         {
             Kanji = pref[KanjiIndex],
             Hiragana = pref[HiraganaIndex],
             Katakana = pref[KatakanaIndex]
         },
         City = new JapaneseText
         {
             Kanji = city[KanjiIndex],
             Hiragana = city[HiraganaIndex],
             Katakana = city[KatakanaIndex]
         },
         Town = new JapaneseText
         {
             Kanji = town[KanjiIndex],
             Hiragana = town[HiraganaIndex],
             Katakana = town[KatakanaIndex]
         }
     };
 }
Пример #25
0
        public DefaultMapGenerator(long seed)
        {
            Frequency = 0.03;
            Lacunarity = 0.01;
            Persistance = 0.01;
            OctaveCount = 1;

            Seed = seed;
            CaveNoise = new Perlin();
            TreeNoise = new Perlin();
            CaveNoise.Seed = (int)Seed + 3;
            TreeNoise.Seed = (int)Seed + 4;
            rand = new Random((int)Seed);

            CaveNoise.Frequency = Frequency;
            CaveNoise.NoiseQuality = NoiseQuality;
            CaveNoise.OctaveCount = OctaveCount+2;
            CaveNoise.Lacunarity = Lacunarity;
            CaveNoise.Persistence = Persistance;

            TreeNoise.Frequency = Frequency+2;
            TreeNoise.NoiseQuality = NoiseQuality;
            TreeNoise.OctaveCount = OctaveCount;
            TreeNoise.Lacunarity = Lacunarity;
            TreeNoise.Persistence = Persistance;
        }
Пример #26
0
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int[] numbers = new int[n];
            Random rand = new Random();

            for (int i = 0; i < numbers.Length; i++)
            {
                numbers[i] = rand.Next(1, 100);
            }

            int startArraySort = Environment.TickCount;
            Array.Sort(numbers);
            Console.WriteLine("Array sort in miliseconds: " + (Environment.TickCount - startArraySort));

            int startSort = Environment.TickCount;
            var sortedOdd = numbers
                .Where(number => number % 2 == 1)
                .OrderByDescending(number => number);
            Console.WriteLine("Array sort in milisecond: " + (Environment.TickCount - startSort));

            int lastArray = Environment.TickCount;
            var sortedEven = numbers
                .Where(number => number % 2 == 0)
                .OrderBy(number => number);
            Console.WriteLine("Array sort in miliseconds: " + (Environment.TickCount - lastArray));
        }
Пример #27
0
        public static void Main()
        {
            var someActivities = new string[] {
                "Pesho beshe na more",
                "Boil ima novo kuche",
                "Neli chete GoT"
            };

            var rng = new Random();

            var newsFeedList = new List<UserNewsFeed>();

            // slow operation simulation
            Console.WriteLine("Request weather report from the server");
            var weatherReport = Server.GetWeatherReport();
            Console.WriteLine("Report reveceived for: " + 2000 + " miliseconds");

            // cloning proves a lot faster in that case
            for (int i = 0; i < 4; i++)
            {
                var activity = someActivities[rng.Next() % 3];
                newsFeedList.Add(new UserNewsFeed(activity, (WeatherReport)weatherReport.Clone()));
            }

            foreach (var item in newsFeedList)
            {
                Console.WriteLine("\n" + item + "\n ");
            }
        }
Пример #28
0
        static void Main(string[] args)
        {
            var m_Config = new ServerConfig
            {
                Port = 911,
                Ip = "Any",
                MaxConnectionNumber = 1000,
                Mode = SocketMode.Tcp,
                Name = "CustomProtocolServer"
            };

            var m_Server = new CustomProtocolServer();
            m_Server.Setup(m_Config, logFactory: new ConsoleLogFactory());
            m_Server.Start();

            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);

            using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Connect(serverAddress);

                var socketStream = new NetworkStream(socket);
                var reader = new StreamReader(socketStream, Encoding.ASCII, false);

                string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty);

                Random rd = new Random();

                var watch = Stopwatch.StartNew();
                for (int i = 0; i < 10; i++)
                {
                    int startPos = rd.Next(0, charSource.Length - 2);
                    int endPos = rd.Next(startPos + 1, charSource.Length - 1);

                    var currentMessage = charSource.Substring(startPos, endPos - startPos + 1);

                    byte[] requestNameData = Encoding.ASCII.GetBytes("ECHO");
                    socketStream.Write(requestNameData, 0, requestNameData.Length);
                    var data = Encoding.ASCII.GetBytes(currentMessage);
                    socketStream.Write(new byte[] { (byte)(data.Length / 256), (byte)(data.Length % 256) }, 0, 2);
                    socketStream.Write(data, 0, data.Length);
                    socketStream.Flush();

                   // Console.WriteLine("Sent: " + currentMessage);

                    var line = reader.ReadLine();
                    //Console.WriteLine("Received: " + line);
                    //Assert.AreEqual(currentMessage, line);
                }

                

                watch.Stop();
                Console.WriteLine(watch.ElapsedMilliseconds);
            }

            Console.ReadLine();
        }
        static void Main2(string[] args)
        {
            var numReal = new List<double>(80);
            Random gerador = new Random();
            double maior = 0;
            double menor = 0;
            double soma = 0;
            double media = 0;
            for (int i = 0; i < 80; i++)
            {
                numReal.Add(gerador.NextDouble());
                if (i == 0)
                {
                    maior = numReal[i];
                    menor = numReal[i];
                }
                soma += numReal[i];

            }
            media = soma / 80;
            for (int i = 0; i < 80; i++)
            {
                maior = (numReal[i] > maior) ? numReal[i] : maior;
                menor = (numReal[i] < menor) ? numReal[i] : menor;
            }
            Console.WriteLine("Maior: {0:F2}", maior);
            Console.WriteLine("Menor: {0:F2}", menor);
            Console.WriteLine("Soma: {0:F2}", soma);
            Console.WriteLine("Media: {0:F2}", media);
            Console.ReadKey();
        }
Пример #30
0
 public static long GetRandomLong()
 {
     var random = new Random();
     var value = ((long)random.Next()) << 32 + random.Next();
     var sign = random.Next(0, 2) == 0 ? -1 : 1;
     return value * sign;
 }