Exemple #1
0
        static void Main(string[] args)
        {
            RandomArray rArray;

            while (true)
            {
                Console.Write("Создание экземпляра класса RandomArray\nВведите длину массива (от 10 до 100): ");
                int capacity = 0;
                if (int.TryParse(Console.ReadLine(), out capacity) && capacity >= 10 && capacity <= 100)
                {
                    rArray = new RandomArray(capacity);
                    break;
                }
                else
                {
                    Console.WriteLine("Вводимое значение должно быть натуральным числом от 10 до 100\nПовторите ввод");
                }
            }

            StepInfo(rArray, "Массив до инициации случайными значениями");

            rArray.RandomInit();

            StepInfo(rArray, "Массив после инициации случайными значениями");

            StepInfo(rArray.AmmountOfDegrees(), "Результат работы метода AmountOfDegrees");

            rArray[0] = 5;
            StepInfo(rArray, "Попытка присвоить невалидное значение - 5, первому элементу массива");

            rArray[0] = 8;
            StepInfo(rArray, "Попытка присвоить валидное значение - 8, первому элементу массива");
        }
        /// <summary>
        /// 创建用户顺便创建用户的钱包信息
        /// </summary>
        /// <param name="evnt"></param>
        /// <returns></returns>
        public Task <AsyncTaskResult> HandleAsync(UserCreatedEvent evnt)
        {
            var tasks  = new List <Task>();
            var number = DateTime.Now.ToSerialNumber();

            //创建用户的钱包信息
            tasks.Add(_commandService.SendAsync(new CreateWalletCommand(evnt.WalletId,
                                                                        evnt.AggregateRootId)));
            //创建用户的购物车信息
            tasks.Add(_commandService.SendAsync(new CreateCartCommand(evnt.CartId,
                                                                      evnt.AggregateRootId)));
            //给用户随机余额
            tasks.Add(_commandService.SendAsync(new CreateCashTransferCommand(
                                                    GuidUtil.NewSequentialId(),
                                                    evnt.WalletId,
                                                    number,
                                                    CashTransferType.SystemOp,
                                                    CashTransferStatus.Placed,
                                                    RandomArray.NewUserRedPacket(),
                                                    0,
                                                    WalletDirection.In,
                                                    "新用户红包")));
            //执行所以的任务
            Task.WaitAll(tasks.ToArray());
            return(Task.FromResult(AsyncTaskResult.Success));
        }
Exemple #3
0
        public void Incentive()
        {
            var benevolenceIndex = RandomArray.BenevolenceIndex();

            if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
            {
                //周日两倍激励
                benevolenceIndex = benevolenceIndex * 2;
            }

            //善心指数判断
            if (benevolenceIndex <= 0 || benevolenceIndex >= 1)
            {
                throw new Exception("善心指数异常");
            }

            //遍历所有的钱包发送激励指令
            var wallets = _walletQueryService.ListPage();

            foreach (var wallet in wallets)
            {
                var command = new IncentiveBenevolenceCommand(wallet.Id, benevolenceIndex);
                _commandService.SendAsync(command);
            }
        }
        public BaseApiResponse Info()
        {
            //今日当前销售量
            //var todaySale = _storeQueryService.TodaySale();
            //所有待分配的善心量
            //var totalBenevolence = _walletQueryService.TotalBenevolence();
            decimal currentBIndex = 0;
            //if (todaySale>0&&totalBenevolence>0)
            //{
            //    currentBIndex = Math.Round((todaySale * 0.15M) / (totalBenevolence*ConfigSettings.BenevolenceValue*10), 4);
            //}

            //指定范围的随机数

            //从缓存获取善心指数
            var benevolenceIndex = _apiSession.GetBenevolenceIndex();

            if (benevolenceIndex == null)
            {
                benevolenceIndex = RandomArray.BenevolenceIndex().ToString();
                _apiSession.SetBenevolenceIndex(benevolenceIndex);
            }
            currentBIndex = Convert.ToDecimal(benevolenceIndex);

            return(new InfoResponse
            {
                CurrentBenevolenceIndex = currentBIndex,
                StoreCount = 3413,
                ConsumerCount = 3453,
                PasserCount = 35346,
                AmbassadorCount = 44343
            });
        }
