示例#1
0
        private static void SwapExample()
        {
            var a = 10;
            var b = 20;

            Swapper.Swap(ref a, ref b);
            // V premennych by mali byt tieto hodnoty:
            // a = 20, b = 10
            Console.WriteLine($"{a} {b}");

            var d1 = Math.PI;
            var d2 = Math.E;

            Swapper.Swap(ref d1, ref d2);
            // V premennych by mali byt tieto hodnoty:
            // d1 = Math.E, d2 = Math.PI
            Console.WriteLine($"{d1} {d2}");

            var hello = "Ahoj";
            var world = "svet";

            Swapper.Swap(ref hello, ref world);
            // V premennych by mali byt tieto hodnoty:
            // hello = "svet", world = "Ahoj"
            Console.WriteLine($"{hello} {world}");

            // Pozadovany vystup:
            // 20 10
            // 2,718281828459045 3,141592653589793
            // svet Ahoj
        }
示例#2
0
        internal int Pivot(IList array, int lower, int upper)
        {
            // Pivot with first element
            var left  = lower + 1;
            var pivot = array[lower];
            var right = upper;

            // Partition array elements
            while (left <= right)
            {
                // Find item out of place
                while ((left <= right) && (Comparer.Compare(array[left], pivot) <= 0))
                {
                    ++left;
                }

                while ((left <= right) && (Comparer.Compare(array[right], pivot) > 0))
                {
                    --right;
                }

                // Swap values if necessary
                if (left < right)
                {
                    Swapper.Swap(array, left, right);
                    ++left;
                    --right;
                }
            }

            // Move pivot element
            Swapper.Swap(array, lower, right);
            return(right);
        }
示例#3
0
        public static void GenButton(Swapper role, int index, bool isDead)
        {
            if (isDead)
            {
                role.Buttons.Add(null);
                role.ListOfActives.Add(false);
                return;
            }

            var confirmButton = MeetingHud.Instance.playerStates[index].Buttons.transform.GetChild(0).gameObject;


            var newButton = Object.Instantiate(confirmButton, MeetingHud.Instance.playerStates[index].transform);
            var renderer  = newButton.GetComponent <SpriteRenderer>();
            var passive   = newButton.GetComponent <PassiveButton>();

            renderer.sprite = DisabledSprite;
            newButton.transform.position    = confirmButton.transform.position - new Vector3(0.5f, 0f, 0f);
            newButton.transform.localScale *= 0.8f;
            newButton.layer            = 5;
            newButton.transform.parent = confirmButton.transform.parent.parent;

            passive.OnClick = new Button.ButtonClickedEvent();
            passive.OnClick.AddListener(SetActive(role, index));
            role.Buttons.Add(newButton);
            role.ListOfActives.Add(false);
        }
