Ejemplo n.º 1
0
 public static void And_EmptyArray()
 {
     BitArray bitArray1 = new BitArray(0);
     BitArray bitArray2 = new BitArray(0);
     
     Assert.Equal(0, bitArray1.And(bitArray2).Length);
 }
Ejemplo n.º 2
0
        // BreakStmt
        public override bool Walk(BreakStatement node)
        {
            BitArray exit = PeekLoop();

            // break outside loop
            exit?.And(_bits);
            return(true);
        }
Ejemplo n.º 3
0
        public static void And_Operator(bool[] l, bool[] r, bool[] expected)
        {
            BitArray left = new BitArray(l);
            BitArray right = new BitArray(r);

            BitArray actual = left.And(right);
            Assert.Same(left, actual);
            Assert.Equal(actual.Length, expected.Length);

            for (int i = 0; i < expected.Length; i++)
            {
                Assert.Equal(expected[i], actual[i]);
            }
        }
Ejemplo n.º 4
0
        public void AddDependency(BitArray from, BitArray to)
        {
            if (from.Count != Keys.Count)
            {
                return;
            }
            if (to.Count != Keys.Count)
            {
                return;
            }
            to.And(Utils.Not(from));
            var index =
                DependencyList.FindIndex(tuple => tuple.Item1.EqualsTo(from));

            if (index != -1)
            {
                DependencyList[index].Item2.Or(to);
            }
            else
            {
                DependencyList.Add(new Tuple <BitArray, BitArray>(from, to));
            }
            _prepared = false;
        }
Ejemplo n.º 5
0
        public GameUnit GetOffset(BitArray tileType)
        {
            BitArray leftTopTall = TileInfo.CreateTileType();

            leftTopTall.Set((int)TileInfo.TileFlag.LeftSlope, true);
            leftTopTall.Set((int)TileInfo.TileFlag.TopSlope, true);
            leftTopTall.Set((int)TileInfo.TileFlag.TallSlope, true);
            BitArray rightBottomShort = TileInfo.CreateTileType();

            rightBottomShort.Set((int)TileInfo.TileFlag.RightSlope, true);
            rightBottomShort.Set((int)TileInfo.TileFlag.BottomSlope, true);
            rightBottomShort.Set((int)TileInfo.TileFlag.ShortSlope, true);
            if ((leftTopTall.And(tileType).IsEqual(leftTopTall)) ||
                (rightBottomShort.And(tileType).IsEqual(rightBottomShort)))
            {
                return(Units.TileToGame(1));
            }

            BitArray leftBottomTall = TileInfo.CreateTileType();

            leftBottomTall.Set((int)TileInfo.TileFlag.LeftSlope, true);
            leftBottomTall.Set((int)TileInfo.TileFlag.BottomSlope, true);
            leftBottomTall.Set((int)TileInfo.TileFlag.TallSlope, true);
            BitArray rightTopShort = TileInfo.CreateTileType();

            rightTopShort.Set((int)TileInfo.TileFlag.RightSlope, true);
            rightTopShort.Set((int)TileInfo.TileFlag.TopSlope, true);
            rightTopShort.Set((int)TileInfo.TileFlag.ShortSlope, true);
            if (leftBottomTall.And(tileType).IsEqual(leftBottomTall) ||
                rightTopShort.And(tileType).IsEqual(rightTopShort))
            {
                return(0.0f);
            }

            return(Units.HalfTile);
        }
        public static void Test()
        {
            Console.WriteLine();
            Console.WriteLine("Working With BitArray ");
            Console.WriteLine("".PadLeft(40, '='));

            BitArray arr = new BitArray(64);

            arr = new BitArray(new[] { true, true, true, true }); // value of 15
            arr = new BitArray(64);                               // length is 64 bit
            arr = new BitArray(8, true);                          // value of 255 , with array length 8 bit
            arr = new BitArray(new[] { 0x0F });                   // Value of 15 one int in the array is with the length of 32 bit.

            // convert to array of bool
            List <bool> bools = arr.OfType <bool>().ToList();

            Console.WriteLine(string.Join(", ", bools));

            // convert to array of int , each integer represent bit
            List <int> ints = arr.OfType <bool>().Select(b => b ? 1 : 0).ToList();

            Console.WriteLine(string.Join("", ints));


            var arrOr    = arr.Or(new BitArray(new[] { 0x0F }));
            var orResult = new int[1];

            arrOr.CopyTo(orResult, 0);
            Console.WriteLine($"{arrOr[0]:x2}");

            var arrAnd    = arr.And(new BitArray(new int[] { 0x0F }));
            var andResult = new int[1];

            arrAnd.CopyTo(orResult, 0);
            Console.WriteLine($"{arrAnd[0]:x2}");
        }
Ejemplo n.º 7
0
 static void Zadanie()
 {
     int[] U = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
     // __1__
     {
         BitArray A      = Bits_read(new int[] { 0, 2, 3, 4, 6, 7 }, U);
         BitArray B      = Bits_read(new int[] { 1, 2, 4, 5, 7, 8 }, U);
         BitArray C      = Bits_read(new int[] { 1, 3, 5, 7, 9 }, U);
         BitArray Result = (B.Or(C)).Not();
         Bits_write("1. ", Result, U);
     }
     {
         BitArray B      = Bits_read(new int[] { 4, 8 }, U);
         BitArray C      = Bits_read(new int[] { 1, 3, 5, 7, 9 }, U);
         BitArray Result = B.And(C.Not());
         Bits_write("2. ", Result, U);
     }
     {
         BitArray A      = Bits_read(new int[] { 1, 3, 6, 7, 9 }, U);
         BitArray C      = Bits_read(new int[] { 2, 4, 8 }, U);
         BitArray Result = A.Or(C);
         Bits_write("3. ", Result, U);
     }
 }