Exemple #5
0
        public void GeneralTest()
        {
            var randomArray = new RandomArray(5);
            var num = randomArray.Next();
            Assert.IsTrue(num <= 5 && num >= 0);

            AssertHelper.ExpectedException<ArgumentOutOfRangeException>(() => new RandomArray(-1));
            AssertHelper.ExpectedException<ArgumentOutOfRangeException>(() => new RandomArray(0));
        }
 public static string Status()
 {
     return(RandomArray.Pick(
                new string[] {
         QuoteStatusV1.New, QuoteStatusV1.Writing, QuoteStatusV1.Translating,
         QuoteStatusV1.Verifying, QuoteStatusV1.Completed
     }
                ));
 }
        public void BenchmarkDelete()
        {
            var id = RandomArray.Pick(_ids.ToArray());

            if (!string.IsNullOrWhiteSpace(id))
            {
                _cache.RemoveAsync(_correlationId, id).Wait();
            }
        }
        public void TestAccuracy()
        {
            int arraySize = 100;

            int[] testArray = RandomArray.GetRandomArray(arraySize, 0, 20000);

            int[] sortedArray = EvenOddSort.Sort(testArray);
            Assert.IsTrue(ArrayUtils.IsSorted(sortedArray));
        }
        /// <summary>
        /// To initialize the generator state.
        /// </summary>
        public virtual void Init()
        {
            LastGenerationTime = DateTimeOffset.MinValue;

            Volumes = new RandomArray <int>(MinVolume, MaxVolume, RandomArrayLength);
            Steps   = new RandomArray <int>(1, MaxPriceStepCount, RandomArrayLength);

            SecurityDefinition = null;
        }
Exemple #10
0
        public void GeneralTest()
        {
            var randomArray = new RandomArray(5);
            var num         = randomArray.Next();

            Assert.IsTrue(num <= 5 && num >= 0);

            AssertHelper.ExpectedException <ArgumentOutOfRangeException>(() => new RandomArray(-1));
            AssertHelper.ExpectedException <ArgumentOutOfRangeException>(() => new RandomArray(0));
        }
Exemple #11
0
        public static DoubleMatrix DoubleMatrix(Double max, int rowCount, int columnCount)
        {
            double[][] array = new double[rowCount][];

            RandomArray <double, double> generator = new RandomArray <double, double>(Double);

            for (int i = 0; i < rowCount; i++)
            {
                array[i] = generator.Instance(max, columnCount);
            }

            return(new DoubleMatrix(array));
        }
        public void OriginalArrayUnmodified()
        {
            int arraySize = 100;

            int[] testArray = RandomArray.GetRandomArray(arraySize, 0, 20000);
            int[] copyArray = new int[arraySize];
            testArray.CopyTo(copyArray, 0);

            int[] sortedArray = EvenOddSort.Sort(testArray);
            for (int i = 0; i < arraySize; i++)
            {
                Assert.IsTrue(testArray[i] == copyArray[i]);
            }
        }
Exemple #13
0
 public static BlobInfoV1 Blob()
 {
     return(new BlobInfoV1
     {
         Id = IdGenerator.NextLong(),
         Group = RandomText.Name(),
         Name = RandomText.Name(),
         Size = RandomLong.NextLong(100, 100000),
         ContentType = RandomArray.Pick(new string[] { "text/plain", "application/binary", "application/json" }),
         CreateTime = DateTime.UtcNow,
         ExpireTime = RandomDateTime.NextDateTime(DateTime.UtcNow, new DateTime(2010, 1, 1)),
         Completed = RandomBoolean.NextBoolean()
     });
 }
        public void BenchmarkGet()
        {
            var id = RandomArray.Pick(_ids.ToArray());

            if (!string.IsNullOrWhiteSpace(id))
            {
                var a = _cache.RetrieveAsync <DummyCacheObject>(_correlationId, id).Result;

                if (a == null)
                {
                    var obj = listCacheObjects.FirstOrDefault(t => t.Id == id);
                    _cache.StoreAsync(_correlationId, obj.Id, obj, 600000).Wait();
                }
            }
        }
