private int Partitions(T[] array, int lowIndex, int highIndex) { T pivot = array[highIndex]; // index of smaller element int i = (lowIndex - 1); for (int j = lowIndex; j < highIndex; j++) { string[] jthArr = array[j].ToString().Trim().Split(' '); string[] pivArr = pivot.ToString().Trim().Split(' '); // If current element is smaller than or equal to pivot if (_comparator.Compare(array[j], pivot) <= 0) { i++; // swap arr[i] and arr[j] T ith = array[i]; array[i] = array[j]; array[j] = ith; } } // swap arr[i+1] and arr[high] (or pivot) T holder = array[i + 1]; array[i + 1] = array[highIndex]; array[highIndex] = holder; return(i + 1); }
public virtual void TestArrayComparator() { IComparator <bool[]> ac = Comparators.GetArrayComparator(); NUnit.Framework.Assert.IsTrue(ac.Compare(new bool[] { true, false, true }, new bool[] { true, false, true }) == 0); NUnit.Framework.Assert.IsTrue(ac.Compare(new bool[] { true, false, true }, new bool[] { true, false }) > 0); NUnit.Framework.Assert.IsTrue(ac.Compare(new bool[] { true, false, true }, new bool[] { true, false, true, false }) < 0); NUnit.Framework.Assert.IsTrue(ac.Compare(new bool[] { false, false, true }, new bool[] { true, false, true }) < 0); }
public virtual void TestNullSafeComparator() { IComparator <int> comp = Comparators.NullSafeNaturalComparator(); NUnit.Framework.Assert.AreEqual(0, comp.Compare(null, null)); NUnit.Framework.Assert.AreEqual(-1, comp.Compare(null, int.Parse(42))); NUnit.Framework.Assert.AreEqual(1, comp.Compare(int.Parse(42), null)); NUnit.Framework.Assert.AreEqual(-1, comp.Compare(11, 18)); NUnit.Framework.Assert.AreEqual(0, comp.Compare(11, 11)); }
public virtual void TestListComparator() { IComparator <IList <string> > lc = Comparators.GetListComparator(); string[] one = new string[] { "hello", "foo" }; string[] two = new string[] { "hi", "foo" }; string[] three = new string[] { "hi", "foo", "bar" }; NUnit.Framework.Assert.IsTrue(lc.Compare(Arrays.AsList(one), Arrays.AsList(one)) == 0); NUnit.Framework.Assert.IsTrue(lc.Compare(Arrays.AsList(one), Arrays.AsList(two)) < 0); NUnit.Framework.Assert.IsTrue(lc.Compare(Arrays.AsList(one), Arrays.AsList(three)) < 0); NUnit.Framework.Assert.IsTrue(lc.Compare(Arrays.AsList(three), Arrays.AsList(two)) > 0); }
public List <Group> Compute(Group news, uint K, uint maxIterations) { var rand = new Random(); var centroids = new Vector[K]; //1. Losuj K newsow for (int i = 0; i < K; i++) { News n = news[rand.Next() % news.Count]; centroids[i] = new Vector(stats, n, maxLen); centroids[i].BuildVector(); } var assigment = new int[news.Count]; var vectors = new Vector[news.Count]; // /// Petla for (int iteration = 0; iteration < maxIterations; iteration++) { // liczenie przydzialu for (int i = 0; i < news.Count; i++) { vectors[i] = new Vector(stats, news[i], maxLen); vectors[i].BuildVector(); int min = 0; double maxVal = comparator.Compare(centroids[0], vectors[i]); for (int j = 1; j < centroids.Length; j++) { double val = comparator.Compare(centroids[j], vectors[i]); if (val > maxVal) { maxVal = val; min = j; } } assigment[i] = min; } // liczymy centroidy centroids = ComputeNewCentroids(K, assigment, vectors, centroids); } return(GetCurrentSet(news, assigment, K)); }
public void CompareImages(XRayImage xRayImageBefore, XRayImage xRayImageAfter, XRayImage imagesDiff, IComparator comparator) { var imageBefore = xRayImageBefore.XRayBitmap; var imageAfter = xRayImageAfter.XRayBitmap; if (imageBefore.PixelWidth != imageAfter.PixelWidth || imageBefore.PixelHeight != imageAfter.PixelHeight) { throw new System.Exception("Bitmaps have different dimensions"); } BitmapSource bitmapSourceBefore = new FormatConvertedBitmap(imageBefore, PixelFormats.Pbgra32, null, 0); BitmapSource bitmapSourceAfter = new FormatConvertedBitmap(imageAfter, PixelFormats.Pbgra32, null, 0); var imageBeforeWritable = new WriteableBitmap(bitmapSourceBefore); var imageAfterWritable = new WriteableBitmap(bitmapSourceAfter); var imagesDiffWritable = new WriteableBitmap(bitmapSourceAfter); var width = imageAfter.PixelWidth; var height = imageAfter.PixelHeight; var pixelDataBefore = new int[width * height]; var pixelDataAfter = new int[width * height]; var pixelDataDiff = new int[width * height]; var widthInByte = 4 * imageAfter.PixelWidth; imageBeforeWritable.CopyPixels(pixelDataBefore, widthInByte, 0); imageAfterWritable.CopyPixels(pixelDataAfter, widthInByte, 0); imagesDiffWritable.CopyPixels(pixelDataDiff, widthInByte, 0); comparator.Compare(pixelDataBefore, pixelDataAfter, pixelDataDiff, width, height); imagesDiffWritable.WritePixels(new Int32Rect(0, 0, width, height), pixelDataDiff, widthInByte, 0); imagesDiff.XRayBitmap = imagesDiffWritable.ToBitmapImage(); }
public double Compare(string v1, string v2) { if (v1.Equals(v2)) { return(1.0); } // tokenize String[] t1 = StringUtils.Split(v1); String[] t2 = StringUtils.Split(v2); // ensure that t1 is shorter than or same length as t2 if (t1.Length > t2.Length) { String[] tmp = t2; t2 = t1; t1 = tmp; } // find best matches for each token in t1 double sum = 0; for (int ix1 = 0; ix1 < t1.Length; ix1++) { double highest = 0; for (int ix2 = 0; ix2 < t2.Length; ix2++) { highest = Math.Max(highest, _subcomp.Compare(t1[ix1], t2[ix2])); } sum += highest; } return((sum * 2) / (t1.Length + t2.Length)); }
public override void Sort(List <T> list, int start, int end, IComparator <T> comparator) { for (int i = start + 1; i < end; i++) { T current = list[i]; T prev = list[i - 1]; if (comparator.Compare(current, prev) < 0) { int j = i; do { list[j--] = prev; } while (j > start && comparator.Compare(current, prev = list[j - 1]) < 0); } } }
private void btnCompare_Click(object sender, EventArgs e) { var input = txtInput.Text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); var patterns = txtPatterns.Text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); var output = m_selectedComparator.Compare(input, patterns); StringBuilder result = new StringBuilder(); foreach (var str in output) { result.AppendLine(str); } txtOutput.Text = result.ToString(); }
public static AnyType findMax <AnyType>(AnyType[] a, IComparator <AnyType> cmp) { int maxIndex = 0; for (int i = 1; i < a.Length; i++) { if (cmp.Compare(a[i], a[maxIndex]) > 0) { maxIndex = i; } } return(a[maxIndex]); }
public static int Search(T[] collection, T key, IComparator <T> comparator) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } if (collection.Length == 0) { throw new ArgumentException(nameof(collection)); } int min = 0; int max = collection.Length - 1; while (min <= max) { int mid = (min + max) / 2; int comperedValue = 0; if (comparator != null) { comperedValue = comparator.Compare(key, collection[mid]); } else { var enumerable = key as IComparable <T>; if (enumerable != null) { comperedValue = enumerable.CompareTo(collection[mid]); } else { throw new InvalidOperationException(); } } if (comperedValue == 0) { return(mid); } if (comperedValue < 0) { max = mid - 1; } else { min = mid + 1; } } return(-1); }
/// <summary>Finds and returns the key in this Counter with the smallest count.</summary> /// <remarks> /// Finds and returns the key in this Counter with the smallest count. /// Ties are broken by comparing the objects using the given tie breaking /// Comparator, favoring Objects that are sorted to the front. This is useful /// if the keys are numeric and there is a bias to prefer smaller or larger /// values, and can be useful in other circumstances where random tie-breaking /// is not desirable. Returns null if this Counter is empty. /// </remarks> public virtual E Argmin(IComparator <E> tieBreaker) { int min = int.MaxValue; E argmin = null; foreach (E key in map.Keys) { int count = GetIntCount(key); if (argmin == null || count < min || (count == min && tieBreaker.Compare(key, argmin) < 0)) { min = count; argmin = key; } } return(argmin); }
/// <summary>Finds and returns the key in this Counter with the largest count.</summary> /// <remarks> /// Finds and returns the key in this Counter with the largest count. /// Ties are broken by comparing the objects using the given tie breaking /// Comparator, favoring Objects that are sorted to the front. This is useful /// if the keys are numeric and there is a bias to prefer smaller or larger /// values, and can be useful in other circumstances where random tie-breaking /// is not desirable. Returns null if this Counter is empty. /// </remarks> public virtual E Argmax(IComparator <E> tieBreaker) { int max = int.MinValue; E argmax = null; foreach (E key in KeySet()) { int count = GetIntCount(key); if (argmax == null || count > max || (count == max && tieBreaker.Compare(key, argmax) < 0)) { max = count; argmax = key; } } return(argmax); }
public static void Sort <T>(T[] arr, IComparator <T> comparator) { T temp = default(T); for (int iteration = 0; iteration < arr.Length; iteration++) { for (int index = 0; index < arr.Length - 1; index++) { if (comparator.Compare(arr[index], arr[index + 1]) > 0) { temp = arr[index + 1]; arr[index + 1] = arr[index]; arr[index] = temp; } } } }
/// <summary> Sorts its argument (destructively) using insert sort; in the context of this package /// insertion sort is simple and efficient given its relatively small inputs. /// /// </summary> /// <param name="vector">vector to sort /// </param> /// <param name="comparator">comparator to define sort ordering /// </param> public static void InsertionSort(ArrayList vector, IComparator comparator) { int max = vector.Count; for (int i = 1; i < max; i++) { object value_Renamed = vector[i]; int j = i - 1; object valueB; while (j >= 0 && comparator.Compare(valueB = vector[j], value_Renamed) > 0) { vector[j + 1] = valueB; j--; } vector[j + 1] = value_Renamed; } }
/// <summary> /// Sort matrix using a BubbleSort algorithm based on values of sz-array elements /// </summary> /// <param name="matrix">Matrix</param> /// <param name="comparator">Comparator</param> public static void Sort(int[][] matrix, IComparator comparator) { if (matrix == null) { throw new ArgumentNullException(); } for (int i = 0; i < matrix.Length - i; i++) { for (int j = 0; j < matrix.Length - i - 1; j++) { if (comparator.Compare(matrix[j], matrix[j + 1]) == 1) { SwapMatrixStrings(ref matrix[j], ref matrix[j + 1]); } } } }
/// <summary> /// search on searchable using Best First Search algorithm /// </summary> /// <param name="searchable">obj that can be searched on, has functions initialize/goal state and get all possible states from specific state</param> /// <param name="comparator">has function copmare which helped the comparator param to determine who's better state to came from</param> /// <returns>the solution of the BFS algorithm: /// path to the goal and the number of state that evaluated</returns> public override Solution <T> Search(ISearchable <T> searchable, IComparator <T> comparator) { State <T> state = searchable.GetInitializeState(); state.Cost = 1; state.CameFrom = null; AddToOpenList(state, 1); HashSet <State <T> > closed = new HashSet <State <T> >(); while (OpenListSize > 0) { State <T> currentState = PopOpenList(); closed.Add(currentState); if (currentState.Equals(searchable.GetGoalState())) { return(BackTrace(ref currentState)); } List <State <T> > succerssors = searchable.GetAllPossibleStates(currentState); foreach (State <T> s in succerssors) { if (!closed.Contains(s) && !OpenContains(s)) { s.Cost = currentState.Cost + 1; s.CameFrom = currentState; AddToOpenList(s, 1); } else if (comparator.Compare(s, currentState) == 1) { if (!OpenContains(s)) { s.Cost = currentState.Cost + 1; s.CameFrom = currentState; AddToOpenList(s, 1); } else { RemoveAndAddElementToOpenList(s, currentState.Cost + 1); } } } } return(null); }
private double[,] computeDistances(Group news) { double[,] distances = new double[news.Count, news.Count]; for (int i = news.Count - 1; i >= 0; i--) { Vector row = new Vector(stats, news[i], 1000); row.BuildVector(); for (int j = 0; j < i; j++) { Vector col = new Vector(stats, news[j], 1000); col.BuildVector(); distances[i, j] = comp.Compare(row, col); distances[j, i] = distances[i, j]; } } return(distances); }
public double Compare(string v1, string v2) { if (v1.Equals(v2)) { return(1.0); } // tokenize String[] t1 = StringUtils.Split(v1); String[] t2 = StringUtils.Split(v2); //FIXME: we assume t1 and t2 do not have internal duplicates // ensure that t1 is shorter than or same length as t2 if (t1.Length > t2.Length) { String[] tmp = t2; t2 = t1; t1 = tmp; } // find best matches for each token in t1 double intersection = 0; double union = t1.Length + t2.Length; for (int ix1 = 0; ix1 < t1.Length; ix1++) { double highest = 0; for (int ix2 = 0; ix2 < t2.Length; ix2++) { highest = Math.Max(highest, _subcomp.Compare(t1[ix1], t2[ix2])); } // INV: the best match for t1[ix1] in t2 is has similarity highest intersection += highest; union -= highest; // we reduce the union by this similarity } return(intersection / union); }
private double[,] computeDistances(Group news) { double[,] distances = new double[news.Count, news.Count]; for (int i = news.Count - 1; i >= 0; i--) { Vector row = new Vector(stats, news[i], maxLen); row.BuildVector(); for (int j = 0; j < i; j++) { Vector col = new Vector(stats, news[j], maxLen); col.BuildVector(); distances[i, j] = comparator.Compare(row, col); distances[j, i] = distances[i, j]; //Console.Write(distances[i, j] + " "); } //Console.WriteLine(i); } return(distances); }
private List <int> getNeighbours(int current, Group news, State[] states, double eps) { // Result - indices of news that are neighbours of current news. List <int> neighbours = new List <int>(); // Look through all possibly unvisited neighbours. Maybe can be done more effective. for (int i = 0; i < news.Count; i++) { // Look only for unvisited states. if (i == current || states[i] == State.noise) { continue; } // If the news is near enough. Add to neighbours. if (Math.Abs(comparator.Compare(newsVectors[current], newsVectors[i])) >= eps) { neighbours.Add(i); } } return(neighbours); }
private int Compare(ArrayHeap.HeapEntry <E> entryA, ArrayHeap.HeapEntry <E> entryB) { return(cmp.Compare(entryA.@object, entryB.@object)); }
public void Analyze(string path1, string path2) { _writer.Write( _comparator.Compare( _readers.Find(x => path1.EndsWith(x._format)).ReadToTable(path1), _readers.Find(x => path2.EndsWith(x._format)).ReadToTable(path2))); }
public int CompareTo(Slice other, IComparator comparator = null) { if (comparator == null) { comparator = ByteWiseComparator.Default; } return comparator.Compare(this, other); }
private bool BeforeFile(IComparator comparator, Slice key, FileMetadata file) { // Empty 'key' occurs after all keys and is therefore never before 'file' return (key.IsEmpty() == false && comparator.Compare(key, file.SmallestKey.UserKey) < 0); }
private bool AfterFile(IComparator comparator, Slice key, FileMetadata file) { // Empty 'key' occurs before all keys and is therefore never after 'file' return (key.IsEmpty() == false && comparator.Compare(key, file.LargestKey.UserKey) > 0); }
public ItemState Get(InternalKey key, ulong fileNumber, long fileSize, ReadOptions readOptions, IComparator comparator, out Stream stream) { Table table = FindTable(fileNumber, fileSize); Tuple<Slice, Stream> result = table.InternalGet(readOptions, key); stream = null; if (result == null) { return ItemState.NotFound; } bool shouldDispose = true; try { InternalKey internalKey; if (!InternalKey.TryParse(result.Item1, out internalKey)) { return ItemState.Corrupt; } if (comparator.Compare(internalKey.UserKey, key.UserKey) == 0) { bool isFound = internalKey.Type == ItemType.Value; if (!isFound) { return ItemState.Deleted; } stream = result.Item2; shouldDispose = false; return ItemState.Found; } return ItemState.NotFound; } finally { if (shouldDispose && result.Item2 != null) result.Item2.Dispose(); } }
public string getData(List <News> news, WordsStats stats, int maxLen, IComparator comp) { StringBuilder sb = new StringBuilder(); double standardDeviation; double average; double aritm; double min = double.MaxValue; double max = double.MinValue; double sum = 0.0; int c = 0; int zeroCount = 0; int cLinks = 0; double[,] dist = new double[news.Count, news.Count]; for (int i = 0; i < news.Count; i++) { Vector x = new Vector(stats, news[i], maxLen); x.BuildVector(); for (int j = 0; j < i; j++) { Vector y = new Vector(stats, news[j], maxLen); y.BuildVector(); double res = comp.Compare(x, y); dist[i, j] = res; if (res == 0) { zeroCount++; } min = Math.Min(min, res); max = Math.Max(max, res); sum += res; c++; //cLinks += commonLinks(news[i], news[j]); if (c % 10000 == 0) { Console.WriteLine(c); } //Console.WriteLine(cLinks); } } average = sum / c; double devSum = 0.0; double artSum = 0.0; c = 0; for (int i = 0; i < news.Count; i++) { for (int j = 0; j < i; j++) { devSum += dist[i, j] * dist[i, j]; artSum += Math.Abs(dist[i, j] - average); c++; } } standardDeviation = Math.Sqrt((devSum / c) - (average * average)); aritm = artSum / c; sb.Append("Data information:\n"); sb.Append("Minimum distance = " + min.ToString() + "\n"); sb.Append("Maximum distance = " + max.ToString() + "\n"); sb.Append("Average distance = " + average.ToString() + "\n"); sb.Append("Zero count = " + zeroCount + "\n"); sb.Append("Standard deviation = " + standardDeviation.ToString() + "\n"); sb.Append("Arithmetic median = " + aritm.ToString() + "\n"); //sb.Append("Common links average = " + (cLinks / c) + "\n"); sb.Append("End data information\n"); return(sb.ToString()); }
/** * Appends to the <code>builder</code> the comparison of * two <code>Object</code>s. * * <ol> * <li>Check if <code>lhs == rhs</code></li> * <li>Check if either <code>lhs</code> or <code>rhs</code> is <code>null</code>, * a <code>null</code> object is less than a non-<code>null</code> object</li> * <li>Check the object contents</li> * </ol> * * If <code>lhs</code> is an array, array comparison methods will be used. * Otherwise <code>comparator</code> will be used to compare the objects. * If <code>comparator</code> is <code>null</code>, <code>lhs</code> must * implement {@link Comparable} instead. * * @param lhs left-hand object * @param rhs right-hand object * @param comparator <code>IComparator</code> used to compare the objects, * <code>null</code> means treat lhs as <code>Comparable</code> * @return this - used to chain append calls * @throws ClassCastException if <code>rhs</code> is not assignment-compatible * with <code>lhs</code> * @since 2.0 */ public CompareToBuilder Append(Object lhs, Object rhs, IComparator comparator) { if (comparison != 0) { return(this); } if (lhs == rhs) { return(this); } if (lhs == null) { comparison = -1; return(this); } if (rhs == null) { comparison = +1; return(this); } if (lhs.GetType().IsArray) { // switch on type of array, to dispatch to the correct handler // handles multi dimensional arrays // throws a ClassCastException if rhs is not the correct array type if (lhs is long[]) { Append((long[])lhs, (long[])rhs); } else if (lhs is int[]) { Append((int[])lhs, (int[])rhs); } else if (lhs is short[]) { Append((short[])lhs, (short[])rhs); } else if (lhs is char[]) { Append((char[])lhs, (char[])rhs); } else if (lhs is byte[]) { Append((byte[])lhs, (byte[])rhs); } else if (lhs is double[]) { Append((double[])lhs, (double[])rhs); } else if (lhs is float[]) { Append((float[])lhs, (float[])rhs); } else if (lhs is bool[]) { Append((bool[])lhs, (bool[])rhs); } else { // not an array of primitives // throws a ClassCastException if rhs is not an array Append((Object[])lhs, (Object[])rhs, comparator); } } else { // the simple case, not an array, just test the element if (comparator == null) { comparison = ((IComparable)lhs).CompareTo(rhs); } else { comparison = comparator.Compare(lhs, rhs); } } return(this); }