示例#4
0
 /// <summary>
 /// Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)].
 /// </summary>
 private static void vecswap(Swapper swapper, int a, int b, int n)
 {
     for (int i = 0; i < n; i++, a++, b++)
     {
         swapper(a, b);
     }
 }
        public SortingResult Sort(Data[] array)
        {
            SortingResult sortingResult = new SortingResult {
                ArrayOfData = array
            };
            var watch = Stopwatch.StartNew();

            for (int i = 0; i < array.Length; i++)
            {
                for (int g = 0; g < (array.Length - 1); g++)
                {
                    sortingResult.CountOfCompares++;
                    if (_compareMethod.Invoke(array[g], array[g + 1]) == 1)
                    {
                        Swapper.Swap(ref array[g], ref array[g + 1]);
                        sortingResult.CountOfSwaps++;
                    }
                }
            }

            watch.Stop();
            sortingResult.Time = watch.Elapsed;


            return(sortingResult);
        }
        private IEnumerable <Intersection> IntersectWalls(Ray localRay)
        {
            var a = Math.Pow(localRay.Direction.x, 2) - Math.Pow(localRay.Direction.y, 2) + Math.Pow(localRay.Direction.z, 2);

            var b =
                2 * localRay.Origin.x * localRay.Direction.x -
                2 * localRay.Origin.y * localRay.Direction.y +
                2 * localRay.Origin.z * localRay.Direction.z;

            var c =
                Math.Pow(localRay.Origin.x, 2) -
                Math.Pow(localRay.Origin.y, 2) +
                Math.Pow(localRay.Origin.z, 2);

            if (Math.Abs(a) < C.Epsilon)
            {
                // Ray is parallell to one of the cones halves
                if (Math.Abs(b) < C.Epsilon)
                {
                    yield break;
                }
                var t = -c / (2 * b);
                var y = localRay.Origin.y + t * localRay.Direction.y;
                if (Min < y && y < Max)
                {
                    yield return(new Intersection(t, this));
                }
                yield break;
            }

            var disc = Math.Pow(b, 2) - 4 * a * c;

            if (disc < 0)
            {
                // Ray does not intersect the cone
                yield break;
            }

            var t0 = (-b - Math.Sqrt(disc)) / (2 * a);
            var t1 = (-b + Math.Sqrt(disc)) / (2 * a);

            if (t0 > t1)
            {
                Swapper.Swap(ref t0, ref t1);
            }

            var y0 = localRay.Origin.y + t0 * localRay.Direction.y;

            if (Min < y0 && y0 < Max)
            {
                yield return(new Intersection(t0, this));
            }

            var y1 = localRay.Origin.y + t1 * localRay.Direction.y;

            if (Min < y1 && y1 < Max)
            {
                yield return(new Intersection(t1, this));
            }
        }
示例#7
0
        private void DownHeap(IList list, int k, int n)
        {
            var loop = true;

            while (k <= n / 2 && loop)
            {
                var j = k + k;
                if (j < n)
                {
                    if (Comparer.Compare(list[j - 1], list[j]) < 0)
                    {
                        j++;
                    }
                }

                if (Comparer.Compare(list[k - 1], list[j - 1]) >= 0)
                {
                    loop = false;
                }
                else
                {
                    Swapper.Swap(list, k - 1, j - 1);
                    k = j;
                }
            }
        }
示例#8
0
        private (double tMin, double tMax) CheckAxis(double origin, double direction, double min, double max)
        {
            var tMinNumerator = min - origin;
            var tMaxNumerator = max - origin;

            double tMin, tMax;

            if (Math.Abs(direction) >= C.Epsilon)
            {
                tMin = tMinNumerator / direction;
                tMax = tMaxNumerator / direction;
            }
            else
            {
                tMin = tMinNumerator * double.PositiveInfinity;
                tMax = tMaxNumerator * double.PositiveInfinity;
            }

            if (tMin > tMax)
            {
                Swapper.Swap(ref tMin, ref tMax);
            }

            return(tMin, tMax);
        }