Exemple #15
0
        public static async void Run()
        {
            Vector2[] vectors         = RandomArray.Vector2(10);
            double[]  distances       = new double[10];
            double    closestDistance = double.MaxValue;

            for (int i = 0; i < 10; i++)
            {
                distances[i] = Vector2.Distance(Vector2.Zero(), vectors[i]);
                Debug.WriteLine($"{vectors[i].ToString()} has a distance of {distances[i]}");
            }

            distances = Bubble.Sort(distances);

            Debug.WriteLine($"The closest distance is {closestDistance}");
        }
Exemple #16
0
        public void RandomArray_01()
        {
            var result   = new List <string>();
            var testData = new string[] { "tokyo    ", "singapore", "usa      ", "france   ", "africa   " };
            var original = new RandomArray <string>(testData);

            for (int i = 0; i < 100000; ++i)
            {
                var shuffled = original.Shuffle();

                string joined = string.Join(",", shuffled);
                result.Add(joined);
            }

            foreach (var x in result.GroupBy(x => x.Substring(0, 9)).OrderByDescending(x => x.Count()).Select(x => x.Key + " : " + x.Count()))
            {
                Console.WriteLine(x);
            }
        }
Exemple #17
0
        static void Main(string[] args)
        {
            ArrayGenerator random  = new RandomArray();
            ArrayGenerator nealy   = new NealySorted();
            ArrayGenerator reverse = new Reverse();
            ArrayGenerator unique  = new NealyRandom();

            unique.GenerateArray(100, 10);
            int[] unsortedInts = unique.unsorted;


            string yn;

            Console.WriteLine("Would you like to see your unsorted array? (Y)");
            yn = Console.ReadLine();

            if (yn == "y" || yn == "Y")
            {
                foreach (int i in unsortedInts)
                {
                    Console.WriteLine($"{i}");
                }
            }

            SuperSorter quick = new InsertionSort();

            quick.Sort(unsortedInts);

            Console.WriteLine("Would you like to see your sorted array? (Y)");
            yn = Console.ReadLine();

            if (yn == "y" || yn == "Y")
            {
                foreach (int i in unsortedInts)
                {
                    Console.WriteLine($"{i}");
                }
            }



            Console.ReadKey();
        }
Exemple #18
0
        public void Incentive()
        {
            var benevolenceIndex = RandomArray.BenevolenceIndex();

            if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
            {
                //周日两倍激励
                benevolenceIndex = benevolenceIndex * 2;
            }

            //善心指数判断
            if (benevolenceIndex <= 0 || benevolenceIndex >= 1)
            {
                throw new Exception("善心指数异常");
            }
            //所有待激励的钱包 福豆>1  钱包未锁定
            var wallets = _walletQueryService.ListPage().Where(x => x.Benevolence > 1 && x.IsFreeze == Common.Enums.Freeze.UnFreeze);

            //遍历所有的钱包发送激励指令
            if (wallets.Any())
            {
                var totalBenevolenceAmount = wallets.Sum(x => x.Benevolence);
                //创建激励记录
                _commandService.SendAsync(new CreateBenevolenceIndexCommand(
                                              GuidUtil.NewSequentialId(),
                                              benevolenceIndex,
                                              totalBenevolenceAmount
                                              ));

                foreach (var wallet in wallets)
                {
                    if (wallet.Benevolence > 1)
                    {
                        var command = new IncentiveBenevolenceCommand(wallet.Id, benevolenceIndex);
                        _commandService.SendAsync(command);
                    }
                }
            }
        }