Ejemplo n.º 8
0
        static void SpecialOp3(ref BitArray A, ref BitArray A1, ref BitArray C, ref BitArray C1, HashSet <string> U)
        {
            BitArray opAC         = A.And(C);
            BitArray notC         = C.Not();
            BitArray opAnotC      = A1.And(notC);
            BitArray notA         = A1.Not();
            BitArray opNotAC      = notA.And(C);
            BitArray opUnionAC    = opAnotC.Or(opAC);
            BitArray opUnionallAC = opUnionAC.Or(opNotAC);
            BitArray total        = opUnionAC.Not();

            Console.Write("Задание №3: ");
            for (int i = 0; i < U.Count; i++)
            {
                if (total[i] == true)
                {
                    foreach (char el in U.ElementAt(i))
                    {
                        Console.Write(el + " ");
                    }
                }
            }
            Console.WriteLine();
        }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            BitArray arr1 = new BitArray(10);
            BitArray arr2 = new BitArray(10, true);

            bool[]   arrBool = new bool[] { true, false, true, false, true };
            BitArray arr3    = new BitArray(arrBool);

            Console.Write("Array Bool value: ");
            PrintBit(arr3, 5);

            byte[]   arrByte = new byte[] { 1, 2, 3, 4, 5 };
            BitArray arr4    = new BitArray(arrByte);

            Console.WriteLine("Array Byte length: {0} ", arr4.Length);
            Console.Write("Array Byte value: ");
            PrintBit(arr4, 8);


            int[]    arrInt = new int[] { 1, 2, 3, 4, 5 };
            BitArray arr5   = new BitArray(arrInt);

            Console.Write("Array Int value: ");
            PrintBit(arr5, 32);

            BitArray A = new BitArray(new bool[] { false, false, true, true });
            BitArray B = new BitArray(new bool[] { false, true, false, true });

            Console.WriteLine("Initial values");
            Console.Write("A:");
            PrintBit(A, 4);
            Console.Write("B:");
            PrintBit(B, 4);
            Console.Write("Result AND: ");
            PrintBit(A.And(B), 4);
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            //Question 1

            //ArrayList
            Console.WriteLine("ArrayList");
            ArrayList arraylist = new ArrayList();

            //arraylist.Add(13);
            //arraylist.Add(11);
            arraylist.Add("Asia");
            arraylist.Add("Ala");
            foreach (var item in arraylist)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("Liczba elementów, które ArrayLista może zawierać: {0}", arraylist.Capacity);
            Console.WriteLine("Liczba elementów: {0}", arraylist.Count);
            arraylist.Sort(); //tylko gdzy mam obiekty tego samego rodzaju, bo mogę mieć różne ale różnych nie mogę sortować
            foreach (var item in arraylist)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine();

            //Hashtable
            Console.WriteLine("Hashtable");
            Hashtable ht = new Hashtable();

            ht.Add("001", "Audi");
            ht.Add("002", "Pagani");
            ht.Add("003", "Lamborghini");
            ht.Add("004", "Nissan");
            ht.Add("005", "Volvo");
            ht.Add("006", null);
            if (ht.ContainsKey("005")) //jeśli istnieje klucz 005
            {
                Console.WriteLine("Wartość klucza 005 : {0}", ht["005"]);
            }
            if (ht.ContainsValue("Volvo"))// Możemy sprawdzić czy w kolekcji jest konkretna wartość
            {
                Console.WriteLine("Volvo jest elementem kolekcji");
            }
            // Pobierzemy teraz wszystkie klucze
            ICollection key = ht.Keys;

            foreach (string k in key)
            {
                Console.WriteLine("Klucz: {0} || wartość: {1}", k, ht[k]);
            }
            ht.Clear();                                                     //czyślimy całą zawartość
            Console.WriteLine("Pozostała liczba elementów: {0}", ht.Count); //0 elementów
            Console.WriteLine();

            //SortedList
            Console.WriteLine("SortedList ");
            SortedList sl = new SortedList();

            sl.Add("001", "Audi"); // Dodajemy pary: klucz/wartość
            sl.Add("002", "Pagani");
            sl.Add("005", "Volvo");
            sl.Add("004", "Nissan");      // element ten zostaje dodany do listy przed pozycją 005
            sl.Add("003", "Lamborghini"); // element ten zostaje dodany do listy przed powyższym elementem
            // Dostęp przez klucz -> jak HashTable
            if (sl.ContainsKey("004"))
            {
                Console.WriteLine("Wartość: {0}", sl["004"]);
            }
            // Dostęp przez wartość -> jak ArrayList
            if (sl.ContainsValue("Nissan"))
            {
                Console.WriteLine("Nissan jest elementem kolekcji");
            }
            ICollection keys = sl.Keys;

            foreach (string k in keys)
            {
                Console.WriteLine("Klucz: {0} || wartość: {1}", k, sl[k]);
            }
            Console.WriteLine();

            //Stack
            Console.WriteLine("Stack");
            Stack st = new Stack();

            st.Push("A");
            st.Push("B");
            st.Push("C");
            st.Push("D");
            // Nasz stos jest pełny. Zgodnie z definicją kolejny element powinien trafić na pierwszą pozycję
            st.Push("TEST");
            Console.WriteLine("Zawartość stosu: ");
            foreach (var item in st)
            {
                Console.WriteLine(item);
            }
            // usuwamy 2 pozycje
            st.Pop();                                              //usunie sie TEST
            st.Pop();                                              //usunie sie D
            // Możemy również zwrócić obiekt na szczycie stosu bez usuwania
            Console.WriteLine("Pierwszy element: {0}", st.Peek()); //C
            Console.WriteLine();

            //Queue
            Console.WriteLine("Queue");
            Queue q = new Queue();

            q.Enqueue("A");
            q.Enqueue("B");
            q.Enqueue("C");
            q.Enqueue("D");
            q.Dequeue(); //first-in, first-out. Pierwszy dodany el to pierwszy do usunięcia.Usuneliśmy A
            Console.WriteLine("Zawartość kolejki: ");
            foreach (var item in q)
            {
                Console.WriteLine(item);
            }
            // Spróbujmy jeszcze zobaczyć jaki element usuwamy
            string tekst = (string)q.Dequeue();

            Console.WriteLine("Usuneliśmy: {0}", tekst); //Usunelismy B
            Console.WriteLine();

            //BitArray
            Console.WriteLine("BitArray");
            // Tworzymy dwie tablice o rozmiarze 8 bitów
            BitArray ba1 = new BitArray(8);
            BitArray ba2 = new BitArray(8);

            byte[] a = { 60 };
            byte[] b = { 13 };
            // zapisujemy wartości w naszych tablicach
            ba1 = new BitArray(a);
            ba2 = new BitArray(b);
            // Zawartość pierwszej z nich
            Console.WriteLine("Tablica bitów ba: 60");
            for (int i = 0; i < ba1.Count; i++)
            {
                // Co oznacza poniższy zapis
                // Na każdy wyraz poświęcamy 6 znaków
                // Ale z wyrównianiem do lewej strony
                // Gdybyśmy zapis zmienili na {0, 6}
                // Wyrównanie byłoby do prawej strony
                Console.Write("{0, -6}", ba1[i]);
            }
            Console.WriteLine();
            // Zawartość drugiej z nich
            Console.WriteLine("Tablica bitów ba: 13");
            for (int i = 0; i < ba2.Count; i++)
            {
                Console.Write("{0, -6}", ba2[i]);
            }
            Console.WriteLine();
            // Połączmy teraz obie tablie operatorem logicznym AND
            BitArray ba3 = new BitArray(8);

            ba3 = ba1.And(ba2);
            Console.WriteLine("Tablica bitów ba3: ba1 i ba2");
            for (int i = 0; i < ba3.Count; i++)
            {
                Console.Write("{0, -6}", ba3[i]);
            }
            // Wynik działania programu
            // Tablica bitów ba: 60
            // False False True  True  True  True  False False
            // Tablica bitów ba: 13
            // True  False True  True  False False False False
            // Tablica bitów ba3: ba1 i ba2
            // False False True  True  False False False False
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Lists");
            // List is like an array but elements can be added and removed dynamically
            // The Generic Collection List<T> requires all elments to be of the same type T

            // Some List<T> methods:

            List <int> li = new List <int>();

            li.Add(56);
            li.Add(2);
            li.Add(1);
            li.Add(86);
            li.Add(6);
            li.Add(26);

            PrintList(li);

            li.RemoveAt(1);

            PrintList(li);

            li.Sort();

            PrintList(li);

            /*
             * some noteworthy List<T> methods:
             * Capacity: how much space is left before a resize becomes necessary[property]
             * Clear(): remove everything
             * TrimExcess(): set capacity to the actual number of elements, usefull to free memory
             * AddRange(IEnumerable coll): adds the elements of the collection coll to the end of the List<T> [same type required]
             *  IEnumerable  is the collections interface that supports simple iteration over the collection.
             * Insert (int i, T t): insert element t at position i
             * InsertRange(int i, IEnumerable coll): inserts the elements of a collection coll at a specific index i
             *  in List<T>
             * Remove(T t): Removes the first occourence of object t in the list
             * RemoveRange(int i, int count): guess...
             * Contains(T t): returns true if the specified element t is present in the list
             * IndexOf(T t): guess...
             * Reverse(): reverses the orger of the elements in the list
             * toArray(): Copies the elements of the list into a new array
             *
             */

            Console.WriteLine("SortedList<K,V>");

            /*
             * SortedList is a collection of key/value pairs sorted by key
             * Keys are used to retrieve the corresponding values.
             * Keys must be unique
             * All keys must be of the same type K and values must be of type V
             *
             * Some properties
             * Count - guess...
             * Item[K key] gets or sets the value associated to the specific key.
             *  Item is the indexer and is not required, you can use the brakets[]
             * Keys - gets a sorted and indexed collection containing only  the keys in a sorted list
             *
             * Some Methods:
             * Add(K key, V value) - adds an element with a specific key
             * Remove(K key) - removes the key/value pair with the specified key
             */

            SortedList <string, int> sl = new SortedList <string, int>();

            sl.Add("meaning of life", 42);
            sl.Add("A", 1);
            sl.Add("test", 123);
            PrintSortedList(sl);
            sl.Remove("A");
            PrintSortedList(sl);


            Console.WriteLine("BitArray");

            /*
             * Bit Array - Collection of bits
             * Usefull to represent a simple group of boolean flags
             *
             * Props:
             * Count
             * IsReadOnly
             *
             * Methods:
             * Get(int i)
             * Set(int i, bool value)
             * SetAll(bool value)
             * And(BitArray ba)
             * Or(BitArray ba)
             * Not()
             * Xor(BitArray ba)
             */

            BitArray ba1 = new BitArray(4);
            BitArray ba2 = new BitArray(4);

            ba1.SetAll(true);
            ba2.SetAll(false);

            PrintBarr("ba1", ba1);
            PrintBarr("ba2", ba2);
            Console.WriteLine();

            PrintBarr("ba1 And ba2", ba1.And(ba2));
            PrintBarr("Not ba2", ba1.Not());

            Console.ReadKey();
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            //LECCION 3
            //Se meten bytes como si fueran bits. (de 8 en 8)
            //Ojo se rellena el array con el bit menos significativo de cada byte
            BitArray bits = new BitArray(new byte[] { 1, 2, 4, 8, 16 });

            //Contar elementos.
            Console.WriteLine(bits.Count);
            listar(bits, "bits");
            Console.WriteLine("-------");

            //Obtener un bit en particular (según posicion)
            Console.WriteLine(bits.Get(0));
            Console.WriteLine(bits.Get(1));
            Console.WriteLine("-------");

            //Establecer valor de un bit según su posicion
            bits.Set(4, true);
            listar(bits, "bits");


            //LECCION 4
            //Clonación de bitarray (se necesita hacer un cast porque devuelve un objeto)
            BitArray bits2 = (BitArray)bits.Clone();

            Console.WriteLine("-------");
            listar(bits, "bitArray original");
            listar(bits2, "bitArray clonado");

            //invertimos arreglo con not
            Console.WriteLine("-------");
            listar(bits2, "bits2    ");
            listar(bits2.Not(), "not bits2"); //al hacer el not, se cambia el valor de bits2.
            listar(bits2, "bits2    ");

            //Otro arrayBit para hacer operaciones con el
            BitArray bits3 = new BitArray(new byte[] { 5, 7, 9, 13, 15 });
            BitArray temp;

            //OR
            Console.WriteLine("-------");
            temp = new BitArray(new byte[] { 4, 8, 19, 11, 15 });
            listar(temp, "temp     ");
            listar(bits3, "bits3    ");
            listar(temp.Or(bits3), "OR       ");

            //AND
            Console.WriteLine("-------");
            temp = new BitArray(new byte[] { 4, 8, 19, 11, 15 });
            listar(temp, "temp     ");
            listar(bits3, "bits3    ");
            listar(temp.And(bits3), "AND      ");

            //XOR
            Console.WriteLine("-------");
            temp = new BitArray(new byte[] { 4, 8, 19, 11, 15 });
            listar(temp, "temp     ");
            listar(bits3, "bits3    ");
            listar(temp.Xor(bits3), "XOR      ");


            Console.ReadKey();
        }
Ejemplo n.º 13
0
 private BitArray And() //3
 {
     ThirdOperand = new BitArray(FirstOperand);
     ThirdOperand.And(SecondOperand);
     return(ThirdOperand);
 }
 public FreezableBitArray And(BitArray other)
 {
     _CheckReadonly();
     m_ba.And(other);
     return(this);
 }
Ejemplo n.º 15
0
Archivo: Node.cs Proyecto: GotoK/H401
    // 隣接判定、ノードごとの処理
    public void NodeCheckAction(NodeController.NodeLinkTaskChecker Tc, _eLinkDir Link)
    {
        NodeDebugLog += "NodeCheckAction. CheckerID : " + Tc.ID + "\n";
        // チェック済みでスキップ
        if (bChecked) { Tc.Branch--; return; }

        // 各種変数定義
        bool bBranch = false;
        bChecked = true;
        Tc.SumNode++;
        bChain = false;

        // お隣さんを更新
        UpdateNegibor();

        // 状態表示
        Tc += (ToString() + "Action \n     Link : " + bitLink.ToStringEx() + "\nNegibor : " + Negibor.ToStringEx());
        Tc += Tc.NotFin + " : " + Tc.Branch.ToString();

        // チェックスタート
        // 接地判定(根本のみ)
        if (Link == _eLinkDir.NONE)     // 根本か確認
        {
            if (!bitLink[(int)_eLinkDir.RD] && !bitLink[(int)_eLinkDir.LD]) // 下方向チェック
            {
                Tc.Branch--;
                Tc.SumNode--;
                bChecked = false;
                return;                 // 繋がってないなら未チェックとして処理終了
            }
            // 繋がっている
            Tc += ("Ground");
        }

        // この時点で枝が繋がっている事が確定
        bChain = true;
        Tc.NodeList.Add(this);  // チェッカに自身を登録しておく

        // 終端ノードであれば、周囲チェック飛ばす
        var TempBit = new BitArray(6);
        // 除外方向設定
        TempBit.SetAll(false);
        if (Link == _eLinkDir.NONE)
        {
            TempBit.Set((int)_eLinkDir.RD, true);
            TempBit.Set((int)_eLinkDir.LD, true);
        }
        else {
            TempBit.Set((int)Link, true);
        }
        TempBit.And(bitLink).Xor(bitLink);    // 自身の道とAND後、自身の道とXOR。
        if (TempBit.isZero())                  // 比較して一致なら除外方向以外に道がない = XOR後に全0なら終端
        {
            Tc.Branch--;                      // 終端ノードであればそこで終了
            return;
        }

        // 周囲のチェック
        // この時点で、TempBitは先が壁の道を除いた自分の道を示している。
        Tc += "ExcludeFrom MyWay : " + TempBit.ToStringEx();

        for (int n = 0; n < (int)_eLinkDir.MAX; n++)
        {
            var TempBit2 = new BitArray(6);
            // 隣接ノードのうち、道が無い場所に自分の道が伸びてたらそこは途切れている。
            TempBit2 = TempBit.retAnd(Negibor.retNot());
            // ノード繋がってない
            if (TempBit2[n])
            {
                nodeControllerScript.unChainController.AddObj(this, (_eLinkDir)n);
                Tc.NotFin = true;                               // 隣と繋がってないので、枝未完成として登録
            }
        }

        Tc += ("Negibor : " + Negibor.ToStringEx());
        TempBit.And(Negibor);                       // 隣接ノードと繋がっている場所を特定
        Tc += "Linked : " + TempBit.ToStringEx();
        for (int n = 0; n < (int)_eLinkDir.MAX; n++)
        {
            if (!TempBit[n]) { continue; }          // ビット立ってないならスキップ

            // お隣さんと繋がっているので、処理引き渡しの準備
            bChain = true;

            // デバック表示
            Tc += ("Linked [" + LinkDirToString(n) + "]");

            // 接続先がおかしいならノーカンで
            Vec2Int Target = nodeControllerScript.GetDirNode(nodeID, (_eLinkDir)n);
            if (Target.x == -1) { continue; }

            // 分岐を検出してカウント
            if (!bBranch)
            {
                bBranch = true;     // 一回目ならノーカン
            }
            else {
                Tc.Branch++;        // 二回目以降は分岐なので、枝カウンタを+1
            }

            // 次へ引き渡す
            Node TgtNode = nodeControllerScript.GetNodeScript(Target);
            if (TgtNode.IsOutPuzzle)
            {
                Tc.Branch--;        // 接続先が壁なら処理飛ばして枝解決
            }
            else {
                // 周囲のActionをトリガーさせる
                Observable
                .Return(TgtNode)
                .Subscribe(_ => {
                    TgtNode.NodeCheckAction(Tc, (_eLinkDir)((n + 3 >= 6) ? (n + 3 - 6) : (n + 3)));
                }).AddTo(this);
            }
        }

        if (Tc.NotFin && Tc.Branch > 0)
        {
            Tc.Branch--;
        }
    }
