コード例 #1
0
ファイル: Sprite.cs プロジェクト: zbx91/UtinyRipper
        public IReadOnlyList <IReadOnlyList <Vector2f> > GenerateOutline(SpriteAtlas atlas, Rectf rect, Vector2f pivot)
        {
            Vector2f[][] outlines    = RD.GenerateOutline(File.Version);
            float        pivotShiftX = rect.Width * pivot.X - rect.Width * 0.5f;
            float        pivotShiftY = rect.Height * pivot.Y - rect.Height * 0.5f;
            Vector2f     pivotShift  = new Vector2f(pivotShiftX, pivotShiftY);

            foreach (Vector2f[] outline in outlines)
            {
                for (int i = 0; i < outline.Length; i++)
                {
                    Vector2f point = outline[i] * PixelsToUnits;
                    outline[i] = point + pivotShift;
                }
            }
            return(FixRotation(atlas, outlines));
        }
コード例 #2
0
            /// <summary>
            ///     Тест Соловея-Штрассена. Имеет числа КарлМайкла
            /// </summary>
            /// <param name="source">Число, которое необходмио протестировать</param>
            /// <param name="count">Число прогонов теста</param>
            /// <returns></returns>
            public static PrimalityTestResult SSPT(BigInteger source, BigInteger count)
            {
                if (count >= source)
                {
                    throw new InvalidOperationException("Число прогонов теста не должно быть меньше тестируемого числа.");
                }
                if (source == 0)
                {
                    return(PrimalityTestResult.Composite);
                }
                if (source == 1)
                {
                    return(PrimalityTestResult.Unknown);
                }

                if (source < 0 || count <= 0)
                {
                    throw new InvalidOperationException(
                              "Тестируемое число и число его прогонов должны быть положительными числами!");
                }

                //нам необходимо, чтобы число было нечетным, поэтому мы отсеиваем все четные числа.
                if (source % 2 == 0)
                {
                    return(PrimalityTestResult.Composite);
                }
                BigInteger[] RestVariants = RD.UniformDistribution(2, source - 1, count);
                //отрезок [2,n-1]
                for (int i = 0; i < count; i++)
                {
                    BigInteger CurrentValue = RestVariants[i];
                    if (AdvancedEuclidsalgorithm.GCDResult(CurrentValue, source) != 1)
                    {
                        return(PrimalityTestResult.Composite);
                    }
                    //значение символа якоби
                    BigInteger jacobi = JacobiSymbol.Get(CurrentValue, source);
                    Comparison.LinearComparison comparison = new Comparison.LinearComparison(CurrentValue, source);
                    if (Comparison.MultiplicativeInverse.BinaryPowLinearComparison(comparison, (source - 1) / 2).LeastModulo != jacobi)
                    {
                        return(PrimalityTestResult.Composite);
                    }
                }

                return(PrimalityTestResult.Unknown);
            }
コード例 #3
0
ファイル: Sprite.cs プロジェクト: SeaniaTwix/UtinyRipper
        public override void Read(AssetStream stream)
        {
            base.Read(stream);

            Rect.Read(stream);
            Offset.Read(stream);
            if (IsReadBorder(stream.Version))
            {
                Border.Read(stream);
            }
            PixelsToUnits = stream.ReadSingle();
            if (IsReadPivot(stream.Version))
            {
                Pivot.Read(stream);
            }
            Extrude = stream.ReadUInt32();
            if (IsReadPolygon(stream.Version))
            {
                IsPolygon = stream.ReadBoolean();
                stream.AlignStream(AlignType.Align4);
            }

            if (IsReadRendererData(stream.Version))
            {
                RenderDataKey = stream.ReadTupleTLong <UtinyGUID>();
                m_atlasTags   = stream.ReadStringArray();
                SpriteAtlas.Read(stream);
            }
            RD.Read(stream);
            stream.AlignStream(AlignType.Align4);

            if (IsReadPhysicsShape(stream.Version))
            {
                int count = stream.ReadInt32();
                m_physicsShape = new Vector2f[count][];
                for (int i = 0; i < count; i++)
                {
                    m_physicsShape[i] = stream.ReadArray <Vector2f>();
                }
            }

            if (IsReadBones(stream.Version))
            {
                m_bones = stream.ReadArray <SpriteBone>();
            }
        }
コード例 #4
0
        public string Task2()
        {
            var timeMin = RD
                          .Where(s => s.SectionId == 0)
                          .Where(s => s.EnterOrLeave)
                          .Min(s => s.TimeLng);
            int minIndex = RD.FindIndex(x => x.TimeLng == timeMin);
            var timeMax  = RD
                           .Where(s => s.SectionId == 0)
                           .Where(s => s.EnterOrLeave)
                           .Max(s => s.TimeLng);
            int maxIndex = RD.FindIndex(x => x.TimeLng == timeMax);

            return($"\nAz első az {RD[minIndex].GuestId} sz. kuncsaft, " +
                   $"{RD[minIndex].TimeStr}-kor,\n " +
                   $"az utolsó az {RD[maxIndex].GuestId} sz., " +
                   $"{RD[maxIndex].TimeStr}-kor \nlépett ki az öltözőből");
        }
コード例 #5
0
ファイル: Enemy_Giant.cs プロジェクト: timrockefeller/Captris
    private IEnumerator DoExplode()
    {
        // 震动一波摄像头
        mainCameraCMP.DoVibrate(transform.position);
        // 伤敌80,自损15
        health.DoAttack(15);

        // 爆炸部分
        int totalExplotions = 5;

        while (totalExplotions-- > 0)
        {
            Vector2 varing = RD.NextPositionf(1, 1);
            Vector3 pos    = transform.position + new Vector3(varing.x - 0.5f, -transform.localScale.y / 2 + 0.2f, varing.y - 0.5f);
            Instantiate(explotionPrefab, pos, Quaternion.identity);
            yield return(new WaitForSeconds(0.1f));
        }
    }
コード例 #6
0
        public void DB_UPDATE_RUN()
        {
            if (DB_UPDT_WHERE != "" && DB_UPDT_SET != "" && DB_UPDT_table_name != "") //둘다 비어있지 않아야.
            {
                MySqlDataReader RD;
                int             i = 0;
                try
                {
                    RD = query_select("UPDATE `" + DATABASE + "`.`" + DB_UPDT_table_name + "` SET " + DB_UPDT_SET + " WHERE " + DB_UPDT_WHERE);
                }
                catch
                {
                    RD = query_select("UPDATE `" + DATABASE + "`.`" + DB_UPDT_table_name + "` SET " + DB_UPDT_SET + " WHERE " + DB_UPDT_WHERE, ++i);
                }

                RD.Close();
            }
            DB_UPDT_table_name = ""; //실행 후 초기화
        }