示例#9
0
        /// <summary>Byte swap a given structure a number of times over a range of bytes</summary>
        /// <param name="definition">Structure definition in terms of byte swap codes</param>
        /// <param name="buffer">Buffer containing the bytes of an instance of the definition</param>
        /// <param name="startIndex">Where to start processing the definition in the buffer</param>
        /// <param name="count">Number of times to process the definition on the buffer</param>
        /// <returns>Offset in <paramref name="buffer"/> where processing ended</returns>
        public static int SwapData(IByteSwappable definition, byte[] buffer,
                                   int startIndex = 0, int count = 1)
        {
            Contract.Requires <ArgumentNullException>(definition != null);
            Contract.Requires <ArgumentNullException>(buffer != null);
            Contract.Requires <ArgumentOutOfRangeException>(startIndex >= 0);
            Contract.Requires <ArgumentOutOfRangeException>(startIndex <= buffer.Length);
            Contract.Requires <ArgumentOutOfRangeException>(count > 0);
            Contract.Requires <ArgumentOutOfRangeException>((count * definition.SizeOf) <= (buffer.Length - startIndex),
                                                            "buffer doesn't have enough data for the given byte swap parameters");
            Contract.Ensures(Contract.Result <int>() >= 0);

            if (count == 0)
            {
                return(startIndex);
            }

            var swap         = new Swapper(definition);
            int buffer_index = startIndex;

            for (int elements_remaining = count; elements_remaining > 0; elements_remaining--)
            {
                buffer_index = swap.SwapData(buffer, buffer_index);
            }

            Contract.Assert(buffer_index == (startIndex + (definition.SizeOf * count)));
            return(buffer_index);
        }
        public SortingResult Sort(Data[] array)
        {
            SortingResult sortingResult = new SortingResult {
                ArrayOfData = array
            };
            var  watch     = Stopwatch.StartNew();
            bool isOrdered = false;

            for (int i = 0; i < array.Length && !isOrdered; i++)
            {
                for (int g = 0; g < (array.Length - 1); g++)
                {
                    sortingResult.CountOfCompares++;
                    if (_compareMethod(array[g], array[g + 1]) == 1)
                    {
                        Swapper.Swap(ref array[g], ref array[g + 1]);
                        sortingResult.CountOfSwaps++;
                    }
                }

                isOrdered = CheckState(array, sortingResult);
            }

            watch.Stop();
            sortingResult.Time = watch.Elapsed;

            return(sortingResult);
        }
示例#11
0
        public static bool ContainsAny(FlagSet a, FlagSet b)
        {
            if (a == null || a.IsEmpty || b == null || b.IsEmpty)
            {
                return(false);
            }
            if (a.Count == 1)
            {
                return(b.Contains(a[0]));
            }
            if (b.Count == 1)
            {
                return(a.Contains(b[0]));
            }

            if (a.Count > b.Count)
            {
                Swapper.Swap(ref a, ref b);
            }

            foreach (var item in a)
            {
                if (b.Contains(item))
                {
                    return(true);
                }
            }

            return(false);
        }
        public SortingResult Sort(Data[] array)
        {
            SortingResult sortingResult = new SortingResult {
                ArrayOfData = array
            };
            var watch = Stopwatch.StartNew();

            for (int i = 1; i < array.Length; i++)
            {
                bool continueComparing = true;
                for (int g = i; g > 0 && continueComparing; g--)
                {
                    continueComparing = (_compareMethod(array[g - 1], array[g]) == 1);
                    sortingResult.CountOfCompares++;

                    if (continueComparing)
                    {
                        Swapper.Swap(ref array[g], ref array[g - 1]);
                        sortingResult.CountOfSwaps++;
                    }
                }
            }


            watch.Stop();
            sortingResult.Time = watch.Elapsed;

            return(sortingResult);
        }
示例#13
0
    public void TerminateEmployee(int index)
    {
      // Clone sensitive objects.
      var tempActiveEmployees = (ArrayList)_activeEmployees.Clone();
      var tempTerminatedEmployees = (ArrayList)_terminatedEmployees.Clone();

      // Perform actions on temp objects.
      object employee = tempActiveEmployees[index];
      tempActiveEmployees.RemoveAt(index);
      tempTerminatedEmployees.Add(employee);

      //  RuntimeHelpers.PrepareConstrainedRegions();
      try
      {
        Console.WriteLine("In try");
      }
      finally
      {
        Swapper.ListSwap(ref _activeEmployees, ref tempActiveEmployees);
        Swapper.ListSwap(ref _terminatedEmployees, ref tempTerminatedEmployees);
      }

      // Keep the console window open in debug mode.
      Console.WriteLine("Press any key to exit.");
      Console.ReadKey();
    }