Ejemplo n.º 16
0
        private void hideText(object sender, RoutedEventArgs e)
        {
            if (TextForHiding.Text.Length != 0)
            {
                var dialogWindow = new OpenFileDialog();
                dialogWindow.ShowDialog();
                dialogWindow.InitialDirectory = @"С:\\Users\Dell\Documents\ЗИиНИС\KP_ZIINIS\bin\Debug";
                try
                {
                    if (dialogWindow.FileName.Substring(dialogWindow.FileName.Length - 3, 3).Equals("wav"))
                    {
                        using (FileStream fstream = new FileStream(dialogWindow.FileName, FileMode.OpenOrCreate))
                        {
                            String bitsString     = stringToStringOfBits(TextForHiding.Text);
                            byte[] readBytesArray = new byte[bitsString.Length * 2];

                            BitArray mask = new BitArray(bitsString.Length * 2 * 8);
                            mask.SetAll(true);

                            for (int i = 0; i < mask.Length; i++)
                            {
                                if ((i) % 16 == 0)
                                {
                                    mask.Set(i, false);
                                }
                            }
                            BitArray bitsForHiding = new BitArray(bitsString.Length * 2 * 8);
                            bitsForHiding.SetAll(false);
                            for (int i = 0; i < bitsString.Length; i++)
                            {
                                if (bitsString[i].Equals('1'))
                                {
                                    bitsForHiding.Set(i * 16, true);
                                }
                            }
                            BitArray bits2;
                            fstream.Seek(44, SeekOrigin.Begin);
                            fstream.Read(readBytesArray, 0, readBytesArray.Length);
                            if (TextForHiding.Text.Length * 128 < fstream.Length)
                            {
                                bits2 = new BitArray(readBytesArray);
                                bits2.And(mask);
                                bits2.Xor(bitsForHiding);
                                fstream.Seek(44, SeekOrigin.Begin);

                                byte[] hidingbits = BitArrayToByteArray(bits2);
                                fstream.Write(hidingbits, 0, hidingbits.Length);

                                MessageBox.Show("Ваш текст спрятан");
                                TextForHidingLength.Text = TextForHiding.Text.Length.ToString();
                            }
                            else
                            {
                                MessageBox.Show("Введён слишком длинный текст");
                            }
                        }
                    }

                    else
                    {
                        MessageBox.Show("Выбран файл неверного формата, нужен формат .wav ");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Исключение: {ex.Message}");
                }
            }
            else
            {
                MessageBox.Show("Введите спрятанный текст");
            }
        }
Ejemplo n.º 17
0
        internal virtual void DoRandomSets(int maxSize, int iter, int mode)
        {
            BitArray   a0 = null;
            LongBitSet b0 = null;

            for (int i = 0; i < iter; i++)
            {
                int        sz = TestUtil.NextInt(Random(), 2, maxSize);
                BitArray   a  = new BitArray(sz);
                LongBitSet b  = new LongBitSet(sz);

                // test the various ways of setting bits
                if (sz > 0)
                {
                    int nOper = Random().Next(sz);
                    for (int j = 0; j < nOper; j++)
                    {
                        int idx;

                        idx = Random().Next(sz);
                        a.SafeSet(idx, true);
                        b.Set(idx);

                        idx = Random().Next(sz);
                        a.SafeSet(idx, false);
                        b.Clear(idx);

                        idx = Random().Next(sz);
                        a.SafeSet(idx, !a.Get(idx));
                        b.Flip(idx, idx + 1);

                        idx = Random().Next(sz);
                        a.SafeSet(idx, !a.SafeGet(idx));
                        b.Flip(idx, idx + 1);

                        bool val2 = b.Get(idx);
                        bool val  = b.GetAndSet(idx);
                        Assert.IsTrue(val2 == val);
                        Assert.IsTrue(b.Get(idx));

                        if (!val)
                        {
                            b.Clear(idx);
                        }
                        Assert.IsTrue(b.Get(idx) == val);
                    }
                }

                // test that the various ways of accessing the bits are equivalent
                DoGet(a, b);

                // test ranges, including possible extension
                int fromIndex, toIndex;
                fromIndex = Random().Next(sz / 2);
                toIndex   = fromIndex + Random().Next(sz - fromIndex);
                BitArray aa = (BitArray)a.Clone();
                aa.Flip(fromIndex, toIndex);
                LongBitSet bb = b.Clone();
                bb.Flip(fromIndex, toIndex);

                fromIndex = Random().Next(sz / 2);
                toIndex   = fromIndex + Random().Next(sz - fromIndex);
                aa        = (BitArray)a.Clone();
                aa.Clear(fromIndex, toIndex);
                bb = b.Clone();
                bb.Clear(fromIndex, toIndex);

                DoNextSetBit(aa, bb); // a problem here is from clear() or nextSetBit

                DoPrevSetBit(aa, bb);

                fromIndex = Random().Next(sz / 2);
                toIndex   = fromIndex + Random().Next(sz - fromIndex);
                aa        = (BitArray)a.Clone();
                aa.Set(fromIndex, toIndex);
                bb = b.Clone();
                bb.Set(fromIndex, toIndex);

                DoNextSetBit(aa, bb); // a problem here is from set() or nextSetBit

                DoPrevSetBit(aa, bb);

                if (b0 != null && b0.Length() <= b.Length())
                {
                    Assert.AreEqual(a.Cardinality(), b.Cardinality());

                    BitArray a_and = (BitArray)a.Clone();
                    a_and = a_and.And(a0);
                    BitArray a_or = (BitArray)a.Clone();
                    a_or = a_or.Or(a0);
                    BitArray a_xor = (BitArray)a.Clone();
                    a_xor = a_xor.Xor(a0);
                    BitArray a_andn = (BitArray)a.Clone();
                    a_andn.AndNot(a0);

                    LongBitSet b_and = b.Clone();
                    Assert.AreEqual(b, b_and);
                    b_and.And(b0);
                    LongBitSet b_or = b.Clone();
                    b_or.Or(b0);
                    LongBitSet b_xor = b.Clone();
                    b_xor.Xor(b0);
                    LongBitSet b_andn = b.Clone();
                    b_andn.AndNot(b0);

                    Assert.AreEqual(a0.Cardinality(), b0.Cardinality());
                    Assert.AreEqual(a_or.Cardinality(), b_or.Cardinality());

                    Assert.AreEqual(a_and.Cardinality(), b_and.Cardinality());
                    Assert.AreEqual(a_or.Cardinality(), b_or.Cardinality());
                    Assert.AreEqual(a_xor.Cardinality(), b_xor.Cardinality());
                    Assert.AreEqual(a_andn.Cardinality(), b_andn.Cardinality());
                }

                a0 = a;
                b0 = b;
            }
        }
Ejemplo n.º 18
0
    public static bool Contains(this BitArray a, BitArray rhs)
    {
        BitArray tmp = a.And(rhs);

        return(tmp.EqualsReal(rhs));
    }
Ejemplo n.º 19
0
        public static void OperatorTest(Operator op)
        {
            BitArray bitArray1 = new BitArray(6, false);
            BitArray bitArray2 = new BitArray(6, false);
            BitArray result;

            bitArray1.Set(0, true);
            bitArray1.Set(1, true);

            bitArray2.Set(1, true);
            bitArray2.Set(2, true);

            switch (op)
            {
                case Operator.Xor:
                    result = bitArray1.Xor(bitArray2);
                    Assert.Same(bitArray1, result);
                    Assert.True(result.Get(0));
                    Assert.False(result.Get(1));
                    Assert.True(result.Get(2));
                    Assert.False(result.Get(4));
                    break;

                case Operator.And:
                    result = bitArray1.And(bitArray2);
                    Assert.Same(bitArray1, result);
                    Assert.False(result.Get(0));
                    Assert.True(result.Get(1));
                    Assert.False(result.Get(2));
                    Assert.False(result.Get(4));
                    break;

                case Operator.Or:
                    result = bitArray1.Or(bitArray2);
                    Assert.Same(bitArray1, result);
                    Assert.True(result.Get(0));
                    Assert.True(result.Get(1));
                    Assert.True(result.Get(2));
                    Assert.False(result.Get(4));
                    break;
            }
            
            // Size stress cases.
            bitArray1 = new BitArray(0x1000F, false);
            bitArray2 = new BitArray(0x1000F, false);

            bitArray1.Set(0x10000, true); // The bit for 1 (2^0).
            bitArray1.Set(0x10001, true); // The bit for 2 (2^1).

            bitArray2.Set(0x10001, true); // The bit for 2 (2^1).

            switch (op)
            {
                case Operator.Xor:
                    result = bitArray1.Xor(bitArray2);
                    Assert.Same(bitArray1, result);
                    Assert.True(result.Get(0x10000));
                    Assert.False(result.Get(0x10001));
                    Assert.False(result.Get(0x10002));
                    Assert.False(result.Get(0x10004));
                    break;

                case Operator.And:
                    result = bitArray1.And(bitArray2);
                    Assert.Same(bitArray1, result);
                    Assert.False(result.Get(0x10000));
                    Assert.True(result.Get(0x10001));
                    Assert.False(result.Get(0x10002));
                    Assert.False(result.Get(0x10004));
                    break;

                case Operator.Or:
                    result = bitArray1.Or(bitArray2);
                    Assert.Same(bitArray1, result);
                    Assert.True(result.Get(0x10000));
                    Assert.True(result.Get(0x10001));
                    Assert.False(result.Get(0x10002));
                    Assert.False(result.Get(0x10004));
                    break;
            }
        }
Ejemplo n.º 20
0
        public static void Subtract(BitArray a, BitArray b)   // a = a - b
        {
            BitArray c = (BitArray)b.Clone();

            a.And(c.Not());
        }
Ejemplo n.º 21
0
        public static void And_Invalid()
        {
            BitArray bitArray1 = new BitArray(11, false);
            BitArray bitArray2 = new BitArray(6, false);

            // Different lengths
            Assert.Throws<ArgumentException>(null, () => bitArray1.And(bitArray2));
            Assert.Throws<ArgumentException>(null, () => bitArray2.And(bitArray1));

            Assert.Throws<ArgumentNullException>("value", () => bitArray1.And(null));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Create reachability matrix of all pods
        ///     egressMatrix takes egress pods as row and ingress pods as column
        ///     ingressMatrix takes ingress pods as row and egress pods as column
        ///     egressMatrix is the transpose of ingressMatrix
        ///
        /// PodA can send traffic to podB if and only if.
        /// podA is allowed to send traffic to podB and podB is allowed to receive traffic from podA.
        /// </summary>
        /// <param name="pods">all pods.</param>
        /// <param name="policies">all policies.</param>
        /// <param name="namespaces">all namespaces.</param>
        /// <returns>two reachability matrices and three BCP matrices.</returns>
        public static (Zen <IList <bool> >[] egressMatrix, Zen <IList <bool> >[] ingressMatrix, Zen <IList <bool> >[] podPolMatrix, Zen <IList <bool> >[] polPodAllowedMatrix, Zen <IList <bool> >[] polPodSelectedMatrix) CreateReachMatrix(Zen <Pod>[] pods, Zen <Policy>[] policies, Zen <Namespace>[] namespaces)
        {
            var n = pods.Length;
            var m = policies.Length;
            // BCP
            var selectedPolicies = new bool[n, m];
            var allowedPods      = new bool[m, n];
            var selectedPods     = new bool[m, n];
            /***********************ns filter*********************/
            // Create ns-pod mapping
            Dictionary <int, BitArray> nsMatrix = new Dictionary <int, BitArray>();

            for (int i = 0; i < n; ++i)
            {
                var ns   = pods[i].GetNS();
                var hash = ns.GetHashCode();
                if (!nsMatrix.ContainsKey(hash))
                {
                    nsMatrix[hash] = new BitArray(n);
                }
                nsMatrix[hash].Set(i, true);
            }
            // Create label-ns mapping
            var nsSize = namespaces.Length;
            Dictionary <int, BitArray> nsLabelHash = new Dictionary <int, BitArray>();

            for (int i = 0; i < nsSize; ++i)
            {
                var keys = namespaces[i].GetLabelKeys();
                var k    = keys.Length();
                // iterate over Zen<List> to traverse all labels
                for (k -= 1; !k.EqualToNumber(ushort.MaxValue); k -= 1)
                {
                    var keyHash = keys.At(k).Value().GetHashCode();
                    if (!nsLabelHash.ContainsKey(keyHash))
                    {
                        nsLabelHash[keyHash] = new BitArray(nsSize);
                    }
                    nsLabelHash[keyHash].Set(i, true);
                }
            }
            /*****************************************************/

            // Create label-pod mapping
            Dictionary <int, BitArray> labelHash = new Dictionary <int, BitArray>();

            // ingress policy matrix
            BitArray[] ingressReachMatrix = new BitArray[n];
            // egress policy matrix
            BitArray[] egressReachMatrix = new BitArray[n];
            for (int i = 0; i < n; ++i)
            {
                // initialize reachability matrix to allow all traffic (default behavior)
                ingressReachMatrix[i] = new BitArray(n, true);
                egressReachMatrix[i]  = new BitArray(n, true);

                var keys = pods[i].GetKeys();
                var k    = keys.Length();
                for (k -= 1; !k.EqualToNumber(ushort.MaxValue); k -= 1)
                {
                    var keyHash = keys.At(k).Value().GetHashCode();
                    if (!labelHash.ContainsKey(keyHash))
                    {
                        labelHash[keyHash] = new BitArray(n);
                    }
                    labelHash[keyHash].Set(i, true);
                }
            }
            // record which pods have been selected
            // if a pod has not been selected, it by default allows all traffic
            var podSelected = new bool[n];

            // Traverse all policies to create reachability matrix
            for (int i = 0; i < m; ++i)
            {
                // bitvector of selected pods (keys of labels only)
                var selectSet = new BitArray(n, true);
                // if policy is in a namespace which has no pods, this policy is void (no pods can be selected)
                if (!nsMatrix.ContainsKey(policies[i].GetNS().GetHashCode()))
                {
                    continue;
                }
                // else select pods only in the namespace of the policy
                selectSet.And(nsMatrix[policies[i].GetNS().GetHashCode()]);

                var keys = policies[i].GetSelectKeys();
                var k    = keys.Length();
                for (k -= 1; !k.EqualToNumber(ushort.MaxValue); k -= 1)
                {
                    var keyHash = keys.At(k).Value().GetHashCode();
                    // if a label(key) doesn't exist in all pods, no pods are selected
                    if (!labelHash.ContainsKey(keyHash))
                    {
                        selectSet.SetAll(false);
                        break;
                    }
                    // else intersect with pods under the key
                    selectSet = selectSet.And(labelHash[keyHash]);
                }

                // bitvector of allowed ns
                var allowNSSet = new BitArray(nsSize);
                // bitvector of allowed pods
                var allowSet = new BitArray(n);
                {
                    // get all namespaces that match label key of allowed ns
                    var allowNSKeys   = policies[i].GetAllowNSKeys();
                    var allowNSLabels = policies[i].GetAllowNS();
                    k = allowNSKeys.Length();
                    // if this policy is deny all, no pods are allowed to/from selected pods
                    if (policies[i].GetDenyAll().Equals(True()))
                    {
                        allowSet.SetAll(false);
                    }
                    // if this policy is allow all, all pods are allowed to/from selected pods
                    else if (policies[i].GetAllowAll())
                    {
                        allowSet.SetAll(true);
                    }
                    // if no labels of allowed ns is defined in the policy,
                    // namespace of the policy will be used as allowed ns
                    else if (k.EqualToNumber(0))
                    {
                        allowSet.Or(nsMatrix[policies[i].GetNS().GetHashCode()]);
                    }
                    // else tranverse all labels of allowed ns
                    else
                    {
                        // Get ns matchs all keys of allowed labels
                        for (k -= 1; !k.EqualToNumber(ushort.MaxValue); k -= 1)
                        {
                            var keyHash = allowNSKeys.At(k).Value().GetHashCode();
                            if (!nsLabelHash.ContainsKey(keyHash))
                            {
                                allowNSSet.SetAll(false);
                                break;
                            }
                            allowNSSet.Or(nsLabelHash[keyHash]);
                        }
                        // Check if selected namespaces have same label values as required in policy
                        for (int j = 0; j < nsSize; ++j)
                        {
                            if (allowNSSet.Get(j))
                            {
                                var nsLabels = namespaces[j].GetLabels();
                                k = allowNSKeys.Length();
                                for (k -= 1; !k.EqualToNumber(ushort.MaxValue); k -= 1)
                                {
                                    var key = allowNSKeys.At(k).Value();
                                    // if label value is not matched, this ns is not allowed
                                    if (!allowNSLabels.Get(key).Value().GetHashCode().Equals(nsLabels.Get(key).Value().GetHashCode()))
                                    {
                                        allowNSSet.Set(j, false);
                                        break;
                                    }
                                }
                            }
                            // allowed pods can be only in the allowed ns
                            if (allowNSSet.Get(j))
                            {
                                allowSet.Or(nsMatrix[namespaces[j].GetName().GetHashCode()]);
                            }
                        }
                    }
                }

                var labels = policies[i].GetAllowLabels();
                keys = policies[i].GetAllowKeys();
                k    = keys.Length();
                // tranverse labels(key) of allowed pods
                // intersect pods under required labels(key)
                for (k -= 1; !k.EqualToNumber(ushort.MaxValue); k -= 1)
                {
                    var keyHash = keys.At(k).Value().GetHashCode();
                    if (!labelHash.ContainsKey(keyHash))
                    {
                        allowSet.SetAll(false);
                        break;
                    }
                    allowSet = allowSet.And(labelHash[keyHash]);
                }
                // check if pods have the same label values as required
                for (int j = 0; j < n; ++j)
                {
                    if (allowSet.Get(j))
                    {
                        k = keys.Length();
                        var podLabels = pods[j].GetLabels();
                        for (k -= 1; !k.EqualToNumber(ushort.MaxValue); k -= 1)
                        {
                            var key   = keys.At(k).Value();
                            var value = labels.Get(key).Value();
                            if (!podLabels.Get(key).Value().StringValue().Equals(value.StringValue()))
                            {
                                allowSet.Set(j, false);
                                break;
                            }
                        }
                    }
                    // update BCP policy-pod mapping
                    if (allowSet.Get(j))
                    {
                        allowedPods[i, j] = true;
                    }
                }

                labels = policies[i].GetSelectLabels();
                keys   = policies[i].GetSelectKeys();
                var reachMatrix = ingressReachMatrix;
                if (!policies[i].GetIngress().Equals(True()))
                {
                    reachMatrix = egressReachMatrix;
                }
                // tranverse labels(key) of pod selector
                // intersect pods under required labels(key)
                for (int j = 0; j < n; ++j)
                {
                    if (selectSet.Get(j))
                    {
                        k = keys.Length();
                        var podLabels = pods[j].GetLabels();
                        for (k -= 1; !k.EqualToNumber(ushort.MaxValue); k -= 1)
                        {
                            var key   = keys.At(k).Value();
                            var value = labels.Get(key).Value();
                            if (!podLabels.Get(key).Value().StringValue().Equals(value.StringValue()))
                            {
                                selectSet.Set(j, false);
                                break;
                            }
                        }
                    }

                    if (selectSet.Get(j))
                    {
                        // if this pod has not been selected before, set all its reach bits to 0
                        if (!podSelected[j])
                        {
                            podSelected[j] = true;
                            ingressReachMatrix[j].SetAll(false);
                            egressReachMatrix[j].SetAll(false);
                            // intra-pod traffic is always allowed
                            ingressReachMatrix[j].Set(j, true);
                            egressReachMatrix[j].Set(j, true);
                        }
                        // update BCP selected mapping
                        selectedPolicies[j, i] = true;
                        selectedPods[i, j]     = true;
                        // allow pods to/from selected pod
                        reachMatrix[j] = reachMatrix[j].Or(allowSet);
                    }
                }
            }
            // only ingress policy allows podA to receive traffic from podB
            // and egress policy allows podB to send traffic to podA
            // podA can receive traffic from podB
            ingressReachMatrix.Transpose();
            for (int i = 0; i < n; ++i)
            {
                egressReachMatrix[i].And(ingressReachMatrix[i]);
            }

            // ingress matrix is transpose of egress matrix
            ingressReachMatrix = egressReachMatrix.Select(v => (BitArray)v.Clone()).ToArray();
            ingressReachMatrix.Transpose();
            // create Zen data:
            // 1. egress matrix
            // 2. ingress matrix
            // 3. BCP pod-policy mapping
            // 4. BCP policy-pod allowed mapping
            // 5. BCP policy-pod selected mapping
            Zen <IList <bool> >[] eMx              = new Zen <IList <bool> > [n];
            Zen <IList <bool> >[] inMx             = new Zen <IList <bool> > [n];
            Zen <IList <bool> >[] podPolMx         = new Zen <IList <bool> > [n];
            Zen <IList <bool> >[] polPodAllowedMx  = new Zen <IList <bool> > [m];
            Zen <IList <bool> >[] polPodSelectedMx = new Zen <IList <bool> > [m];
            for (int i = 0; i < n; ++i)
            {
                var tmp = new bool[n];
                egressReachMatrix[i].CopyTo(tmp, 0);
                eMx[i] = tmp;
                ingressReachMatrix[i].CopyTo(tmp, 0);
                inMx[i] = tmp;
                // BCP pod-policy mapping
                podPolMx[i] = Enumerable.Range(0, m).Select(x => selectedPolicies[i, x]).ToArray();
            }
            for (int i = 0; i < m; ++i)
            {
                // BCP policy-pod mapping
                polPodAllowedMx[i]  = Enumerable.Range(0, n).Select(x => allowedPods[i, x]).ToArray();
                polPodSelectedMx[i] = Enumerable.Range(0, n).Select(x => selectedPods[i, x]).ToArray();
            }
            return(eMx, inMx, podPolMx, polPodAllowedMx, polPodSelectedMx);
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            /* Generics - allows the reuse of code across different types.
             * For example, let's declare a method that swaps the values of its two parameters
             *
             * static void Swap(ref int a, ref int b)
             * {
             *  int temp = a;
             *  a = b;
             *  b = temp;
             * }
             *
             * Our Swap method will work only for integer parameter. If we want to use it for other types, for example, doubles or strings,
             * we have to overload it for all the types we want to use it with. Beside a lot of code repetition, it becomes harder to
             * manage the code because changes in one method mean changes to all of the overloaded methods.
             * Generics provide a flexible mechanism to define a generic type.
             * example line(12)
             *
             * static void Swap<T>(ref T a, ref T b)
             * {
             *  T temp = a;
             *  a = b;
             *  b = temp;
             * }
             *
             * In the above code, T is the name of our generic type, We can name it anything we want, but T is a commonly used name. Our Swap method
             * now takes two parameters of type T. We also use the T type for our temp variable that is used to swap the values.
             *
             * Note the brackets in the syntax <T>, which re used to define a generic type.
             * We can now use our Swap method with different types, as in below and line(12)
             */
            int a = 4, b = 9;

            Swap <int>(ref a, ref b);
            Console.WriteLine(a + " " + b); //output 9 4

            string x = "Hello";
            string y = "World!";

            Swap <string>(ref x, ref y);
            Console.WriteLine(x + " " + y); //output  World Hello

            /*When calling a generic method, we need to specify the type it will work with by using brackets. So when Swap<int> is called, the T type
             * is replaced by int. For Swap<string>, T is replace by string.
             * If you omit specifying the type when calling a generic method, the compiler will use the type based on the arguments passed to the method
             *
             * Mulitiple generic parameters can be used with a single method.
             * For example: Func<T, U> takes two different generic types.
             */



            /* Generic Classes -
             * generic types can also be used with classes. The most common use for generic classes is with collections of items, where operations such as
             * adding and removing items from the collection are performed in basically the same way regardless of the type of data being stored.
             *  One type of collection is called a stack. Items are "pushed", or added to the collection, and "popped", or removed from the collection.
             *  A stack is sometimes called a Last in First Out(LIFO) data structure.
             * for example - line(20)
             *
             * The generic class stores elements in an array. As you can see, the generic type T is used as the type of the array, the parameter
             * type for the Push method, and the return type for the Pop and Get methods.
             * Now we can create objects of our generic class as below
             */
            Stack <int>    IntStack = new Stack <int>();
            Stack <string> strStack = new Stack <string>();
            //Stack<Person> PersonStack = new Stack<Person>()

            /*We can also use the generic class with custom types, such as the custom defined Person type.
             * In a generic class we do not need to define the generic type for its methods, because the generic type is already defined on the class level.
             * Generic class methods are called the same as for any other object.
             */
            Stack <int> intStack2 = new Stack <int>();

            intStack2.Push(3);
            intStack2.Push(6);
            intStack2.Push(7);
            Console.WriteLine(intStack2.Get(1));



            /*C# Collections
             * A collection is used to group related objects. Unlike an array, it is dynamic and can also group objects. A collection can grow
             * and shrink to accommodate any number of objects. Collection classes are organized into namespaces and contain built in methods for
             * processing elements within the collection.
             * A collection organizes related data in a computer so that it can be used efficiently.
             * Different kinds of collections are suited to different kinds of applications and some are highly specialized to specific tasks.
             * For example,
             * Dictionaries are used to represent connections on social websites (such as Twitter, Facebook),
             * Queues can be used to create task schedulers,
             * HashSets are used in searching algorithms, etc
             *
             * A collection typically includes methods to add, remove and count objects.
             * The for statement and foreach statement are used to iterate through collections. Since a collection is a class you must first declare an
             * instance of the class before you can add elements to that collection.
             * For example as below
             * List<int> li = new List<int>();
             *
             * Collections provide a more flexible way to work with groups of objects. Unlike arrays, the group of objects you work with can grow and shrink
             * dynamically as the needs of the application change
             *
             *
             * Generic Collections
             * Generic collections are the preferred type to use as long as every element in the collection is of the same data type. Only desired data types can
             * can be added to a generic collection and this is enforced by using strong typing which reduces the possibility of errors.
             * The .NET framework provides a number of generic collection classes, useful for storing and manipulating data.
             * The System.Collections.Generic namespace includes the following generic collections:
             * - List<T>
             * - Dictionary<TKey, TValue>
             * - SortedList<TKey, TValue>
             * - Stack<T>
             * - Queue<T>
             * - Hashset<T>
             *
             * To access a generic collection in your code, you will need to include the statement: using System.Collections.Generic;
             *
             *
             * Non-Generic Collections -
             * Non-generic collections can store items that are of type Object. Since an Object data type can refer to any data type,
             * you run the risk of unexpected outcomes. Non-generic collections may also be slower to access as well as execute.
             * The System.Collections namespace includes the following non-generic collections:
             * - ArrayList
             * - SortedList
             * - Stack
             * - Queue
             * - Hashtable
             * - BitArray
             *
             * Because non-generic collections are error prone and less performant, it is recommended to always use generic collections from the
             * System.Collections.Generic namespace if available and to avoid using legacy collections from the System.Collections namespace
             *
             */


            /*Lists and BitArray
             * - List<T> - A list is similar to an array, but the elements in a list can be inserted and removed dynamically.
             * C# generic collection List<T> class requires all elements be of the same type T.
             *
             * List<T> properties and methods include:
             * - Count : A property that gets the number of elements contained in the list
             * - Item[int i] : Gets or sets the element in the list at the index i. Item is the indexer and is not required when accessing an element. You only
             *   need to use the brackets[] and the index value inside the brackets.
             * - Add(T t) : Adds an element t to the end of the list.
             * - RemoveAt(int index) : Removes the element at the specified position (index) from the list.
             * - Sort() : Sorts elements in the list
             * See few examples of List<T> below
             */
            List <int> li = new List <int>();

            li.Add(59);
            li.Add(72);
            li.Add(95);
            li.Add(5);
            li.Add(9);
            li.Remove(1); //removes 72

            Console.Write("\nList: ");
            for (int xi = 0; xi < li.Count; xi++)
            {
                Console.Write(li[xi] + " "); //59, 95, 5, 9
            }
            li.Sort();
            Console.Write("\nSorted: ");
            for (int xi = 0; xi < li.Count; xi++)
            {
                Console.Write(li[xi] + " "); // 5 9 59 95
            }

            /*Additional List<T> properties and methods are listed below. Try them out by adding them to the List<T> example code above.
             * - Capacity : A property that gets the number of elements the list can hold before needing to be resized
             * - Clear() : Removes all the elements from the list
             * - TrimExcess() : Sets the capacity to the actual number of elements in the list. This is useful when trying to reduce memory overhead.
             * - AddRange(IEnumerable coll) : Adds the elements of collection coll with elements of the same type as List<T> to the end of the list. IEnumerable
             *   is the collections interface that supports simple iteration over the collection.
             * - Insert(int i, T t) : inserts an element t at a specific index i in the list
             * - InsertRange(int i, IEnumerable coll) : Inserts the elements of a collection coll at a specified index i in the list. IEnumerable is the collections
             *   interface that supports simple iteration over the collection.
             * - Remove(T t) : Removes the first occurence of the object t from the list.
             * - RemoveRange(int i, int count) : Removes a specified number of elements count from the list starting at a specified index i.
             * - Contains(T t) : Returns true if the specified element t is present in the list
             * - IndexOf(T t) : Returns the index of the first occurrence of the element t in the list.
             * - Reverse() : Reverses the order of the elements in the list
             * - ToArray() : Copies the elements of the list into a new array
             *
             */

            /*SortedList<k,V>
             * A sorted list is a collection of key/value pairs that are sorted by key. A key can be used to access its corresponding value in the sorted list
             * C# generic collection SortedList<K, V> class requires all element key/value pairs to be of the same type K, V. Duplicate keys are not permitted,
             * which ensures that every key/value pair is unique.
             *
             * SortedList<k, V> properties include:
             * - Count : Gets the number of key/value pairs contained in the sorted list
             * - Item[K key] : Gets or sets the value associated with the specified key contained in the sorted list. Item is the indexer and is not required
             *   when accessing an element. You only need to use the brackets[] and the key, value.
             * - key : Gets a sorted and indexed collection containing only the keys in the sorted list
             *
             * SortedList<K, V> methods include:
             * - Add(K key, V value) : Adds an element with a specific key, value pair into the sorted list.
             * - Remove(K key) : Removes the element with the specific key, value pair associated with the specified key from the sorted list.
             * example os SortedList below
             */
            SortedList <string, int> s1 = new SortedList <string, int>();

            s1.Add("Stanley", 59);
            s1.Add("the", 95);
            s1.Add("Ikechukwu", 72);
            s1.Remove("the");
            Console.WriteLine("Sorted List: ");
            foreach (string s in s1.Keys)
            {
                Console.WriteLine(s + ": " + s1[s]);   //Ikechukwu: 72 Stanley: 59
            }
            Console.WriteLine("\nCount: " + s1.Count); //Count: 2

            /*Here are additional SortedList<K, V> properties and methods:
             * - Values : Gets a sorted and indexed collection of the values in the sorted list
             * - Clear() : removes all the elements from the sorted list
             * - ContainsKey(K key) : Returns true when the specified key is present in the sorted list
             * - IndexOfKey(K key) : Returns the index of the specified key within the sorted list
             * - IndexOfValue(V value) : Returns the index of the specified value within the sorted list
             */

            /*BitArray
             * A bit array is a collection of bits. The value of a bit can be either 0 (off/false) or 1 (on/true).
             * Bit array compactly store bits. Most commonly, they are used to represent a simple group of boolean flags or an ordered sequence of boolean
             * values.
             * BitArray Properties includes:
             * - Count : Gets the number of bits in the bit array
             * - IsReadOnly : Gets a value indicating if the bit array is read only or not
             *
             * BitArray methods include:
             * - Get(int i) : Gets the value of the bit at a specified position i in the bit array.
             * - Set(int i, bool value) : Sets the bit at a specified position i to a specified value in the bit array
             * - SetAll(bool value) : Sets all the bits to a specified value in the bit array.
             * - And(BitArray ba) : Performs the bitwise AND operation on the elements of the bit array object with a specified bit array ba.
             * - Or(BitArray ba) : Performs the bitwise OR operation on the elements of the bit array and the specified bit array ba
             * - Not() : Inverts the bit values of the bit array.
             * - Xor(BitArray ba) : Performs the bitwise XOR operation on the elements of the current bit array object and the elements in the specified bit array ba
             * see examples on properties and methods of bitArray class below and line (42)
             */
            BitArray ba1 = new BitArray(4);
            BitArray ba2 = new BitArray(4);

            ba1.SetAll(true);
            ba2.SetAll(false);

            ba1.Set(2, false);
            ba2.Set(3, true);

            PrintBar("ba1", ba1);
            PrintBar("ba2", ba2);
            Console.WriteLine();

            PrintBar("ba1 AND ba2", ba1.And(ba2));
            PrintBar(" Not ba2", ba2.Not());
            //one use case of BitArrays is in image processing to store the individual bits of a gray-scale image
        }
Ejemplo n.º 24
0
 public BitArray BitArrayAnd() => _original.And(_original2);
Ejemplo n.º 25
0
    public virtual bool runTest()
    {
        Console.Out.WriteLine("Plain\\System_NewCollections\\BitArray\\Co1550And.cs  runTest() started.");
        int      iCountErrors    = 0;
        int      iCountTestcases = 0;
        BitArray ba2             = null;
        BitArray ba3             = null;
        BitArray ba4             = null;

        ba2 = new BitArray(6, false);
        ba3 = new BitArray(6, false);
        ba2.Set(0, true);
        ba2.Set(1, true);
        ba3.Set(1, true);
        ba3.Set(2, true);
        ba4 = ba2.And(ba3);
        ++iCountTestcases;
        if (ba4.Get(0))
        {
            ++iCountErrors;
            Console.Error.WriteLine("POINTTOBREAK: find error E_09pv (Co1550And)");
            Console.Error.WriteLine("EXTENDEDINFO: 1 & 0 (E_09pv ,Co1550And)");
        }
        ++iCountTestcases;
        if (!ba4.Get(1))
        {
            ++iCountErrors;
            Console.Error.WriteLine("POINTTOBREAK: find error E_96hf (Co1550And)");
        }
        ++iCountTestcases;
        if (ba4.Get(2))
        {
            ++iCountErrors;
            Console.Error.WriteLine("POINTTOBREAK: find error E_84si (Co1550And)");
        }
        ++iCountTestcases;
        if (ba4.Get(4))
        {
            ++iCountErrors;
            Console.Error.WriteLine("POINTTOBREAK: find error E_79kn (Co1550And)");
        }
        ba2 = new BitArray(0x1000F, false);
        ba3 = new BitArray(0x1000F, false);
        ba2.Set(0x10000, true);
        ba2.Set(0x10001, true);
        ba3.Set(0x10001, true);
        ba3.Set(0x10002, true);
        ba4 = ba2.And(ba3);
        ++iCountTestcases;
        if (ba4.Get(0x10000))
        {
            ++iCountErrors;
            Console.Error.WriteLine("POINTTOBREAK: find error E_61ah (Co1550And)");
        }
        ++iCountTestcases;
        if (!ba4.Get(0x10001))
        {
            ++iCountErrors;
            Console.Error.WriteLine("POINTTOBREAK: find error E_52xd (Co1550And)");
        }
        ++iCountTestcases;
        if (ba4.Get(0x10002))
        {
            ++iCountErrors;
            Console.Error.WriteLine("POINTTOBREAK: find error E_47op (Co1550And)");
        }
        ++iCountTestcases;
        if (ba4.Get(0x10004))
        {
            ++iCountErrors;
            Console.Error.WriteLine("POINTTOBREAK: find error E_54ja (Co1550And)");
        }
        try
        {
            BitArray b1 = new BitArray(0);
            BitArray b2 = new BitArray(0);
            b1.And(b2);
        }
        catch (Exception exc)
        {
            ++iCountErrors;
            Console.WriteLine("Err_001, Exception was not expected " + exc);
        }
        ba2 = new BitArray(11, false);
        ba3 = new BitArray(6, false);
        try
        {
            ++iCountTestcases;
            ba4 = ba2.And(ba3);
            ++iCountErrors;
            Console.Error.WriteLine("POINTTOBREAK: find error E_66vc (Co1550And)");
        }
        catch (ArgumentException) {}
        catch (Exception)
        {
            ++iCountErrors;
            Console.Error.WriteLine("POINTTOBREAK: find error E_58jq (Co1550And)");
        }
        ba2 = new BitArray(6, false);
        ba3 = new BitArray(11, false);
        try
        {
            ++iCountTestcases;
            ba4 = ba2.And(ba3);
            ++iCountErrors;
            Console.Error.WriteLine("POINTTOBREAK: find error E_432k (Co1550And)");
        }
        catch (ArgumentException) {}
        catch (Exception)
        {
            ++iCountErrors;
            Console.Error.WriteLine("POINTTOBREAK: find error E_452a (Co1550And)");
        }
        ba2 = new BitArray(6, false);
        ba3 = null;
        try
        {
            ++iCountTestcases;
            ba4 = ba2.And(ba3);
            ++iCountErrors;
            Console.Error.WriteLine("POINTTOBREAK: find error E_72dg (Co1550And)");
        }
        catch (ArgumentNullException) {}
        catch (Exception)
        {
            ++iCountErrors;
            Console.Error.WriteLine("POINTTOBREAK: find error E_93kx (Co1550And)");
        }
        if (iCountErrors == 0)
        {
            Console.Error.Write("BitArray\\Co1550And.cs: paSs.  iCountTestcases==");
            Console.Error.WriteLine(iCountTestcases);
            return(true);
        }
        else
        {
            Console.Error.Write("Co1550And.cs iCountErrors==");
            Console.Error.WriteLine(iCountErrors);
            Console.Error.WriteLine("PATHTOSOURCE: BitArray\\Co1550And.cs   FAiL !");
            return(false);
        }
    }
        public virtual bool ReflexCompatible(GameActor actor, ReflexData reflex, ProgrammingElement replacedElement, bool allowArchivedCategories)
        {
            // Check actor compatibility
            {
                if (!this.ActorCompatible(actor))
                {
                    return(false);
                }
            }

            // Build datatype bitmask
            {
                string selectionUpid = (replacedElement != null) ? replacedElement.upid : null;

                scratchOutputs.SetAll(false);
                scratchNegOutputs.SetAll(false);

                // Set sensor bits
                if (reflex.Sensor != null)
                {
                    scratchOutputs.Or(reflex.Sensor.Outputs);
                }
                else
                {
                    // if no sensor, simulate a boolean output type (for "always" behavior).
                    scratchOutputs.Set((int)SensorOutputType.Boolean, true);
                }
                // Set filter bits
                foreach (Filter filter in reflex.Filters)
                {
                    // Don't consider the selected one, since we'd be replacing it.
                    if (filter.upid == selectionUpid)
                    {
                        selectionUpid = null;
                        continue;
                    }

                    scratchOutputs.Or(filter.Outputs);
                    scratchNegOutputs.Or(filter.NegOutputs);
                }
                // Set actuator bits
                if (reflex.Actuator != null)
                {
                    scratchNegOutputs.Or(reflex.Actuator.NegOutputs);
                }
                // Set selector bits
                if (reflex.Selector != null)
                {
                    scratchNegOutputs.Or(reflex.Selector.NegOutputs);
                }
                // Set modifier bits
                foreach (Modifier modifier in reflex.Modifiers)
                {
                    // Don't consider the selected one, since we'd be replacing it.
                    if (modifier.upid == selectionUpid)
                    {
                        selectionUpid = null;
                        continue;
                    }

                    scratchNegOutputs.Or(modifier.NegOutputs);
                }
            }

            // If this element is on the do side, remove negated outputs.
            // TODO (****) I just noticed that "this is Filter" is here even though filters
            // shouldn't be on the DO side.  Is this a bug or do we need this?
            if (this is Actuator || this is Selector || this is Modifier || this is Filter)
            {
                scratchOutputs.And(scratchNegOutputs.Not());
            }

            // Check datatype compatibility
            {
                if (this.InputCount > 0 && !MatchesAnyBit(scratchOutputs, this.Inputs))
                {
                    return(false);
                }
            }

            // Build category bitmask
            int scratchExclusionCount = 0;

            {
                string selectionUpid = (replacedElement != null) ? replacedElement.upid : null;

                scratchCategories.SetAll(false);
                scratchNegations.SetAll(false);

                // Set sensor bits
                if (reflex.Sensor != null && reflex.Sensor.upid != selectionUpid)
                {
                    scratchCategories.Or(reflex.Sensor.Categories);
                    scratchNegations.Or(reflex.Sensor.Negations);
                }
                // Set actuator bits
                if (reflex.Actuator != null && reflex.Actuator.upid != selectionUpid)
                {
                    scratchCategories.Or(reflex.Actuator.Categories);
                    scratchNegations.Or(reflex.Actuator.Negations);
                }
                // Set selector bits
                if (reflex.Selector != null && reflex.Selector.upid != selectionUpid)
                {
                    scratchCategories.Or(reflex.Selector.Categories);
                    scratchNegations.Or(reflex.Selector.Negations);
                }
                // Set filter bits
                foreach (Filter filter in reflex.Filters)
                {
                    // Don't consider the selected modifier, since we'd be replacing it.
                    // Don't consider any filters after the selection either, since we need to consider only everything to its left when replacing.
                    if (filter.upid == selectionUpid)
                    {
                        selectionUpid = null;
                        break;
                    }

                    scratchCategories.Or(filter.Categories);
                    scratchNegations.Or(filter.Negations);

                    scratchExclusionCount += Math.Max(scratchExclusionCount, filter.ExclusionCount);
                }
                // Set modifier bits
                foreach (Modifier modifier in reflex.Modifiers)
                {
                    // Don't consider the selected modifier, since we'd be replacing it.
                    // Don't consider any modifiers after the selection either, since we need to consider only everything to its left when replacing.
                    if (modifier.upid == selectionUpid)
                    {
                        selectionUpid = null;
                        break;
                    }

                    scratchCategories.Or(modifier.Categories);
                    scratchNegations.Or(modifier.Negations);

                    scratchExclusionCount = Math.Max(scratchExclusionCount, modifier.ExclusionCount);
                }
            }

            // If this element is on the "do" side, remove negated categories.
            // Let Negations work on WHEN side also...
            //if (this is Actuator || this is Selector || this is Modifier)
            {
                scratchNegations.Not(); // Invert the negations.
                scratchCategories.And(scratchNegations);
            }

            // Build my inclusion bitmask
            {
                scratchMyCategories.SetAll(false);
                scratchMyCategories.Or(this.Inclusions);
                if (allowArchivedCategories)
                {
                    scratchMyCategories.Or(this.ArchivedInclusions);
                }
            }

#if DEBUG_COMPATIBILITY
            if (this.upid == "modifier.it")
            {
                scratchNegations.Not(); // Restore negations so they dump correctly.

                num++;
                Debug.Print(num.ToString());
                Debug.Print(this.upid);
                DumpCategories(this.Inclusions, "  inclusions");
                DumpCategories(this.Exclusions, "  exclusions");
                DumpCategories(scratchCategories, "  scratch");
                DumpCategories(scratchMyCategories, "  scratchMy");
                DumpCategories(scratchNegations, "  scratchNegations");
            }
#endif

            // Check category compatibility
            {
                if (this.InclusionCount > 0 && !MatchesAnyBit(scratchCategories, scratchMyCategories))
                {
                    return(false);
                }
                if (this.ExclusionCount > 0 && MatchesAnyBit(scratchCategories, this.Exclusions))
                {
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            byte[] a = { 10 };
            byte[] b = { 64 };
            byte[] c = { 25 };

            BitArray ba1 = new BitArray(8);
            BitArray ba2 = new BitArray(8);
            BitArray ba3 = new BitArray(8);

            ba1 = new BitArray(a);
            ba2 = new BitArray(b);
            ba3 = new BitArray(c);

            Console.WriteLine("First BitArray whose value is 10");
            for (int i = 0; i < ba1.Count; i++)
            {
                Console.Write("{0 , -6}", ba1[i]);
            }
            Console.WriteLine();

            Console.WriteLine("First BitArray whose value is 25");
            for (int i = 0; i < ba2.Count; i++)
            {
                Console.Write("{0 , -6}", ba2[i]);
            }
            Console.WriteLine();

            Console.WriteLine("First BitArray whose value is 64");
            for (int i = 0; i < ba3.Count; i++)
            {
                Console.Write("{0 , -6}", ba3[i]);
            }
            Console.WriteLine();

            Console.WriteLine("BitArray ba2: 13");
            for (int i = 0; i < ba2.Count; i++)
            {
                Console.Write("{0 , -6}", ba1[i]);
            }
            Console.WriteLine();

            BitArray ba4 = new BitArray(8);

            ba4 = ba1.And(ba2);
            Console.WriteLine("After AND operation:");
            for (int i = 0; i < ba4.Count; i++)
            {
                Console.Write("{0 , -6}", ba4[i]);
            }
            Console.WriteLine();

            ba4.Set(3, true);
            Console.WriteLine("After SET operation:");
            for (int i = 0; i < ba4.Count; i++)
            {
                Console.Write("{0 , -6}", ba4[i]);
            }
            Console.WriteLine();

            ba4 = ba1.Or(ba2);
            Console.WriteLine("After OR operation:");
            for (int i = 0; i < ba4.Count; i++)
            {
                Console.Write("{0 , -6}", ba4[i]);
            }
            Console.WriteLine();

            ba4 = ba1.Xor(ba2);
            Console.WriteLine("After XOR operation:");
            for (int i = 0; i < ba4.Count; i++)
            {
                Console.Write("{0 , -6}", ba4[i]);
            }
            Console.WriteLine();
        }
Ejemplo n.º 28
0
        public override void ReadGroupCodes()
        {
            BitArray      flags;
            BitArray      comparer;
            bool          processingVertices;
            CEntityVertex vertex;

            VertexList         = new ArrayList();
            processingVertices = false;
            vertex             = null;


            foreach (CGroupCode gc in GroupCodeList)
            {
                if (gc.Code == 0)
                {
                    if (gc.Value.Trim().ToUpper() == "VERTEX")
                    {
                        processingVertices = true;

                        if (vertex != null)
                        {
                            vertex.ReadGroupCodes();
                            VertexList.Add(vertex);
                        }

                        vertex            = new CEntityVertex();
                        vertex.EntityName = "VERTEX";
                        vertex.LayerName  = LayerName;
                    }
                    else if (gc.Value.Trim().ToUpper() == "SEQEND")
                    {
                        processingVertices = false;
                        if (vertex != null)
                        {
                            vertex.ReadGroupCodes();
                            VertexList.Add(vertex);
                        }
                    }
                }
                else if (gc.Code == 30 && processingVertices == false)
                {
                    Elevation = CGlobals.ConvertToDouble(gc.Value.Trim());
                }
                else if (gc.Code == 40 && processingVertices == false)
                {
                    DefaultStartingWidth = CGlobals.ConvertToDouble(gc.Value.Trim());
                }
                else if (gc.Code == 41 && processingVertices == false)
                {
                    DefaultEndingWidth = CGlobals.ConvertToDouble(gc.Value.Trim());
                }
                else if (gc.Code == 70 && processingVertices == false)
                {
                    flags = new BitArray(new int[] { CGlobals.ConvertToInt(gc.Value.Trim()) });

                    comparer         = new BitArray(new int[] { 1 });
                    IsClosedPolyline = flags.And(comparer)[0];

                    comparer            = new BitArray(new int[] { 2 });
                    HasCurveFitVertices = flags.And(comparer)[0];

                    comparer             = new BitArray(new int[] { 4 });
                    HasSplineFitVertices = flags.And(comparer)[0];

                    comparer     = new BitArray(new int[] { 8 });
                    Is3DPolyline = flags.And(comparer)[0];

                    comparer = new BitArray(new int[] { 16 });
                    Is3DMesh = flags.And(comparer)[0];

                    comparer = new BitArray(new int[] { 32 });
                    MeshClosedInTheNDirection = flags.And(comparer)[0];

                    comparer       = new BitArray(new int[] { 64 });
                    IsPolyfaceMesh = flags.And(comparer)[0];

                    comparer           = new BitArray(new int[] { 128 });
                    ContinuousLineType = flags.And(comparer)[0];
                }
                else if (gc.Code == 71 && processingVertices == false)
                {
                    PolygonMeshMVertexCount = CGlobals.ConvertToDouble(gc.Value.Trim());
                }
                else if (gc.Code == 72 && processingVertices == false)
                {
                    PolygonMeshNVertexCount = CGlobals.ConvertToDouble(gc.Value.Trim());
                }
                else if (gc.Code == 73 && processingVertices == false)
                {
                    SmoothSurfaceMDensity = CGlobals.ConvertToDouble(gc.Value.Trim());
                }
                else if (gc.Code == 74 && processingVertices == false)
                {
                    SmoothSurfaceNDensity = CGlobals.ConvertToDouble(gc.Value.Trim());
                }
                else if (gc.Code == 75 && processingVertices == false)
                {
                    if (CGlobals.ConvertToInt(gc.Value.Trim()) == 0)
                    {
                        NoSmoothSurfaceFitted = true;
                    }
                    else if (CGlobals.ConvertToInt(gc.Value.Trim()) == 5)
                    {
                        QuadraticBSplineSurface = true;
                    }
                    else if (CGlobals.ConvertToInt(gc.Value.Trim()) == 6)
                    {
                        CubicBSplineSurface = true;
                    }
                    else if (CGlobals.ConvertToInt(gc.Value.Trim()) == 8)
                    {
                        BezierSurface = true;
                    }
                }
                else
                {
                    if (processingVertices && vertex != null)
                    {
                        if (gc.Code == 5)
                        {
                            // Handle

                            vertex.Handle = gc.Value.Trim();
                        }
                        else if (gc.Code == 6)
                        {
                            // Line Type

                            vertex.LineType = gc.Value.Trim();
                        }
                        else if (gc.Code == 8)
                        {
                            // Layer Name

                            vertex.LayerName = gc.Value.Trim();
                        }
                        else
                        {
                            vertex.GroupCodeList.Add(gc);
                        }
                    }
                }
            }
        }
Ejemplo n.º 29
0
        public static BitArray And(BitArray X, BitArray Y)
        {
            BitArray n = X.And(Y);

            return(n);
        }
Ejemplo n.º 30
0
		public override void ReadGroupCodes()
		{
			BitArray flags;
			BitArray comparer;

			foreach(CGroupCode gc in GroupCodeList)
			{
				if(gc.Code == 10)
				{
					X0 = CGlobals.ConvertToDouble(gc.Value.Trim());
				}
				else if(gc.Code == 20)
				{
					Y0 = CGlobals.ConvertToDouble(gc.Value.Trim());
				}
				else if(gc.Code == 30)
				{
					Z0 = CGlobals.ConvertToDouble(gc.Value.Trim());
				}
				else if(gc.Code == 11)
				{
					X1 = CGlobals.ConvertToDouble(gc.Value.Trim());
				}
				else if(gc.Code == 21)
				{
					Y1 = CGlobals.ConvertToDouble(gc.Value.Trim());
				}
				else if(gc.Code == 31)
				{
					Z1 = CGlobals.ConvertToDouble(gc.Value.Trim());
				}
				else if(gc.Code == 12)
				{
					X2 = CGlobals.ConvertToDouble(gc.Value.Trim());
				}
				else if(gc.Code == 22)
				{
					Y2 = CGlobals.ConvertToDouble(gc.Value.Trim());
				}
				else if(gc.Code == 32)
				{
					Z2 = CGlobals.ConvertToDouble(gc.Value.Trim());
				}
				else if(gc.Code == 13)
				{
					X3 = CGlobals.ConvertToDouble(gc.Value.Trim());
				}
				else if(gc.Code == 23)
				{
					Y3 = CGlobals.ConvertToDouble(gc.Value.Trim());
				}
				else if(gc.Code == 33)
				{
					Z3 = CGlobals.ConvertToDouble(gc.Value.Trim());
				}
				else if(gc.Code == 70)
				{
					flags = new BitArray(new int[] { CGlobals.ConvertToInt(gc.Value.Trim()) });
			
					comparer = new BitArray(new int[] { 1 });
					Edge1Invisible = flags.And(comparer)[0];

					comparer = new BitArray(new int[] { 2 });
					Edge2Invisible = flags.And(comparer)[0];

					comparer = new BitArray(new int[] { 4 });
					Edge3Invisible = flags.And(comparer)[0];

					comparer = new BitArray(new int[] { 8 });
					Edge4Invisible = flags.And(comparer)[0];
				}
			}
		}
Ejemplo n.º 31
0
        static void Main(string[] args)
        {
            #region Khai báo và khởi tạo BitArray

            /*
             * Khởi tạo 1 BitArray có 10 phần tử
             * Mỗi phần tử có giá trị mặc định 0 (false)
             */
            BitArray MyBA = new BitArray(10);

            /*
             * Khởi tạo 1 BitArray có 10 phần tử
             * Mỗi phần tử có giá trị mặc định 0 (false)
             */
            BitArray MyBA2 = new BitArray(10, true);

            // Khởi tạo 1 BitArray từ 1 mảng bool có sẵn
            bool[] MyBools = new bool[5] {
                true, false, true, true, false
            };
            BitArray MyBA3 = new BitArray(MyBools);                 // 1 0 1 1 0

            // Khởi tạo 1 BitArray từ 1 mảng byte có sẵn
            byte[] MyBytes = new byte[5] {
                1, 2, 3, 4, 5
            };
            BitArray MyBA4 = new BitArray(MyBytes);

            // Kiểm thử. Uncomment để xem kết quả
            WriteLine(" So bit cua BitArray la {0}", MyBA4.Length);
            PrintBit(MyBA4, 8);

            // Khởi tạo 1 BitArray từ 1 mảng int có sẵn
            int[] MyInts = new int[5] {
                1, 2, 3, 4, 5
            };
            BitArray MyBA5 = new BitArray(MyInts);

            // Kiểm thử. Uncomment để xem kết quả
            // WriteLine(" So bit cua BitArray la {0}", MyBA5.Length);
            // PrintBit(MyBA5, 32);

            #endregion

            #region Ví dụ và sử dụng BitArray

            // Khởi tạo 1 BitArray từ mảng bool có sẵn
            bool[] MyBools2 = new bool[5] {
                true, false, true, true, false
            };
            BitArray MyBA6 = new BitArray(MyBools2);

            // Khởi tạo 1 BitArray có 2 phần tử và có giá trị mặc định là 1 (true)
            bool[]   MyBool3 = new bool[] { false, true, true, false, false };
            BitArray MyBA7   = new BitArray(MyBool3);

            Write(" Gia tri cua MyBA6: ");
            PrintBit(MyBA6, 5);

            Write(" Gia tri cua MyBA7: ");
            PrintBit(MyBA7, 5);

            WriteLine(" Thuc hien cac phep toan AND, OR, NOT, XOR tren MyBA6, va MyBA7: ");

            // Thực hiện sao chép giá trị của MyBA6 ra để không làm thay đổi nó
            BitArray AndBit = MyBA6.Clone() as BitArray;
            AndBit.And(MyBA7);
            Write(" Ket qua cua phep toan AND: ");
            PrintBit(AndBit, 5);

            BitArray OrBit = MyBA6.Clone() as BitArray;
            OrBit.Or(MyBA7);
            Write(" Ket qua cua phep toan AND: ");
            PrintBit(OrBit, 5);

            BitArray NotBit = MyBA6.Clone() as BitArray;
            NotBit.Not();
            Write(" Ket qua cua phep toan AND: ");
            PrintBit(NotBit, 5);

            BitArray XorBit = MyBA6.Clone() as BitArray;
            XorBit.Xor(MyBA7);
            Write(" Ket qua cua phep toan AND: ");
            PrintBit(XorBit, 5);

            #endregion
        }
Ejemplo n.º 32
0
 public virtual bool runTest()
 {
     Console.Out.WriteLine( "Plain\\System_NewCollections\\BitArray\\Co1550And.cs  runTest() started." );
     int iCountErrors = 0;
     int iCountTestcases = 0;
     BitArray ba2 = null;
     BitArray ba3 = null;
     BitArray ba4 = null;
     ba2 = new BitArray( 6 ,false );
     ba3 = new BitArray( 6 ,false );
     ba2.Set( 0 ,true ); 
     ba2.Set( 1 ,true ); 
     ba3.Set( 1 ,true ); 
     ba3.Set( 2 ,true ); 
     ba4 = ba2.And( ba3 );
     ++iCountTestcases;
     if ( ba4.Get( 0 ) )
     {
         ++iCountErrors;
         Console.Error.WriteLine(  "POINTTOBREAK: find error E_09pv (Co1550And)"  );
         Console.Error.WriteLine(  "EXTENDEDINFO: 1 & 0 (E_09pv ,Co1550And)"  );
     }
     ++iCountTestcases;
     if ( ! ba4.Get( 1 ) )
     {
         ++iCountErrors;
         Console.Error.WriteLine(  "POINTTOBREAK: find error E_96hf (Co1550And)"  );
     }
     ++iCountTestcases;
     if ( ba4.Get( 2 ) )
     {
         ++iCountErrors;
         Console.Error.WriteLine(  "POINTTOBREAK: find error E_84si (Co1550And)"  );
     }
     ++iCountTestcases;
     if ( ba4.Get( 4 ) )
     {
         ++iCountErrors;
         Console.Error.WriteLine(  "POINTTOBREAK: find error E_79kn (Co1550And)"  );
     }
     ba2 = new BitArray( 0x1000F ,false );
     ba3 = new BitArray( 0x1000F ,false );
     ba2.Set( 0x10000 ,true );
     ba2.Set( 0x10001 ,true );
     ba3.Set( 0x10001 ,true );
     ba3.Set( 0x10002 ,true );
     ba4 = ba2.And( ba3 );
     ++iCountTestcases;
     if ( ba4.Get( 0x10000 ) )
     {
         ++iCountErrors;
         Console.Error.WriteLine(  "POINTTOBREAK: find error E_61ah (Co1550And)"  );
     }
     ++iCountTestcases;
     if ( ! ba4.Get( 0x10001 ) )
     {
         ++iCountErrors;
         Console.Error.WriteLine(  "POINTTOBREAK: find error E_52xd (Co1550And)"  );
     }
     ++iCountTestcases;
     if ( ba4.Get( 0x10002 ) )
     {
         ++iCountErrors;
         Console.Error.WriteLine(  "POINTTOBREAK: find error E_47op (Co1550And)"  );
     }
     ++iCountTestcases;
     if ( ba4.Get( 0x10004 ) )
     {
         ++iCountErrors;
         Console.Error.WriteLine(  "POINTTOBREAK: find error E_54ja (Co1550And)"  );
     }
     try
     {
         BitArray b1 = new BitArray( 0 );
         BitArray b2 = new BitArray( 0 );
         b1.And( b2 );
     }
     catch ( Exception exc )
     {
         ++iCountErrors;
         Console.WriteLine( "Err_001, Exception was not expected " + exc );
     }
     ba2 = new BitArray( 11 ,false );
     ba3 = new BitArray( 6 ,false );
     try
     {
         ++iCountTestcases;
         ba4 = ba2.And( ba3 );
         ++iCountErrors;
         Console.Error.WriteLine(  "POINTTOBREAK: find error E_66vc (Co1550And)"  );
     }
     catch ( ArgumentException ) {}
     catch ( Exception )  
     {
         ++iCountErrors;
         Console.Error.WriteLine(  "POINTTOBREAK: find error E_58jq (Co1550And)"  );
     }
     ba2 = new BitArray( 6 ,false );
     ba3 = new BitArray( 11 ,false );
     try
     {
         ++iCountTestcases;
         ba4 = ba2.And( ba3 );
         ++iCountErrors;
         Console.Error.WriteLine(  "POINTTOBREAK: find error E_432k (Co1550And)"  );
     }
     catch ( ArgumentException ) {}
     catch ( Exception )  
     {
         ++iCountErrors;
         Console.Error.WriteLine(  "POINTTOBREAK: find error E_452a (Co1550And)"  );
     }
     ba2 = new BitArray( 6 ,false );
     ba3 = null;
     try
     {
         ++iCountTestcases;
         ba4 = ba2.And( ba3 );
         ++iCountErrors;
         Console.Error.WriteLine(  "POINTTOBREAK: find error E_72dg (Co1550And)"  );
     }
     catch ( ArgumentNullException ) {}
     catch ( Exception )  
     {
         ++iCountErrors;
         Console.Error.WriteLine(  "POINTTOBREAK: find error E_93kx (Co1550And)"  );
     }
     if ( iCountErrors == 0 )
     {
         Console.Error.Write( "BitArray\\Co1550And.cs: paSs.  iCountTestcases==" );
         Console.Error.WriteLine( iCountTestcases );
         return true;
     }
     else
     {
         Console.Error.Write( "Co1550And.cs iCountErrors==" );
         Console.Error.WriteLine( iCountErrors );
         Console.Error.WriteLine(  "PATHTOSOURCE: BitArray\\Co1550And.cs   FAiL !"  );
         return false;
     }
 }
Ejemplo n.º 33
0
        static void Main(string[] args)
        {
            List <int> ilist = new List <int>();

            ilist.Add(10);
            ilist.Add(7);
            ilist.Add(15);
            ilist.Add(3);

            foreach (int i in ilist)
            {
                Console.WriteLine(i);
            }

            ilist.Sort();
            Console.WriteLine("Sorted List:");
            foreach (int i in ilist)
            {
                Console.WriteLine(i);
            }

            LinkedList <int> llist = new LinkedList <int>();

            llist.AddLast(10);
            llist.AddLast(15);
            llist.AddLast(20);

            LinkedListNode <int> middle = llist.Find(15);

            llist.AddAfter(middle, 18);

            foreach (int i in llist)
            {
                Console.WriteLine(i);
            }

            Console.WriteLine("Queue:");

            Queue <int> q1 = new Queue <int>();

            q1.Enqueue(1);
            q1.Enqueue(2);
            q1.Enqueue(3);

            while (q1.Count > 0)
            {
                Console.WriteLine(q1.Dequeue());
            }

            Console.WriteLine("Stack");

            Stack <int> s1 = new Stack <int>();

            s1.Push(1);
            s1.Push(2);
            s1.Push(3);

            while (s1.Count > 0)
            {
                Console.WriteLine(s1.Pop());
            }

            BitArray ba = new BitArray(5, true);

            ba.Set(2, false);

            foreach (bool b in ba)
            {
                Console.WriteLine(b);
            }

            BitArray ba2 = new BitArray(5, true);

            ba2.Set(0, false);
            ba2.Set(1, false);

            Console.WriteLine("And BitArray:");

            ba.And(ba2);

            foreach (bool b in ba)
            {
                Console.WriteLine(b);
            }

            HashSet <string> hs = new HashSet <string>();

            hs.Add("String1");
            hs.Add("String2");
            hs.Add("String3");
            hs.Add("String4");
            hs.Add("String5");
            hs.Add("String5");

            foreach (string s in hs)
            {
                Console.WriteLine(s);
            }
        }
Ejemplo n.º 34
0
        public void Update()
        {
#if DEBUG
            var watch = System.Diagnostics.Stopwatch.StartNew();
#endif

            Map map = Find.Maps.Find(x => x.uniqueID == areaExtID.MapID);
            if (map == null)
            {
                return;
            }

            this.areaManager = map.areaManager;

            var innerAreas = InnerAreas;

            BoolGrid innerGrid = (BoolGrid)FieldInfos.innerGrid.GetValue(this);
            bool[]   arr       = (bool[])FieldInfos.boolGridArr.GetValue(innerGrid);

            BitArray arrBA = new BitArray(arr);
            if (innerAreas.Count > 0 && innerAreas.Any(x => x.Value == AreaExtOperator.Inclusion))
            {
                arrBA.SetAll(false);
            }
            else
            {
                arrBA.SetAll(true);
            }

            var areaNameBuilder = new StringBuilder();
            for (int i = 0; i < innerAreas.Count; ++i)
            {
                var kv = innerAreas[i];

                Area            area = kv.Key;
                AreaExtOperator op   = kv.Value;

                BitArray targetArrBA = GetAreaBitArray(area);
                if (op == AreaExtOperator.Inclusion)
                {
                    arrBA = arrBA.Or(targetArrBA);
                    if (i > 0)
                    {
                        areaNameBuilder.Append("+");
                    }
                }
                else if (op == AreaExtOperator.Exclusion)
                {
                    arrBA = arrBA.And(targetArrBA.Not());
                    areaNameBuilder.Append("-");
                }

                areaNameBuilder.Append(area.Label);
            }

            arrBA.CopyTo(arr, 0);
            FieldInfos.boolGridArr.SetValue(innerGrid, arr);
            FieldInfos.boolGridTrueCount.SetValue(innerGrid, arr.Count(x => x));

            cachedLabel = areaNameBuilder.ToString();

            if (innerAreas.Count == 1)
            {
                cachedColor = innerAreas[0].Key.Color;
            }
            else
            {
                cachedColor = Color.black;
            }

            initialized  = true;
            drawer.dirty = true;

#if DEBUG
            watch.Stop();
            Log.Message(string.Format("Update elapsed : {0}", watch.ElapsedMilliseconds));
#endif
        }
Ejemplo n.º 35
0
 public void AndWith(IBitset otherSet)
 {
     _Array = _Array.And(((UncompressedBitArray)otherSet)._Array);
 }
        // <summary>
        // Given discriminator values (ordinally aligned with DiscriminatorColumns), determines
        // the entity type to return. Throws a CommandExecutionException if the type is ambiguous.
        // </summary>
        internal EntityType Discriminate(object[] discriminatorValues, int resultSetIndex)
        {
            var resultMapping = GetResultMapping(resultSetIndex);

            Debug.Assert(resultMapping != null);

            // initialize matching types bit map
            var typeCandidates = new BitArray(resultMapping.MappedEntityTypes.Count, true);

            foreach (var typeMapping in resultMapping.NormalizedEntityTypeMappings)
            {
                // check if this type mapping is matched
                var matches          = true;
                var columnConditions = typeMapping.ColumnConditions;
                for (var i = 0; i < columnConditions.Count; i++)
                {
                    if (null != columnConditions[i]
                        && // this discriminator doesn't matter for the given condition
                        !columnConditions[i].ColumnValueMatchesCondition(discriminatorValues[i]))
                    {
                        matches = false;
                        break;
                    }
                }

                if (matches)
                {
                    // if the type condition is met, narrow the set of type candidates
                    typeCandidates = typeCandidates.And(typeMapping.ImpliedEntityTypes);
                }
                else
                {
                    // if the type condition fails, all implied types are eliminated
                    // (the type mapping fragment is a co-implication, so a type is no longer
                    // a candidate if any condition referring to it is false)
                    typeCandidates = typeCandidates.And(typeMapping.ComplementImpliedEntityTypes);
                }
            }

            // find matching type condition
            EntityType entityType = null;

            for (var i = 0; i < typeCandidates.Length; i++)
            {
                if (typeCandidates[i])
                {
                    if (null != entityType)
                    {
                        throw new EntityCommandExecutionException(Strings.ADP_InvalidDataReaderUnableToDetermineType);
                    }
                    entityType = resultMapping.MappedEntityTypes[i];
                }
            }

            // if there is no match, raise an exception
            if (null == entityType)
            {
                throw new EntityCommandExecutionException(Strings.ADP_InvalidDataReaderUnableToDetermineType);
            }

            return(entityType);
        }
Ejemplo n.º 37
0
    // returns a bitboard of a pump station that exists on the specified coordinates,
    // or return empty if no pump station exists on the specified coordinates
    public static BitArray GetPumpStation(BitArray pumpStations, int x, int y)
    {
        // check to see if specified unit is on one of our pump stations
        BitArray test = new BitArray(length, false).Or(pumpStations);
        test.And(position[x][y]);
        if (Equal(test, empty))
        {
          return empty;
        }

        // create bitboard representing pump station the unit is standing on
        BitArray pumpStation = new BitArray(length, false).Or(position[x][y]);
        if (x - 1 >= 0)
        {
          pumpStation.Or(position[x - 1][y]);
          if (y - 1 >= 0)
          {
        pumpStation.Or(position[x - 1][y - 1]);
          }
          if (y + 1 < height)
          {
        pumpStation.Or(position[x - 1][y + 1]);
          }
        }
        if (x + 1 < width)
        {
          pumpStation.Or(position[x + 1][y]);
          if (y - 1 >= 0)
          {
        pumpStation.Or(position[x + 1][y - 1]);
          }
          if (y + 1 < height)
          {
        pumpStation.Or(position[x + 1][y + 1]);
          }
        }
        if (y - 1 >= 0)
        {
          pumpStation.Or(position[x][y - 1]);
        }
        if (y + 1 < height)
        {
          pumpStation.Or(position[x][y + 1]);
        }
        return pumpStation.And(pumpStations);
    }