コード例 #7
0
        public override void Move()
        {
            int temp = RD.Next(100);

            if (temp < 15)
            {
                X += 5;
            }
            else if (temp < 40)
            {
                X += 1;
            }
            else if (temp < 65)
            {
                X -= 2;
            }
            else if (temp < 80)
            {
                X -= 1;
            }
        }
コード例 #8
0
        public override void Move()
        {
            int temp = RD.Next(100);

            if (temp < 25)
            {
                X += 4;
            }
            else if (temp < 40)
            {
                X += 2;
            }
            else if (temp < 60)
            {
                X -= 2;
            }
            else if (temp < 70)
            {
                X -= 1;
            }
        }
コード例 #9
0
        public override Point Play()
        {
            Point p = new Point(-1, -1);

            do
            {
                p = new Point(RD.Next(10), RD.Next(10));
            } while (B.IsAHit(p));


            Rectangle rect = new Rectangle
            {
                Fill = new SolidColorBrush(Color.FromArgb(255, 50, 50, 50))
            };

            B.G.Children.Add(rect);
            Grid.SetRow(rect, (int)p.X);
            Grid.SetColumn(rect, (int)p.Y);

            return(p);
        }
コード例 #10
0
            /// <summary>
            ///     Fermat Primality Test - тест на основе теоремы Ферма. Имеет псевдопростые числа
            /// </summary>
            /// <param name="source">Число, которое необходимо проверить на простотоу</param>
            /// ///
            /// <param name="count">Число прогонов теста. Чем больше, тем точнее ответ.</param>
            /// <returns></returns>
            /// <exception cref="InvalidOperationException"></exception>
            public static PrimalityTestResult FPT(int source, int count)
            {
                if (count >= source)
                {
                    throw new InvalidOperationException("Число прогонов теста должно быть меньше тестируемого числа.");
                }
                switch (source)
                {
                case 0:
                    return(PrimalityTestResult.Composite);

                case 1:
                    throw new InvalidOperationException("Единица не является ни простым, ни составным числом.");
                }

                if (source < 0 || count <= 0)
                {
                    throw new InvalidOperationException(
                              "Тестируемое число и количество прогонов должны быть положительными числами!");
                }

                BigInteger[] RestVariants = RD.UniformDistribution(2, source - 1, count);
                //отрезок [2,n-1]
                for (int i = 1; i <= count; i++)
                {
                    BigInteger CurrentValue = RestVariants[i - 1];
                    if (AdvancedEuclidsalgorithm.GCDResult(CurrentValue, source) != 1)
                    {
                        return(PrimalityTestResult.Composite);
                    }
                    Comparison.LinearComparison comparison = new Comparison.LinearComparison(CurrentValue, source);
                    if (Comparison.MultiplicativeInverse.BinaryPowLinearComparison(comparison, source - 1).A != 1)
                    {
                        return(PrimalityTestResult.Composite);
                    }
                }

                return(PrimalityTestResult.Unknown);
            }
コード例 #11
0
        public void ExplainServiceLogin(Enums.Departments targetDepartment)
        {
            IExplainServiceLogic service = null;

            if (targetDepartment == Enums.Departments.PD)
            {
                service = new PD();
            }
            else if (targetDepartment == Enums.Departments.RD)
            {
                service = new RD();
            }

            if (service != null)
            {
                service.ExplainServiceLogic();
            }
            else
            {
                throw new NotImplementedException("Only RD and PD know the logic");
            }
        }
コード例 #12
0
    IEnumerator DiedAnim()
    {
        GameObject.Find("CamPos").GetComponent <CameraController>().DoVibrate(transform.position);
        // do dieing ~~
        int num = 10;

        while (num-- > 0)
        {
            GameObject instance = Instantiate(explotionPrefab, this.transform);
            Vector3    deltaPos = RD.NextPositionf(1, 1, 1) - Vector3.one * 0.5f;
            instance.transform.position = instance.transform.position + deltaPos;
            yield return(new WaitForSeconds(0.2f));
        }
        yield return(new WaitForSeconds(1));

        // spawn Giant
        GameObject giant = Instantiate(giantPrefab, new Vector3(transform.position.x, 5, transform.position.z), Quaternion.identity);

        yield return(new WaitForSeconds(6));

        Destroy(transform.parent.gameObject);
    }
コード例 #13
0
ファイル: PlayManager.cs プロジェクト: timrockefeller/Captris
 /// <summary>
 /// 7-Bag Algorithm
 /// https://tetris.fandom.com/wiki/Random_Generator
 /// </summary>
 void FillNextBag()
 {
     if (nextBag.Count <= piecePrefabs.Length)
     {
         //fill a LENGTH long blocks
         int[] cps = new int[piecePrefabs.Length];
         for (int i = piecePrefabs.Length - 1; i >= 0; i--)
         {
             cps[i] = i;
         }
         for (int i = piecePrefabs.Length - 1; i >= 0; i--)
         {
             int rndnum = (int)(RD.NextDouble() * i);
             int tmp    = cps[i];
             cps[i]      = cps[rndnum];
             cps[rndnum] = tmp;
         }
         for (int i = 0; i < piecePrefabs.Length; i++)
         {
             nextBag.Enqueue(cps[i]);
         }
     }
 }
コード例 #14
0
        private BaseDepartment GetDepartmentInstance(Enums.Departments targetDepartmernt)
        {
            BaseDepartment department = null;

            switch (targetDepartmernt)
            {
            case Enums.Departments.RD:
                department = new RD(Enums.Managers.Klen);
                break;

            case Enums.Departments.PD:
                department = new PD();
                break;

            case Enums.Departments.CPD:
                department = new CPD();
                break;

            default:
                throw new NotImplementedException("Sorry, we didn't build this department instance");
            }
            return(department);
        }