示例#14
0
        // GET: api/Face
        public async Task <string> Post()
        {
            var data = await Request.Content.ReadAsStringAsync();

            var requestData = JsonConvert.DeserializeObject <RequestBodyData>(data);

            if (requestData.Key != Constants.Key)
            {
                var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    ReasonPhrase = "Incorrect Auth Token."
                };
                throw new HttpResponseException(msg);
            }

            CloudStorage cloudStorage = new CloudStorage();

            string faceFileName   = requestData.FaceFileName;
            string envFileName    = requestData.EnvFileName;
            string outputFileName = "output_" + DateTime.Now.Ticks.ToString() + ".jpg";

            string facePath   = Constants.LocalTempDirectory + faceFileName;
            string envPath    = Constants.LocalTempDirectory + envFileName;
            string outputPath = Constants.LocalTempDirectory + outputFileName;

            cloudStorage.CreateLocalFiles(faceFileName, envFileName);

            Swapper swapper = new Swapper();

            swapper.SwapFaces(facePath, envPath, outputPath);

            cloudStorage.DeleteLocalFiles(facePath, envPath, outputPath);

            return(cloudStorage.GetOutputUri(outputFileName));
        }
示例#15
0
        public override void Sort(IList list)
        {
            var i = 0;
            var k = list.Count - 1;

            while (i < k)
            {
                var min = i;
                var max = i;
                int j;
                for (j = i + 1; j <= k; j++)
                {
                    if (Comparer.Compare(list[j], list[min]) < 0)
                    {
                        min = j;
                    }

                    if (Comparer.Compare(list[j], list[max]) > 0)
                    {
                        max = j;
                    }
                }

                Swapper.Swap(list, min, i);
                Swapper.Swap(list, max == i ? min : max, k);
                i++;
                k--;
            }
        }
示例#16
0
 void OnTriggerExit2D(Collider2D collider)
 {
     foreach (KeyValuePair <Edge, MapNode> item in chunkScript.mapNode.Neighbors)
     {
         Swapper neighborSwapper = item.Value.chunkScript.GetComponentInChildren <Swapper>();
         neighborSwapper.TrySwapInto(collider.attachedRigidbody.gameObject);
     }
 }
示例#17
0
    protected void dgTroca_ItemCommand(object sender, DataGridCommandEventArgs e)
    {
        if (e.CommandName == "Aceitou")
        {
            List <Troca> trocas = (List <Troca>)Session["Trocas"];
            try
            {
                Troca troca = trocas[e.Item.ItemIndex];
                troca.EstaPendente   = false;
                troca.FoiAceita      = true;
                troca.FoiVisualizada = true;

                Aula   aulaAtual      = troca.AlocacaoAtual.Aula;
                Aula   aulaDesejada   = troca.AlocacaoDesejada.Aula;
                Evento eventoAtual    = troca.AlocacaoAtual.Evento;
                Evento eventoDesejado = troca.AlocacaoDesejada.Evento;

                Swapper.Swap <Aula>(ref aulaAtual, ref aulaDesejada);
                Swapper.Swap <Evento>(ref eventoAtual, ref eventoDesejado);

                trocaBO.UpDateTroca(troca);

                troca.AlocacaoAtual.Aula      = aulaAtual;
                troca.AlocacaoDesejada.Aula   = aulaDesejada;
                troca.AlocacaoAtual.Evento    = eventoAtual;
                troca.AlocacaoDesejada.Evento = eventoDesejado;

                alocBO.UpdateAlocacao(troca.AlocacaoAtual);
                alocBO.UpdateAlocacao(troca.AlocacaoDesejada);

                VerificaTrocas();
            }
            catch (Exception)
            {
                Response.Redirect("~/Default/Erro.aspx?Erro=Erro ao aceitar a troca.");
            }
        }

        if (e.CommandName == "Recusou")
        {
            List <Troca> trocas = (List <Troca>)Session["Trocas"];
            try
            {
                Troca troca = trocas[e.Item.ItemIndex];
                troca.EstaPendente   = false;
                troca.FoiAceita      = false;
                troca.FoiVisualizada = true;

                trocaBO.UpDateTroca(troca);

                VerificaTrocas();
            }
            catch (Exception)
            {
                Response.Redirect("~/Default/Erro.aspx?Erro=Erro ao recusar a troca.");
            }
        }
    }