Exemple #19
0
        public void NextTest()
        {
            var randomArray = new RandomArray(5);

            var num = randomArray.Next();
            Assert.IsTrue(num <= 5 && num >= 0);

            num = randomArray.Next();
            Assert.IsTrue(num <= 5 && num >= 0);

            num = randomArray.Next();
            Assert.IsTrue(num <= 5 && num >= 0);

            num = randomArray.Next();
            Assert.IsTrue(num <= 5 && num >= 0);

            num = randomArray.Next();
            Assert.IsTrue(num <= 5 && num >= 0);

            num = randomArray.Next();
            Assert.IsTrue(num <= 5 && num >= 0);
        }
        public BaseApiResponse Info()
        {
            decimal currentBIndex = 0;
            //从缓存获取善心指数
            var benevolenceIndex = _apiSession.GetBenevolenceIndex();

            if (benevolenceIndex == null)
            {
                benevolenceIndex = RandomArray.BenevolenceIndex().ToString();
                _apiSession.SetBenevolenceIndex(benevolenceIndex);
            }
            currentBIndex = Convert.ToDecimal(benevolenceIndex);

            return(new InfoResponse
            {
                CurrentBenevolenceIndex = currentBIndex,
                StoreCount = GenerFackCount(334, 1),
                ConsumerCount = GenerFackCount(43323, 106),
                PasserCount = GenerFackCount(2344, 8),
                AmbassadorCount = GenerFackCount(352, 2)
            });
        }
Exemple #21
0
        public void NextTest()
        {
            var randomArray = new RandomArray(5);

            var num = randomArray.Next();

            Assert.IsTrue(num <= 5 && num >= 0);

            num = randomArray.Next();
            Assert.IsTrue(num <= 5 && num >= 0);

            num = randomArray.Next();
            Assert.IsTrue(num <= 5 && num >= 0);

            num = randomArray.Next();
            Assert.IsTrue(num <= 5 && num >= 0);

            num = randomArray.Next();
            Assert.IsTrue(num <= 5 && num >= 0);

            num = randomArray.Next();
            Assert.IsTrue(num <= 5 && num >= 0);
        }