コード例 #15
0
    /// Return a lazy sequence of samples. You typically want to call this in a foreach loop, like so:
    ///   foreach (Vector2 sample in sampler.Samples()) { ... }
    public IEnumerable <Vector2> Samples()
    {
        // First sample is choosen randomly
        yield return(AddSample(new Vector2(RD.NextFloat() * rect.width, RD.NextFloat() * rect.height)));

        while (activeSamples.Count > 0)
        {
            // Pick a random active sample
            int     i      = (int)RD.NextFloat() * activeSamples.Count;
            Vector2 sample = activeSamples[i];

            // Try `k` random candidates between [radius, 2 * radius] from that sample.
            bool found = false;
            for (int j = 0; j < k; ++j)
            {
                float   angle     = 2 * Mathf.PI * RD.NextFloat();
                float   r         = Mathf.Sqrt(RD.NextFloat() * 3 * radius2 + radius2); // See: http://stackoverflow.com/questions/9048095/create-random-number-within-an-annulus/9048443#9048443
                Vector2 candidate = sample + r * new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));

                // Accept candidates if it's inside the rect and farther than 2 * radius to any existing sample.
                if (rect.Contains(candidate) && IsFarEnough(candidate))
                {
                    found = true;
                    yield return(AddSample(candidate));

                    break;
                }
            }

            // If we couldn't find a valid candidate after k attempts, remove this sample from the active samples queue
            if (!found)
            {
                activeSamples[i] = activeSamples[activeSamples.Count - 1];
                activeSamples.RemoveAt(activeSamples.Count - 1);
            }
        }
    }
コード例 #16
0
        static void Main(string[] args)
        {
            ////Задание
            ////Используя Visual Studio, создайте проект по шаблону Console Application.
            ////Создайте анонимный метод, который принимает в качестве параметров три целочисленных аргумента и возвращает среднее арифметическое этих аргументов.

            //MyFirst first = delegate (int x, int y, int z) { return (x + y + z) / 3; };
            //Console.WriteLine(first(1, 2, 3));

            ////Задание 2
            ////Используя Visual Studio, создайте проект по шаблону Console Application.
            ////Создайте четыре лямбда оператора для выполнения арифметических действий: (Add – сложение, Sub – вычитание, Mul – умножение, Div – деление).
            ////Каждый лямбда оператор должен принимать два аргумента и возвращать результат вычисления.Лямбда оператор деления должен делать проверку деления на ноль.
            ////Написать программу, которая будет выполнять арифметические действия указанные пользователем.

            //Console.WriteLine("Введите первое число");
            //int x = Int32.Parse(Console.ReadLine());
            //Console.WriteLine("Введите второе число");
            //int y = Int32.Parse(Console.ReadLine());
            //Console.WriteLine("Введите одну из доступных операций Add – сложение, Sub – вычитание, Mul – умножение, Div – деление");
            //string oper = Console.ReadLine().ToLower();

            //MyCalc Add = (x, y) => { return x + y; };
            //MyCalc Sub = (x, y) => { return x - y; };
            //MyCalc Mul = (x, y) => { return x * y; };
            //MyCalc Div = (x, y) => {
            //                           if (y == 0)
            //                           {
            //                              Console.WriteLine("Делить на ноль нельзя, лови ноль.");
            //                              return 0;
            //                           }
            //                           else
            //                              return x / y;
            //                       };

            //int result;

            //switch (oper)
            //{
            //   case "add":
            //      {
            //         result = Add(x, y);
            //         break;
            //      }
            //   case "sub":
            //      {
            //         result = Sub(x, y);
            //         break;
            //      }
            //   case "mul":
            //      {
            //         result = Mul(x, y);
            //         break;
            //      }
            //   case "div":
            //      {
            //         result = Div(x, y);
            //         break;
            //      }
            //   default:
            //      {
            //         Console.WriteLine("Вы ввели недопустимое значение.");
            //         result = 0;
            //         break;
            //      }
            //}

            //Console.WriteLine(result);


            ////Задание 3
            ////Используя Visual Studio, создайте проект по шаблону Console Application.
            ////Создайте анонимный метод, который принимает в качестве аргумента массив делегатов и возвращает среднее арифметическое возвращаемых значений методов сообщенных
            ////с делегатами в массиве.Методы, сообщенные с делегатами из массива, возвращают случайное значение типа int.

            Console.WriteLine("Здадайте размер массива");
            int x = Int32.Parse(Console.ReadLine());

            RD rdd = delegate() { return(new Random().Next(x)); };

            RD[] array = new RD[x];

            for (int i = 0; i < array.Length; i++)
            {
                array[i] = () => new RD(rdd).Invoke();
            }

            RDArray a = delegate(RD[] c) {
                int y = new int();
                foreach (var i in array)
                {
                    y += i.Invoke();
                }
                return(y / array.Length);
            };

            foreach (var i in array)
            {
                Console.WriteLine(i.Invoke());
            }

            Console.WriteLine(a(array));
        }
コード例 #17
0
ファイル: PlayManager.cs プロジェクト: timrockefeller/Captris
    private void FixedUpdate()
    {
        // 更新进度

        float percent = curTime;

        if (progressStart && pieceCount > 0 && progressState == ProgressState.DAYTIME)
        {
            if (curTime < dayTime)
            {
                curTime += Time.fixedDeltaTime;
            }
            percent /= dayTime;

            hudManager.UpdateTimeBoard(percent);
            if (percent > 1)
            {
                /// do spawn monster
                // 数量由天数决定
                // 考虑非线性
                // Lazer
                int enemyCount = (int)((RD.NextDouble() * 0.5 + 0.5) * Mathf.Pow(dayCount, 0.7f) + 1);
                Debug.Log("Spawn Lazer: " + enemyCount);
                // enemies = new GameObject[enemyCount];
                while (enemyCount-- > 0)
                {
                    // random position
                    float thita = (RD.NextFloat() * 2 * Mathf.PI);
                    // 1-1.5倍距离生成
                    float   actualSpawnDistance = enemySpawnDistance * (1 + RD.NextFloat() * 0.5f);
                    Vector3 spawnpoint          = new Vector3(enemySpawnDistance * Mathf.Sin(thita), 3, enemySpawnDistance * Mathf.Cos(thita));
                    enemies.Add(Instantiate(enemyPrefab, worldManager.playerInstance.transform.position + spawnpoint, Quaternion.identity));
                }
                // Giant
                enemyCount = (int)((RD.NextDouble() * 0.5 + 0.5) * Mathf.Max(0, Mathf.Pow(dayCount - towerDestroyed[0], 0.6f)));
                Debug.Log("Spawn Giant: " + enemyCount);
                while (enemyCount-- > 0)
                {
                    bool enemyposN = RD.NextInt(2) == 1;
                    // enemies.Add(enemyposN?)
                    enemies.Add(Instantiate(enemyGiantPrefab,
                                            GameUtils.PositionToTranform(
                                                enemyposN ?
                                                worldManager.GetUnit(worldManager.towerpos1).position :
                                                worldManager.GetUnit(worldManager.towerpos2).position
                                                ) + Vector3.up * 3,
                                            Quaternion.identity)
                                );
                }

                // state change
                SendEvent(PlayEventType.GAME_ENTER_SWITCH);
                SendEvent(PlayEventType.GAME_ENTER_NIGHT);
                progressState = ProgressState.NIGHT;
                curTime       = 0;
                hudManager.UpdateTimeBoard(0);
            }
        }

        if (progressState == ProgressState.NIGHT)
        {
            // update UI
            if (curTime < nightTime)
            {
                curTime += Time.fixedDeltaTime;
            }
            percent /= nightTime;

            enemies.RemoveAll(g => g == null);
            if (/*all monster killed*/ enemies.Count == 0 || percent > 1)
            {
                SendEvent(PlayEventType.GAME_ENTER_SWITCH);
                SendEvent(PlayEventType.GAME_ENTER_DAY);
                progressState = ProgressState.DAYTIME;
                curTime       = 0;
                dayCount++;
            }
        }


        //UI update

        // 补充包
        if (nextPieces.Count < piecePrefabs.Length)
        {
            FillNextPiece();
        }

        // 恒时补充资源
        if (goldRefillTime > curGoldRefillTime)
        {
            curGoldRefillTime += Time.fixedDeltaTime;
        }
        else
        {
            curGoldRefillTime -= goldRefillTime;
            GainResource(ResourceType.GOLD);
        }
    }