示例#18
0
        public void ByRefMismatch()
        {
            dynamic d = new Swapper();
            long    x = 23;
            int     y = 42;

            d(x, y); // Okay because no write-back.
            Assert.Throws <InvalidCastException>(() => d(ref x, ref y));
        }
示例#19
0
        public void Swap_WithValidArray_IsSuccessful()
        {
            var a = new [] { 1, 2 };

            Swapper <int> .Swap(a, 0, 1);

            Assert.Equal(2, a[0]);
            Assert.Equal(1, a[1]);
        }
示例#20
0
        static void NodeTest()
        {
            Console.WriteLine("I'm testing node");
            string     done       = "";
            Node <int> linkedList = new Node <int>(0);
            Node <int> root       = linkedList;

            while (done != "y")
            {
                Console.WriteLine("Insert an integer for Linked List");
                int value = Convert.ToInt32(Console.ReadLine());
                linkedList.next = new Node <int>(value);
                linkedList      = linkedList.next;
                Console.WriteLine("Are you done adding y/n?");
                done = Console.ReadLine().ToLower();
            }

            Node <int> List = new Node <int>(8);

            List.next = new Node <int>(4, List.root);
            List++;
            List.next = new Node <int>(1, List.root);
            List++;
            List.next = new Node <int>(2, List.root);
            List++;
            List.next = new Node <int>(3, List.root);
            List++;
            List.next = new Node <int>(7, List.root);
            List++;
            List = List.root;
            List.Print();
            List.next.Print();
            Swapper <int> .Swap(List.next, List.next.next);

            Console.WriteLine("THis is swaped virsooooon");
            List.Print();
            //Console.WriteLine("...");
            List.next.Print();

            /*
             *  Node<double> n0 = new Node<double>(0.0);
             *  n0.next = new Node<double>(1.0);
             *  Node<double> www = n0[0];
             *  n0[0].Print();
             *  if(n0 == n1)
             *  {
             *      Console.WriteLine("they are equal");
             *  }
             *  else
             *  {
             *      Console.WriteLine("they are NOT equal");
             *  }
             */
            //       linkedList.Print();
            //       linkedList.PrintAll();
        }
示例#21
0
        public void ByRefInvoke()
        {
            dynamic d = new Swapper();
            int     x = 23;
            int     y = 42;

            d(ref x, ref y);
            Assert.Equal(42, x);
            Assert.Equal(23, y);
        }
示例#22
0
        void invert_onClicked(object sender, InputEngine.MouseArgs e)
        {
            Swapper s = AssociatedComponent as Swapper;

            s.Swapped = !s.Swapped;
            if (Settings.GameState == Settings.GameStates.Stopped)
            {
                s.OrigSwapped = !s.OrigSwapped;
            }
        }