Exemple #22
0
 public static DoubleVector DoubleVector(double max, int count)
 {
     double[] array = new RandomArray <double, double>(Double).Instance(max, count);
     return(new DoubleVector(array));
 }
 /// <summary>
 /// Copy constructor if needed (optional)
 /// </summary>
 /// <param name="other">A RandomArray to copy the data from</param>
 public RandomArray(RandomArray other)
 {
     this.min   = other.min;
     this.max   = other.max;
     this.array = (int[])other.array.Clone();
 }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            Button    clickedButton = (Button)sender;
            Stopwatch sw            = new Stopwatch();

            switch (clickedButton.Name.ToLower())
            {
            case "quick":
                break;

            case "insertion":
                iStatus.Text         = RUNNING;
                iSortRuntime.Content = string.Empty;
                sw.Start();
                await InsertionSort.SortAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);

                sw.Stop();
                iStatus.Text         = COMPLETE;
                iSortRuntime.Content = sw.Elapsed;
                break;

            case "evenodd":
                eoStatus.Text         = RUNNING;
                eoSortRuntime.Content = string.Empty;
                sw.Start();
                await EvenOddSort.SortAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);

                sw.Stop();
                eoStatus.Text         = COMPLETE;
                eoSortRuntime.Content = sw.Elapsed;
                break;

            case "arrayadd":
                arrayAddStatus.Text     = RUNNING;
                arrayAddRuntime.Content = string.Empty;
                sw.Start();
                await ArrayAddition.AddArraysAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100),
                                                   RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);

                sw.Stop();
                arrayAddStatus.Text     = COMPLETE;
                arrayAddRuntime.Content = sw.Elapsed;
                break;

            case "arraysum":
                arraySumStatus.Text     = RUNNING;
                arraySumRuntime.Content = string.Empty;
                sw.Start();
                await ArraySum.SumAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);

                sw.Stop();
                arraySumStatus.Text     = COMPLETE;
                arraySumRuntime.Content = sw.Elapsed;
                break;

            case "parrayadd":
                pArrayAddStatus.Text     = RUNNING;
                pArrayAddRuntime.Content = string.Empty;
                sw.Start();
                await ParallelArrayAddition.AddArraysAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100),
                                                           RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);

                sw.Stop();
                pArrayAddStatus.Text     = COMPLETE;
                pArrayAddRuntime.Content = sw.Elapsed;
                break;

            case "psum":
                pSumStatus.Text     = RUNNING;
                pSumRuntime.Content = string.Empty;
                sw.Start();
                await ParallelSum.SumAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);

                sw.Stop();
                pSumStatus.Text     = COMPLETE;
                pSumRuntime.Content = sw.Elapsed;
                break;

            case "reduct":
                reductStatus.Text     = RUNNING;
                reductRuntime.Content = string.Empty;
                sw.Start();
                await ReductionSum.SumAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100));

                sw.Stop();
                reductStatus.Text     = COMPLETE;
                reductRuntime.Content = sw.Elapsed;
                break;

            case "all":
                iSortRuntime.Content     = string.Empty;
                eoSortRuntime.Content    = string.Empty;
                arrayAddRuntime.Content  = string.Empty;
                arraySumRuntime.Content  = string.Empty;
                pArrayAddRuntime.Content = string.Empty;
                pSumRuntime.Content      = string.Empty;
                allRuntime.Content       = string.Empty;
                iStatus.Text             = RUNNING;
                eoStatus.Text            = RUNNING;
                arrayAddStatus.Text      = RUNNING;
                arraySumStatus.Text      = RUNNING;
                pArrayAddStatus.Text     = RUNNING;
                pSumStatus.Text          = RUNNING;
                allStatus.Text           = RUNNING;
                sw.Start();
                Task inSort = InsertionSort.SortAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);
                Task eoSort = EvenOddSort.SortAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);
                Task arrAdd = ArrayAddition.AddArraysAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100),
                                                           RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);
                Task arrSum = ArraySum.SumAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);
                Task parAdd = ParallelArrayAddition.AddArraysAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100),
                                                                   RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);
                Task parSum = ParallelSum.SumAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);
                await inSort.ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        iStatus.Text = COMPLETE;
                    });
                });

                await eoSort.ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        eoStatus.Text = COMPLETE;
                    });
                });

                await arrAdd.ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        arrayAddStatus.Text = COMPLETE;
                    });
                });

                await arrSum.ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        arraySumStatus.Text = COMPLETE;
                    });
                });

                await parAdd.ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        pArrayAddStatus.Text = COMPLETE;
                    });
                });

                await parSum.ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        pSumStatus.Text = COMPLETE;
                    });
                });

                await Task.WhenAll(inSort, eoSort);

                sw.Stop();
                allRuntime.Content = sw.Elapsed;
                allStatus.Text     = COMPLETE;
                break;

            case "cancel":
                _cts?.Cancel();
                _cts = new CancellationTokenSource();
                break;

            default:
                break;
            }
        }