コード例 #18
0
        bool Do_Delete()
        {
            pBar.Visible = true;
            this.Cursor  = Cursors.WaitCursor;


            foreach (DataTable T in DS.Tables)
            {
                if ((T.TableName == "registrymainview") || (T.TableName == "no_table"))
                {
                    continue;
                }
                T.Clear();
            }

            string          dataMember = dgAnagrafica.DataMember;
            CurrencyManager cm         = dgAnagrafica.BindingContext[DS, dataMember] as CurrencyManager;

            if (cm == null)
            {
                return(false);
            }
            DataView view = cm.List as DataView;

            if (view == null)
            {
                MessageBox.Show(this, "Selezionare almeno una anagrafica");
                return(true);
            }
            int Nselected = 0;
            int max       = view.Count - 1;

            for (int i = 0; i <= max; i++)
            {
                if (dgAnagrafica.IsSelected(i))
                {
                    Nselected++;
                }
            }
            pBar.Maximum = Nselected;
            pBar.Value   = 0;

            string filter = "";

            //int j = 0;
            for (int i = 0; i <= max; i++)
            {
                if (!dgAnagrafica.IsSelected(i))
                {
                    continue;
                }
                DataSet D = DS.Clone();
                QueryCreator.SetTableForPosting(D.Tables["registrymainview"], "registry");

                pBar.Increment(1);
                filter = QHS.CmpEq("idreg", view[i]["idreg"]);

                foreach (string tname in new string[] { "registrymainview", "registryaddress",
                                                        "registrycf", "registrylegalstatus", "registrypaymethod", "registrypiva",
                                                        "registryreference", "registrytaxablestatus" })
                {
                    DataAccess.RUN_SELECT_INTO_TABLE(Meta.Conn, D.Tables[tname], null, filter, null, false);
                    foreach (DataRow RD in D.Tables[tname].Rows)
                    {
                        RD.Delete();
                    }
                }

                PostData P = Meta.Get_PostData();
                P.InitClass(D, Meta.Conn);
                if (!P.DO_POST())
                {
                    Aggiorna();
                    pBar.Visible = false;
                    return(false);
                }
            }
            Aggiorna();
            this.Cursor  = Cursors.Default;
            pBar.Visible = false;
            return(true);
        }
コード例 #19
0
        public override void Read(AssetReader reader)
        {
            base.Read(reader);

            Rect.Read(reader);
            Offset.Read(reader);
            if (IsReadBorder(reader.Version))
            {
                Border.Read(reader);
            }
            PixelsToUnits = reader.ReadSingle();
            if (IsReadPivot(reader.Version))
            {
                Pivot.Read(reader);
            }
            Extrude = reader.ReadUInt32();
            if (IsReadPolygon(reader.Version))
            {
                IsPolygon = reader.ReadBoolean();
                reader.AlignStream(AlignType.Align4);
            }
#if UNIVERSAL
            if (IsReadAtlasName(reader.Flags))
            {
                AtlasName  = reader.ReadString();
                PackingTag = reader.ReadString();
            }
#endif

            if (IsReadRendererData(reader.Version))
            {
                RenderDataKey = reader.ReadTupleTLong <EngineGUID>();
                m_atlasTags   = reader.ReadStringArray();
                SpriteAtlas.Read(reader);
            }
            RD.Read(reader);
#if UNIVERSAL
            if (IsReadAtlasRD(reader.Flags))
            {
                AtlasRD.Read(reader);
            }
#endif
            reader.AlignStream(AlignType.Align4);

            if (IsReadPhysicsShape(reader.Version))
            {
                int count = reader.ReadInt32();
                m_physicsShape = new Vector2f[count][];
                for (int i = 0; i < count; i++)
                {
                    m_physicsShape[i] = reader.ReadAssetArray <Vector2f>();
                }
            }

            if (IsReadBones(reader.Version))
            {
                m_bones = reader.ReadAssetArray <SpriteBone>();
            }
#if UNIVERSAL
            if (IsReadSpriteID(reader.Version, reader.Flags))
            {
                SpriteID = reader.ReadString();
            }
#endif
        }