示例#23
0
        /// <summary>
        /// Same as <see cref="Cern.Colt.Partitioning.Partition(int[], int, int, int[], int, int, int[])"/>
        /// except that it <i>synchronously</i> partitions the rows of the given matrix by the values of the given matrix column;
        /// This is essentially the same as partitioning a list of composite objects by some instance variable;
        /// In other words, two entire rows of the matrix are swapped, whenever two column values indicate so.
        /// <p>
        /// Let's say, a "row" is an "object" (tuple, d-dimensional point).
        /// A "column" is the list of "object" values of a given variable (field, dimension).
        /// A "matrix" is a list of "objects" (tuples, points).
        /// <p>
        /// Now, rows (objects, tuples) are partially sorted according to their values in one given variable (dimension).
        /// Two entire rows of the matrix are swapped, whenever two column values indicate so.
        /// <p>
        /// Note that arguments are not checked for validity.
        ///
        /// </summary>
        /// <param name="matrix">
        /// the matrix to be partitioned.
        /// </param>
        /// <param name="rowIndexes">
        /// the index of the i-th row; is modified by this method to reflect partitioned indexes.
        /// </param>
        /// <param name="rowFrom">
        /// the index of the first row (inclusive).
        /// </param>
        /// <param name="rowTo">
        /// the index of the last row (inclusive).
        /// </param>
        /// <param name="column">
        /// the index of the column to partition on.
        /// </param>
        /// <param name="splitters">
        /// the values at which the rows shall be split into intervals.
        /// Must be sorted ascending and must not contain multiple identical values.
        /// These preconditions are not checked; be sure that they are met.
        /// </param>
        /// <param name="splitFrom">
        /// the index of the first splitter element to be considered.
        /// </param>
        /// <param name="splitTo">
        /// the index of the last splitter element to be considered.
        /// The method considers the splitter elements<i>splitters[splitFrom] .d splitters[splitTo]</i>.
        /// </param>
        /// <param name="splitIndexes">
        /// a list into which this method fills the indexes of rows delimiting intervals.
        /// Upon return <i>splitIndexes[splitFrom..splitTo]</i> will be set accordingly.
        /// Therefore, must satisfy <i>splitIndexes.Length >= splitters.Length</i>.
        /// </param>
        /// <example>
        /// <table border="1" cellspacing="0">
        ///           <tr nowrap>
        ///             <td valign="top"><i>8 x 3 matrix:<br>
        ///               23, 22, 21<br>
        ///               20, 19, 18<br>
        ///               17, 16, 15<br>
        ///               14, 13, 12<br>
        ///               11, 10, 9<br>
        ///               8,  7,  6<br>
        ///               5,  4,  3<br>
        ///               2,  1,  0 </i></td>
        ///             <td align="left" valign="top">
        ///               <p><i>column = 0;<br>
        ///                 rowIndexes = {0,1,2,.d,matrix.Rows-1};
        ///                 rowFrom = 0;<br>
        ///                 rowTo = matrix.Rows-1;<br>
        ///                 splitters = {5,10,12}<br>
        ///                 c = 0; <br>
        ///                 d = splitters.Length-1;<br>
        ///                 partition(matrix,rowIndexes,rowFrom,rowTo,column,splitters,c,d,splitIndexes);<br>
        ///                 ==><br>
        ///                 splitIndexes == {0, 2, 3}<br>
        ///                 rowIndexes == {7, 6, 5, 4, 0, 1, 2, 3}</i></p>
        ///               </td>
        ///             <td valign="top">
        ///               The matrix IS NOT REORDERED.<br>
        ///               Here is how it would look<br>
        ///               like, if it would be reordered<br>
        ///               accoring to <i>rowIndexes</i>.<br>
        ///               <i>8 x 3 matrix:<br>
        ///               2,  1,  0<br>
        ///               5,  4,  3<br>
        ///               8,  7,  6<br>
        ///               11, 10, 9<br>
        ///               23, 22, 21<br>
        ///               20, 19, 18<br>
        ///               17, 16, 15<br>
        ///               14, 13, 12 </i></td>
        ///           </tr>
        /// </table>
        /// </example>
        public static void Partition(DoubleMatrix2D matrix, int[] rowIndexes, int rowFrom, int rowTo, int column, double[] splitters, int splitFrom, int splitTo, int[] splitIndexes)
        {
            if (rowFrom < 0 || rowTo >= matrix.Rows || rowTo >= rowIndexes.Length)
            {
                throw new ArgumentException();
            }
            if (column < 0 || column >= matrix.Columns)
            {
                throw new ArgumentException();
            }
            if (splitFrom < 0 || splitTo >= splitters.Length)
            {
                throw new ArgumentException();
            }
            if (splitIndexes.Length < splitters.Length)
            {
                throw new ArgumentException();
            }

            // this one knows how to swap two row indexes (a,b)
            int[]   g       = rowIndexes;
            Swapper swapper = new Swapper((b, c) =>
            {
                int tmp = g[b]; g[b] = g[c]; g[c] = tmp;
            });

            // compare splitter[a] with columnView[rowIndexes[b]]
            DoubleMatrix1D columnView = matrix.ViewColumn(column);
            IntComparator  comp       = new IntComparator((a, b) =>
            {
                double av = splitters[a];
                double bv = columnView[g[b]];
                return(av < bv ? -1 : (av == bv ? 0 : 1));
            });

            // compare columnView[rowIndexes[a]] with columnView[rowIndexes[b]]
            IntComparator comp2 = new IntComparator((a, b) =>
            {
                double av = columnView[g[a]];
                double bv = columnView[g[b]];
                return(av < bv ? -1 : (av == bv ? 0 : 1));
            });

            // compare splitter[a] with splitter[b]
            IntComparator comp3 = new IntComparator((a, b) =>
            {
                double av = splitters[a];
                double bv = splitters[b];
                return(av < bv ? -1 : (av == bv ? 0 : 1));
            });

            // generic partitioning does the main work of reordering row indexes
            Cern.Colt.Partitioning.GenericPartition(rowFrom, rowTo, splitFrom, splitTo, splitIndexes, comp, comp2, comp3, swapper);
        }