Exemple #25
0
        static void Main(string[] args)
        {
            #region Operations

            Console.WriteLine("Q24_8:");
            {
                var f1 = new Fixed <Q24_8>(3);
                Console.WriteLine($"3: {f1}");

                var f2 = new Fixed <Q24_8>(2);
                var f3 = f1.Add(f2);
                Console.WriteLine($"3 + 2: {f3}");

                f3 = f1.Multiply(f2);
                Console.WriteLine($"3 * 2: {f3}");

                f1 = new Fixed <Q24_8>(19);
                f2 = new Fixed <Q24_8>(13);
                f3 = f1.Multiply(f2);
                Console.WriteLine($"19 * 13: {f3}");

                f1 = new Fixed <Q24_8>(3);
                f2 = new Fixed <Q24_8>(2);
                f3 = f1.Divide(f2);
                Console.WriteLine($"3 / 2: {f3}");

                f1 = new Fixed <Q24_8>(248);
                f2 = new Fixed <Q24_8>(10);
                f3 = f1.Divide(f2);
                Console.WriteLine($"248 / 10: {f3}");

                f1 = new Fixed <Q24_8>(625);
                f2 = new Fixed <Q24_8>(1000);
                f3 = f1.Divide(f2);
                Console.WriteLine($"625 / 1000: {f3}");
            }

            Console.WriteLine();
            Console.WriteLine("Q16_16:");
            {
                var f1 = new Fixed <Q16_16>(3);
                Console.WriteLine($"3: {f1}");

                var f2 = new Fixed <Q16_16>(2);
                var f3 = f1.Add(f2);
                Console.WriteLine($"3 + 2: {f3}");

                f3 = f1.Multiply(f2);
                Console.WriteLine($"3 * 2: {f3}");

                f1 = new Fixed <Q16_16>(19);
                f2 = new Fixed <Q16_16>(13);
                f3 = f1.Multiply(f2);
                Console.WriteLine($"19 * 13: {f3}");

                f1 = new Fixed <Q16_16>(248);
                f2 = new Fixed <Q16_16>(10);
                f3 = f1.Divide(f2);
                Console.WriteLine($"248 / 10: {f3}");

                f1 = new Fixed <Q16_16>(625);
                f2 = new Fixed <Q16_16>(1000);
                f3 = f1.Divide(f2);
                Console.WriteLine($"625 / 1000: {f3}");
            }

            Console.WriteLine();
            Console.WriteLine("Q8_24:");
            {
                var f1 = new Fixed <Q8_24>(3);
                var f2 = new Fixed <Q8_24>(2);
                var f3 = f1.Add(f2);
                Console.WriteLine($"3 + 2: {f3}");

                f3 = f1.Multiply(f2);
                Console.WriteLine($"3 * 2: {f3}");

                f1 = new Fixed <Q8_24>(19);
                f2 = new Fixed <Q8_24>(13);
                f3 = f1.Multiply(f2);
                Console.WriteLine($"19 * 13: {f3}");

                f1 = new Fixed <Q8_24>(248);
                f2 = new Fixed <Q8_24>(10);
                f3 = f1.Divide(f2);
                Console.WriteLine($"248 / 10: {f3}");

                f1 = new Fixed <Q8_24>(625);
                f2 = new Fixed <Q8_24>(1000);
                f3 = f1.Divide(f2);
                Console.WriteLine($"625 / 1000: {f3}");
            }

            #endregion

            #region Gaussian Elimination

            Console.WriteLine();
            Console.WriteLine("Gaussian elimination:");

            Console.WriteLine();
            Console.WriteLine("Q8_24:");

            var matrixArr = RandomArray.GetRandomMatrixArray(10, 100);
            var matrix    = new Matrix(matrixArr, 10);
            Console.WriteLine("Original matrix:");
            matrix.Print();

            Console.WriteLine("After elimination:");
            matrix.EliminateRows();
            matrix.Print();

            #endregion

            var summary = BenchmarkRunner.Run <FixedTest>();
        }
Exemple #26
0
 public void GenerateWithSumOfElementsIsOne(int num)
 {
     Assert.IsTrue(Math.Abs(RandomArray.GenerateWithSumOfElementsIsOne(num).Sum() - 1.0) < 1e-8);
 }
Exemple #27
0
 public void SetUp()
 {
     _testMatrix  = RandomArray.GetRandomMatrixArray(dimension, maxValueInMatrix);
     Q16_16Matrix = new Matrix(_testMatrix, dimension);
     FloatMatrix  = new FloatMatrix(_testMatrix, dimension);
 }