コード例 #20
0
        private void LookUp1_Click(object sender, EventArgs e) //部门人数查看,修改按钮事件
        {
            int z = 0; count = 0;                              //z格式控制,count数据的行数

            Initial_Data();                                    //初始化表格
            tableHead[0].Text = "";
            tableHead[1].Text = "员工编号";
            tableHead[2].Text = "姓名";
            tableHead[3].Text = "姓别";
            tableHead[4].Text = "职位";
            foreach (Label a in tableHead)
            {
                a.Visible = true;
            }
            LinkSQL linksql = new LinkSQL();    //创建数据库连接对像linksql

            System.Data.SqlClient.SqlDataReader RD;
            linksql.OpenSQL();    //打开数据库
            switch (label4.Text)  //根据部门选择查询
            {
            case "采购部":
                linksql.SQLSelect(@"select ID,Name,sex,post from employee where department_Id = 'PU0001'");
                break;

            case "仓储部":
                linksql.SQLSelect(@"select ID,Name,sex,post from employee where department_Id = 'ST0001'");
                break;
            }
            RD = linksql.Comm.ExecuteReader(); //接收查询结果
            while (RD.Read())                  //输入查询结果 TODO:暂时只能输出十六条数据
            {
                count++;
                if (count <= 8)              //小于8行,用表1记录
                {
                    for (int i = 0; i < RD.FieldCount; i++)
                    {
                        tableLabel1[z].Text            = ((z / 5) + 1).ToString();
                        tableLabel1[z].Visible         = true;
                        tableLabel1[i + z + 1].Text    = Convert.ToString(RD[i]);
                        tableLabel1[i + z + 1].Visible = true;
                    }
                }
                if (count % 8 == 0)
                {
                    z = 0;
                }
                if (count > 8 && count <= 16)           //8-16行用表2记录
                {
                    z = 0;
                    for (int i = 0; i < RD.FieldCount; i++)
                    {
                        tableLabel2[z].Text            = (((z / 5) + 1) + 8).ToString();
                        tableLabel2[z].Visible         = false;
                        tableLabel2[i + z + 1].Text    = Convert.ToString(RD[i]);
                        tableLabel2[i + z + 1].Visible = false;
                    }
                }

                z += 5;
            }
            pageNow.Text = "1";                          //当前页码
            pageAll.Text = ((count / 9) + 1).ToString(); //总页面数量

            linksql.CloseSQL();                          //闭关数据库
            //if (((Button)sender).Name == "lookUp1")
            //{
            if (int.Parse(pageAll.Text) > 1)
            {
                pageUp.Visible   = true;
                pageDown.Visible = true;
                MessageBox.Show("共" + pageAll.Text + "页");
            }
            //}
            if (((Button)sender).Name == "alter1")
            {
                add.Visible     = true;
                callOff.Visible = true;
            }
        }
コード例 #21
0
        private void LookUp2_Click(object sender, EventArgs e)      //应到、签到人数查看按钮事件
        {
            Initial_Data();
            foreach (Label a in tableHead)
            {
                a.Visible = true;
            }
            int z = 0;

            count = 0;                       //z格式控制,count数据的行数
            //--------------------------------------以上为初始化---------------------------//
            LinkSQL linksql = new LinkSQL(); //创建数据库连接对像linksql

            System.Data.SqlClient.SqlDataReader RD;

            linksql.OpenSQL();
            switch (((Button)sender).Name)   //判断引发事件的按钮
            {
            case "callOff":
            case "lookUp2":             //应到人员
                switch (label4.Text)    //根据部门选择查询
                {
                case "采购部":

                    linksql.SQLSelect(@"select a.employee_ID,a.employee_Name,a.shc,a.sign_in,b.post from sign as a,employee as b where a.employee_ID=b.ID and b.department_ID = 'PU0001' and (shc=1 or shc=2)");
                    break;

                case "仓储部":
                    linksql.SQLSelect(@"select a.employee_ID,a.employee_Name,a.shc,a.sign_in,b.post from sign as a,employee as b where a.employee_ID=b.ID and b.department_ID = 'ST0001' and (shc=1 or shc=2)");
                    break;
                }
                break;

            case "lookUp3":                 //实到人员
                switch (label4.Text)        //根据部门选择查询
                {
                case "采购部":

                    linksql.SQLSelect(@"select a.employee_ID,a.employee_Name,a.shc,a.sign_in,b.post from sign as a,employee as b where a.employee_ID=b.ID and b.department_ID = 'PU0001' and (sign_in=1 or sign_in=2)");
                    break;

                case "仓储部":
                    linksql.SQLSelect(@"select a.employee_ID,a.employee_Name,a.shc,a.sign_in,b.post from sign as a,employee as b where a.employee_ID=b.ID and b.department_ID = 'ST0001' and (sign_in=1 or sign_in=2)");
                    break;
                }
                break;
            }
            RD = linksql.Comm.ExecuteReader();
            while (RD.Read())
            {
                count++;
                if (count <= 8)
                {
                    for (int i = 0; i < RD.FieldCount; i++)
                    {
                        tableLabel1[i + z].Visible = true;
                        switch (i)
                        {
                        case 0:
                        case 1:
                            //tableLabel1[i + z].Visible = true;
                            tableLabel1[i + z].Text = Convert.ToString(RD[i]);
                            break;

                        case 2:
                        case 3:
                            switch (Convert.ToInt16(RD[i]))           //判断上班的值:0为不用上班,1为正常上班,2为特殊情况  签到:0为未签到,1为已签到,2为请假
                            {
                            //tableLabel1[i + z].Visible = true;
                            case 0:
                                tableLabel1[i + z].Text = "×";
                                break;

                            case 1:
                                tableLabel1[i + z].Text = "√";
                                break;

                            case 2:
                                tableLabel1[i + z].Text = "○";
                                break;
                            }
                            break;

                        case 4:
                            tableLabel1[i + z].Text = Convert.ToString(RD[i]);
                            break;
                        }
                    }
                }
                if (count % 8 == 0)    //新的一页重置格式控制
                {
                    z = -5;
                }

                if (count > 8 && count <= 16)
                {
                    for (int i = 0; i < RD.FieldCount; i++)
                    {
                        tableLabel2[i + z].Visible = false;
                        //tableLabel2[i + z].Text = Convert.ToString(RD[i]);
                        switch (i)
                        {
                        case 0:
                        case 1:
                            //tableLabel1[i + z].Visible = true;
                            tableLabel2[i + z].Text = Convert.ToString(RD[i]);
                            break;

                        case 2:
                        case 3:
                            switch (Convert.ToInt16(RD[i]))           //判断上班的值:0为不用上班,1为正常上班,2为特殊情况  签到:0为未签到,1为已签到,2为请假
                            {
                            //tableLabel1[i + z].Visible = true;
                            case 0:
                                tableLabel2[i + z].Text = "×";
                                break;

                            case 1:
                                tableLabel2[i + z].Text = "√";
                                break;

                            case 2:
                                tableLabel2[i + z].Text = "○";
                                break;
                            }
                            break;

                        case 4:
                            tableLabel2[i + z].Text = Convert.ToString(RD[i]);
                            break;
                        }
                    }
                }
                z += 5;
            }
            linksql.CloseSQL();                          //闭关数据库
            pageNow.Text = "1";                          //当前页码
            pageAll.Text = ((count / 9) + 1).ToString(); //总页面数量
            if (int.Parse(pageAll.Text) > 1)
            {
                pageUp.Visible   = true;
                pageDown.Visible = true;
                MessageBox.Show("共" + pageAll.Text + "页");
            }
            if (((Button)sender).Name == "alter2")
            {
                putIn.Visible   = true;
                callOff.Visible = true;
            }
        }