示例#24
0
        public void SwapperSwapsStringBoxesInList()
        {
            List <Box <string> > numbers = new List <Box <string> >();

            numbers.Add(new Box <string>("Pesho"));
            numbers.Add(new Box <string>("Ivan"));


            Swapper.Swap(numbers, 0, 1);
            Assert.IsTrue(numbers[0].Item == "Ivan" && numbers[1].Item == "Pesho");
        }
示例#25
0
        public void SwapperSwapsBoxesInList()
        {
            List <Box <int> > numbers = new List <Box <int> >();

            numbers.Add(new Box <int>(2));
            numbers.Add(new Box <int>(5));


            Swapper.Swap(numbers, 0, 1);
            Assert.IsTrue(numbers[0].Item == 5 && numbers[1].Item == 2);
        }
示例#26
0
        /// <summary>
        /// This is a generic version of C.A.R Hoare's Quick Sort
        /// algorithm.  This will handle arrays that are already
        /// sorted, and arrays with duplicate keys.
        /// </summary>
        /// <remarks>
        /// If you think of a one dimensional array as going from
        /// the lowest index on the left to the highest index on the right
        /// then the parameters to this function are lowest index or
        /// left and highest index or right.  The first time you call
        /// this function it will be with the parameters 0, a.length - 1.
        /// </remarks>
        /// <param name="list">list to sort</param>
        /// <param name="l">left boundary of array partition</param>
        /// <param name="r">right boundary of array partition</param>
        internal void QuickSort(IList list, int l, int r)
        {
            const int m = 4;

            if (r - l <= m)
            {
                return;
            }

            var i = (r + l) / 2;

            if (Comparer.Compare(list[l], list[i]) > 0)
            {
                Swapper.Swap(list, l, i); // Tri-Median Methode!
            }

            if (Comparer.Compare(list[l], list[r]) > 0)
            {
                Swapper.Swap(list, l, r);
            }

            if (Comparer.Compare(list[i], list[r]) > 0)
            {
                Swapper.Swap(list, i, r);
            }

            var j = r - 1;

            Swapper.Swap(list, i, j);
            i = l;
            var v = list[j];

            for (;;)
            {
                while (Comparer.Compare(list[++i], v) > 0)
                {
                }

                while (Comparer.Compare(list[--j], v) < 0)
                {
                }

                if (j < i)
                {
                    break;
                }

                Swapper.Swap(list, i, j);
            }

            Swapper.Swap(list, i, r - 1);
            QuickSort(list, l, j);
            QuickSort(list, i + 1, r);
        }