コード例 #22
0
        private void Alter2_Click(object sender, EventArgs e)   //应到签到修改按钮事件
        {
            Initial_Data();
            foreach (Label a in tableHead)
            {
                a.Visible = true;
            }
            putIn.Visible   = true;
            callOff.Visible = true;
            LinkSQL linksql = new LinkSQL();

            System.Data.SqlClient.SqlDataReader RD;
            int z = 0;      //行控制

            count = 0;      //清空记录
            //AlterSelect(); //根据部门选择查询
            if (((Button)sender).Name == "alter2")
            {
                //linksql.OpenSQL();
                label12.Text = ((Button)sender).Name.ToString();
                RD           = AlterSelect();
                while (RD.Read())
                {
                    count++;
                    if (count <= 8)
                    {
                        for (int i = 0; i < RD.FieldCount; i++)
                        {
                            tableLabel1[i + z].Visible = true;
                            switch (i)
                            {
                            case 0:
                            case 1:
                                tableLabel1[i + z].Visible = true;
                                tableLabel1[i + z].Text    = Convert.ToString(RD[i]);
                                break;

                            case 2:
                                tableTextBox1[(count - 1) * 2].Visible = true;
                                tableTextBox1[(count - 1) * 2].Text    = Convert.ToString(RD[i]);
                                tableLabel1[i + z].Visible             = false;
                                break;

                            case 3:
                                switch (Convert.ToInt16(RD[i]))           //判断上班的值:0为不用上班,1为正常上班,2为特殊情况  签到:0为未签到,1为已签到,2为请假
                                {
                                //tableLabel1[i + z].Visible = true;
                                case 0:
                                    tableLabel1[i + z].Text = "×";
                                    break;

                                case 1:
                                    tableLabel1[i + z].Text = "√";
                                    break;

                                case 2:
                                    tableLabel1[i + z].Text = "○";
                                    break;
                                }
                                break;

                            case 4:
                                tableLabel1[i + z].Text = Convert.ToString(RD[i]);
                                break;
                            }
                        }
                    }
                    if (count % 8 == 0)   //新的一页重置格式控制
                    {
                        z = -5;
                    }

                    if (count > 8 && count <= 16)
                    {
                        for (int i = 0; i < RD.FieldCount; i++)
                        {
                            //tableLabel2[i + z].Visible = true;
                            switch (i)
                            {
                            case 0:
                            case 1:
                                //tableLabel1[i + z].Visible = true;
                                tableLabel2[i + z].Text = Convert.ToString(RD[i]);
                                break;

                            case 2:
                            case 3:
                                switch (Convert.ToInt16(RD[i]))           //判断上班的值:0为不用上班,1为正常上班,2为特殊情况  签到:0为未签到,1为已签到,2为请假
                                {
                                //tableLabel1[i + z].Visible = true;
                                case 0:
                                    tableLabel2[i + z].Text = "×";
                                    break;

                                case 1:
                                    tableLabel2[i + z].Text = "√";
                                    break;

                                case 2:
                                    tableLabel2[i + z].Text = "○";
                                    break;
                                }
                                break;

                            case 4:
                                tableLabel2[i + z].Text = Convert.ToString(RD[i]);
                                break;
                            }
                        }
                    }
                    z += 5;
                }
                linksql.CloseSQL();
            }
            if (((Button)sender).Name == "alter3")
            {
                label12.Text = ((Button)sender).Name.ToString();
                count        = 0;
                linksql.OpenSQL();
                RD = AlterSelect();
                //int j = 0;
                while (RD.Read())
                {
                    count++;
                    if (count <= 8)
                    {
                        for (int i = 0; i < RD.FieldCount; i++)
                        {
                            tableLabel1[i + z].Visible = true;
                            switch (i)
                            {
                            case 0:
                            case 1:
                                tableLabel1[i + z].Visible = true;
                                tableLabel1[i + z].Text    = Convert.ToString(RD[i]);
                                break;

                            case 2:
                                switch (Convert.ToInt16(RD[i]))           //判断上班的值:0为不用上班,1为正常上班,2为特殊情况  签到:0为未签到,1为已签到,2为请假
                                {
                                //tableLabel1[i + z].Visible = true;
                                case 0:
                                    tableLabel1[i + z].Text = "×";
                                    break;

                                case 1:
                                    tableLabel1[i + z].Text = "√";
                                    break;

                                case 2:
                                    tableLabel1[i + z].Text = "○";
                                    break;
                                }
                                tableLabel1[i + z].Visible = true;
                                break;

                            case 3:
                                tableLabel1[i + z].Visible           = false;
                                tableTextBox1[count * 2 - 1].Visible = true;
                                tableTextBox1[count * 2 - 1].Text    = Convert.ToString(RD[i]);
                                //j++;

                                break;

                            case 4:
                                tableLabel1[i + z].Text = Convert.ToString(RD[i]);
                                break;
                            }
                        }
                    }
                    if (count % 8 == 0)   //新的一页重置格式控制
                    {
                        z = -5;
                    }

                    if (count > 8 && count <= 16)
                    {
                        //j = 0;
                        for (int i = 0; i < RD.FieldCount; i++)
                        {
                            //tableLabel2[i + z].Visible = true;
                            switch (i)
                            {
                            case 0:
                            case 1:
                                //tableLabel1[i + z].Visible = true;
                                tableLabel2[i + z].Text = Convert.ToString(RD[i]);
                                break;

                            case 2:
                                switch (Convert.ToInt16(RD[i]))           //判断上班的值:0为不用上班,1为正常上班,2为特殊情况  签到:0为未签到,1为已签到,2为请假
                                {
                                //tableLabel1[i + z].Visible = true;
                                case 0:
                                    tableLabel2[i + z].Text = "×";
                                    break;

                                case 1:
                                    tableLabel2[i + z].Text = "√";
                                    break;

                                case 2:
                                    tableLabel2[i + z].Text = "○";
                                    break;
                                }
                                break;

                            case 3:
                            case 4:
                                tableLabel2[i + z].Text = Convert.ToString(RD[i]);
                                break;
                            }
                        }
                    }
                    z += 5;
                }
                linksql.CloseSQL();
            }
            pageNow.Text = "1";                          //当前页码
            pageAll.Text = ((count / 9) + 1).ToString(); //总页面数量
            if (int.Parse(pageAll.Text) > 1)
            {
                pageUp.Visible   = true;
                pageDown.Visible = true;
                //MessageBox.Show("共" + pageAll.Text + "页");
            }
            foreach (TextBox a in tableTextBox1)
            {
                a.TextChanged += TextBoxChange_Click;
            }
        }
コード例 #23
0
    public static UnitType[,] NextModule()
    {
        int rn = RD.NextInt(modules.GetLength(0));

        return(RotateMatrix(modules[rn], RD.NextInt(4)));
    }