示例#27
0
        public void should_be_swapped_for_simple_type()
        {
            var swapper = new Swapper<int>();

            var i = 5;
            var j = 10;

            swapper.Execute(ref i, ref j);

            Assert.AreEqual(5, j);
            Assert.AreEqual(10, i);
        }
示例#28
0
        internal void SortPart1(IList list, int Lo, int Hi, int Nx, bool Up)
        {
            int c;

            for (int j = Lo; j + Nx < Hi; j += 2 * Nx)
            {
                c = Comparer.Compare(list[j], list[j + Nx]);
                if ((Up && c > 0) || !Up && c < 0)
                {
                    Swapper.Swap(list, j, j + Nx);
                }
            }
        }
示例#29
0
    void Start()
    {
        guis = new Swapper <GuiState, GameObject>(
            GUIs.ToDictionary(kp => kp.Key, kp => { kp.Value.SetActive(false); return(kp.Value); }),
            (gui, active) => gui.SetActive(active)
            );
        cameras = new Swapper <CameraState, Camera>(
            Cameras.ToDictionary(kp => kp.Key, kp => kp.Value),
            (camera, active) => camera.enabled = active
            );

        GoMainMenu();
    }
示例#30
0
 public override void Sort(IList list)
 {
     for (var i = list.Count; --i >= 0;)
     {
         for (var j = 0; j < i; j++)
         {
             if (Comparer.Compare(list[j], list[j + 1]) > 0)
             {
                 Swapper.Swap(list, j, j + 1);
             }
         }
     }
 }
示例#31
0
        private void Sort(IList list, int fromPos, int toPos, object[] scratch)
        {
            if (fromPos >= toPos)
            {
                return;
            }

            var mid = (fromPos + toPos) / 2;

            Sort(list, fromPos, mid, scratch);
            Sort(list, mid + 1, toPos, scratch);

            var tLow  = fromPos;
            var tHigh = mid + 1;
            int i;

            for (i = fromPos; i <= toPos; i++)
            {
                if (tLow <= mid)
                {
                    if (tHigh > toPos)
                    {
                        scratch[i] = list[tLow];
                        tLow++;
                    }
                    else
                    {
                        if (Comparer.Compare(list[tLow], list[tHigh]) < 0)
                        {
                            scratch[i] = list[tLow];
                            tLow++;
                        }
                        else
                        {
                            scratch[i] = list[tHigh];
                            tHigh++;
                        }
                    }
                }
                else
                {
                    scratch[i] = list[tHigh];
                    tHigh++;
                }
            }

            for (i = fromPos; i <= toPos; i++)
            {
                Swapper.Set(list, i, scratch[i]);
            }
        }
示例#32
0
        public void should_be_swapped_for_complex_type()
        {
            var swapper = new Swapper<SwapperTestClass>();

            var left = new SwapperTestClass { Id = 0, Name = "OLD LEFT" };
            var right = new SwapperTestClass { Id = 1, Name = "OLD RIGHT" };

            swapper.Execute(ref left, ref right);

            Assert.AreEqual(1, left.Id);
            Assert.AreEqual("OLD RIGHT", left.Name);
            Assert.AreEqual(0, right.Id);
            Assert.AreEqual("OLD LEFT", right.Name);
        }
示例#33
0
 public void ByRefInvoke()
 {
     dynamic d = new Swapper();
     int x = 23;
     int y = 42;
     d(ref x, ref y);
     Assert.Equal(42, x);
     Assert.Equal(23, y);
 }
示例#34
0
 public void ByRefMismatch()
 {
     dynamic d = new Swapper();
     long x = 23;
     int y = 42;
     d(x, y); // Okay because no write-back.
     Assert.Throws<InvalidCastException>(() => d(ref x, ref y));
 }
示例#35
0
    public void StartSwapping(Swapper.SwapDirection direction, bool swapFront)
    {
        State = BlockState.Swapping;

        Direction = direction;

        SwapFront = swapFront;

        grid.ChangeState(X, Y, this, GridElement.ElementState.Immutable);
    }