コード例 #24
0
    public static UnitType[,] NextTower()
    {
        int rn = RD.NextInt(towers.GetLength(0));

        return(RotateMatrix(towers[rn], RD.NextInt(4)));
    }
コード例 #25
0
    public void Generate()
    {
        poolCur          = 0;
        _seedX           = (float)(RD.NextDouble() * 100.0);
        _seedZ           = (float)(RD.NextDouble() * 100.0);
        int[,] heightMap = new int[size.x, size.y];
        ///////////// generate world
        for (int x = 0; x < size.x; x++)
        {
            for (int z = 0; z < size.y; z++)
            {
                float xSample = (x + _seedX) / _relief;
                float zSample = (z + _seedZ) / _relief;
                float noise   = Mathf.PerlinNoise(xSample, zSample) * 1.2f - 0.2f;
                noise = Mathf.Pow(noise, 2);


                heightMap[x, z] = (int)Mathf.Clamp(Mathf.Floor(_maxHeight * noise), 0, 1000);
                // int y = 0;
            }
        }

        //////////////////
        /// STACK begin
        /// 这里提前定义了两座遗迹的位置,需要在生成地形的时候提前平滑他们所在的位置
        const int TOWER_OUTTER_BORDER = 5, TOWER_INNER_BORDER = 10;

        towerpos1 = RD.NextPosition(size.x / 2 - TOWER_OUTTER_BORDER - TOWER_INNER_BORDER, size.y / 2 - TOWER_OUTTER_BORDER - TOWER_INNER_BORDER) + new Vector2Int(TOWER_OUTTER_BORDER, TOWER_INNER_BORDER + size.y / 2);
        towerpos2 = RD.NextPosition(size.x / 2 - TOWER_OUTTER_BORDER - TOWER_INNER_BORDER, size.y / 2 - TOWER_OUTTER_BORDER - TOWER_INNER_BORDER) + new Vector2Int(TOWER_INNER_BORDER + size.x / 2, TOWER_OUTTER_BORDER);
        /// do lerp
        const int TOWER_IS_HIGHER = 1;
        int       towerpos1height = TOWER_IS_HIGHER + heightMap[towerpos1.x, towerpos1.y];
        int       towerpos2height = TOWER_IS_HIGHER + heightMap[towerpos2.x, towerpos2.y];

        const float roundBorderMin = 7f;
        const float roundBorderMax = 11f;

        for (int x = 0; x < size.x; x++)
        {
            for (int z = 0; z < size.y; z++)
            {
                Vector2Int _cur       = new Vector2Int(x, z);
                float      _magnitude = (_cur - towerpos1).magnitude;
                if (_magnitude < roundBorderMax)
                {
                    heightMap[x, z] = (int)Mathf.SmoothStep(towerpos1height, heightMap[x, z], Mathf.Clamp01((_magnitude - roundBorderMin) / (roundBorderMax - roundBorderMin)));
                }
                else
                {
                    _magnitude = (_cur - towerpos2).magnitude;
                    if (_magnitude < roundBorderMax)
                    {
                        heightMap[x, z] = (int)Mathf.SmoothStep(towerpos2height, heightMap[x, z], Mathf.Clamp01((_magnitude - roundBorderMin) / (roundBorderMax - roundBorderMin)));
                    }
                }
            }
        }
        /// STACK end
        //////////////////

        // 整流一波
        bool changed        = true;
        int  maxChangeCount = 5;

        while (maxChangeCount-- > 0 && changed)
        {
            changed = false;
            for (int x = 0; x < size.x; x++)
            {
                for (int z = 0; z < size.y; z++)
                {
                    int tmp = heightMap[x, z], tc = heightMap[x, z], ts = 1;
                    foreach (var item in GetNeiboursVector(x, z))
                    {
                        tc += heightMap[item.x, item.y];
                        ts++;
                    }
                    int tr = (int)Mathf.Round((tc * 1.0F - 0.1f * (5 - ts)) / ts);
                    // VS: int tr = (int)Mathf.Round((tc * 1.0F / ts - 0.1f * (5 - ts));
                    if (tmp != tr)
                    {
                        changed         = true;
                        heightMap[x, z] = tr;
                    }
                }
            }
        }
        for (int x = 0; x < size.x; x++)
        {
            for (int z = 0; z < size.y; z++)
            {
                GameObject ground = Instantiate(pGround, GameUtils.PositionToTranform(new Vector3Int(x, heightMap[x, z], z)), Quaternion.identity);
                ground.transform.SetParent(transform);
                this.map[x, z]              = ground.GetComponent <TerrainUnit>();
                this.map[x, z].position     = new Vector3Int(x, heightMap[x, z], z);
                this.map[x, z].worldManager = this;
            }
        }



        ///////////// Generate Static Terrains

        /////// Rocks
        int collapseNum = (int)(RD.NextDouble() * 0 + 1);

        // 1. collapse
        while (collapseNum-- > 0)
        {
        }
        PoissonDiscSampler sampler;
        int sampleOffset;

        /////// Voids
        // sampleOffset = 5;// 裁去边框
        // sampler = new PoissonDiscSampler(size.x - 2 * sampleOffset, size.y - 2 * sampleOffset, 5f);// 在少2倍边框区域内随机生成点
        // foreach (Vector2 sample in sampler.Samples())
        // {
        //     var dir = (int)(RD.NextDouble() * 4);
        //     Vector3Int dirVector;
        //     switch (dir)
        //     {
        //         case 0:
        //             dirVector = Vector3Int.right; break;
        //         case 1:
        //             dirVector = Vector3Int.left; break;
        //         case 2:
        //             dirVector = new Vector3Int(0, 0, -1); break;
        //         case 3:
        //         default:
        //             dirVector = new Vector3Int(0, 0, 1); break;
        //     }
        //     int i = 0, maxInter = 100;
        //     bool camPlace = true;
        //     while (maxInter-- > 0 && GetUnit((int)sample.x + i * dirVector.x + sampleOffset,
        //                    (int)sample.y + i * dirVector.z + sampleOffset) != null)
        //     {
        //         if (GetUnit((int)sample.x + i * dirVector.x + sampleOffset,
        //                     (int)sample.y + i * dirVector.z + sampleOffset).type != UnitType.Empty)
        //         {
        //             camPlace = false;
        //             break;
        //         }
        //         i++;
        //     }
        //     if (camPlace)
        //     {
        //         i = 1; maxInter = 100;
        //         while (maxInter-- > 0 && GetUnit((int)sample.x + i * dirVector.x + sampleOffset,
        //                   (int)sample.y + i * dirVector.z + sampleOffset) != null)
        //         {
        //             GetUnit((int)sample.x + i * dirVector.x + sampleOffset,
        //                         (int)sample.y + i * dirVector.z + sampleOffset).SetType(UnitType.Void);

        //             i++;
        //         }
        //     }
        // }

        ///////////// TEMPLATE bfs
        // foreach (var item in SpreadBFS(map[15, 15].position,
        //     (a, b) => ((a.position - b.position).magnitude < 2)
        // ))
        // {
        //     GetUnit(item).SetType(UnitType.Spawn);
        // }
        /////////////
        ///  BuffEffect be = GameObject.Find("TestBuff").GetComponent<BuffEffect>();
        // //buff test
        // be.AttachMesh(BuffEffectManager.GetLineByVectors(SpreadBFS(map[15, 15].position,
        //     (a, b) => ((a.position - b.position).magnitude < 2)
        // )));


        ///////////// generate Mines
        //  http://www.twinklingstar.cn/2013/406/stochastic-distributed-ray-tracing/
        //  Poisson Disk Distribution
        sampleOffset = 2;// 裁去边框
        sampler      = new PoissonDiscSampler(size.x - sampleOffset * 2, size.y - sampleOffset * 2, 14f);
        foreach (Vector2 sample in sampler.Samples())
        {
            // // Instantiate(pGround, new Vector3(sample.x,10,sample.y),Quaternion.identity);
            Vector2Int centerPos = new Vector2Int((int)sample.x + sampleOffset, (int)sample.y + sampleOffset);
            if ((centerPos - towerpos1).magnitude < 4 || (centerPos - towerpos2).magnitude < 4 || (centerPos - new Vector2Int(size.x / 2, size.y / 2)).magnitude < 4)
            {
                continue;
            }
            UnitType[,] mineM = StaticTerrain.NextModule();
            for (int _i = 0; _i < mineM.GetLength(0); _i++)
            {
                for (int _j = 0; _j < mineM.GetLength(1); _j++)
                {
                    if (mineM[_i, _j] != UnitType.Empty)
                    {
                        GetUnit(_i - mineM.GetLength(0) / 2 + centerPos.x, _j - mineM.GetLength(1) / 2 + centerPos.y).SetType(mineM[_i, _j]);
                    }
                }
            }
        }
        /////// Towers
        /** GOTO .Generate():1 */

        UnitType[,] tu1 = StaticTerrain.NextTower();
        for (int _i = 0; _i < tu1.GetLength(0); _i++)
        {
            for (int _j = 0; _j < tu1.GetLength(1); _j++)
            {
                GetUnit(_i - tu1.GetLength(0) / 2 + towerpos1.x, _j - tu1.GetLength(1) / 2 + towerpos1.y).SetType(tu1[_i, _j]);
            }
        }
        UnitType[,] tu2 = StaticTerrain.NextTower();
        for (int _i = 0; _i < tu2.GetLength(0); _i++)
        {
            for (int _j = 0; _j < tu2.GetLength(1); _j++)
            {
                GetUnit(_i - tu2.GetLength(0) / 2 + towerpos2.x, _j - tu2.GetLength(1) / 2 + towerpos2.y).SetType(tu2[_i, _j]);
            }
        }
        /////// Grasses
        sampler = new PoissonDiscSampler(size.x, size.y, 10f);
        foreach (Vector2 sample in sampler.Samples())
        {
            foreach (var item in SpreadBFS(new Vector3Int((int)sample.x, 0, (int)sample.y), (me, him) => (me.position - him.position).magnitude < 2f))
            {
                GetUnit(item).SetBuff(UnitBuffType.INCREASE_GRASS);
            }
        }

        ///////////// generate spawn point & player
        map[size.x / 2, size.y / 2].SetType(UnitType.Spawn);
        playerSpawnPoint = new Vector3(size.x / 2 + 0.5f, 15, (size.y / 2) + 0.5f);
        playerInstance   = Instantiate(playerPrefab, playerSpawnPoint, Quaternion.identity);
    }
コード例 #26
0
            /// <summary>
            ///     Тест Рабина Миллера. Имеет сильно псевдопростые числа
            /// </summary>
            /// <param name="source"></param>
            /// <param name="count"></param>
            /// <returns></returns>
            public static PrimalityTestResult MRPT(int source, int count)
            {
                if (count >= source)
                {
                    throw new InvalidOperationException("Число прогонов теста не должно быть меньше тестируемого числа.");
                }
                switch (source)
                {
                case 0:
                    return(PrimalityTestResult.Composite);

                case 1:
                    throw new InvalidOperationException("Единица не является ни простым, ни составным числом.");
                }

                if (source < 0 || count <= 0)
                {
                    throw new InvalidOperationException(
                              "Тестируемое число и число его прогонов должны быть положительными числами!");
                }

                //нам необходимо, чтобы число было нечетным, поэтому мы отсеиваем все четные числа.
                if (source % 2 == 0)
                {
                    return(PrimalityTestResult.Composite);
                }
                int t = source - 1;
                int s = 0;

                while (t % 2 == 0)
                {
                    t /= 2;
                    s++;
                }
                //n-1 = (2^s) * t


                BigInteger[] RestVariants = RD.UniformDistribution(2, source - 1, count);
                //отрезок [2,n-1]
                for (int i = 0; i < count; i++)
                {
                    BigInteger CurrentValue = RestVariants[i];
                    if (AdvancedEuclidsalgorithm.GCDResult(CurrentValue, source) != 1)
                    {
                        return(PrimalityTestResult.Composite);
                    }
                    //значение символа якоби
                    Comparison.LinearComparison comparison = new Comparison.LinearComparison(CurrentValue, source);
                    if (BigInteger.Abs((comparison = Comparison.MultiplicativeInverse.BinaryPowLinearComparison(comparison, t))
                                       .LeastModulo) == 1)
                    {
                        continue;
                    }

                    while (s != 1)
                    {
                        comparison = Comparison.MultiplicativeInverse.BinaryPowLinearComparison(comparison, 2);
                        if (comparison.LeastModulo == -1)
                        {
                            break;
                        }
                        if (--s == 0)
                        {
                            return(PrimalityTestResult.Composite);
                        }
                    }
                }

                return(PrimalityTestResult.Unknown);
            }
コード例 #27
0
 public void Enter()
 {
     RD.SetSeedS(int.Parse(inputField.GetComponent <Text>().text));
     SceneManager.LoadScene("MainMap");
 }
コード例 #28
0
 public void EnterRandom()
 {
     RD.SetSeedS(new System.Random().Next());
     SceneManager.LoadScene("MainMap");
 }