/// <summary> /// Use binary search to find all Isotopic Peaks we want to consider when looking for the cross-links shifts. /// </summary> /// <param name="completePeakList">The complete list of Isotopic Peaks that we will use for searching.</param> /// <param name="minimumMz">The minimum m/z value to consider.</param> /// <param name="scanLc">The LC Scan to consider.</param> /// <param name="scanIms">The IMS Scan to consider.</param> /// <returns>All peaks that are in the given LC Scan and IMS Scan and m/z >= thegiven m/z of the Feature.</returns> public static List<IPeak> FindCandidatePeaks(List<IsotopicPeak> completePeakList, double minimumMz, int scanLc, int scanIms) { // Set up Peak Comparer to use for binary search later on AnonymousComparer<IsotopicPeak> peakComparer = new AnonymousComparer<IsotopicPeak>((x, y) => x.ScanLc != y.ScanLc ? x.ScanLc.CompareTo(y.ScanLc) : x.ScanIms != y.ScanIms ? x.ScanIms.CompareTo(y.ScanIms) : x.Mz.CompareTo(y.Mz)); IsotopicPeak lowPeak = new IsotopicPeak {ScanLc = scanLc, ScanIms = scanIms, Mz = minimumMz, Intensity = 1}; IsotopicPeak highPeak = new IsotopicPeak { ScanLc = scanLc, ScanIms = scanIms + 1, Mz = 0, Intensity = 1 }; int lowPeakPosition = completePeakList.BinarySearch(lowPeak, peakComparer); int highPeakPosition = completePeakList.BinarySearch(highPeak, peakComparer); lowPeakPosition = lowPeakPosition < 0 ? ~lowPeakPosition : lowPeakPosition; highPeakPosition = highPeakPosition < 0 ? ~highPeakPosition : highPeakPosition; List<IPeak> candidatePeaks = new List<IPeak>(); for (int j = lowPeakPosition; j < highPeakPosition; j++) { IsotopicPeak peak = completePeakList[j]; MSPeak msPeak = new MSPeak(peak.Mz, peak.Intensity, 0.05f, 1); candidatePeaks.Add(msPeak); } return candidatePeaks; }
public static void Main() { List<string> dinosaurs = new List<string>(); dinosaurs.Add("Pachycephalosaurus"); dinosaurs.Add("Amargasaurus"); dinosaurs.Add("Mamenchisaurus"); dinosaurs.Add("Deinonychus"); Console.WriteLine(); foreach(string dinosaur in dinosaurs) { Console.WriteLine(dinosaur); } Console.WriteLine("\nSort"); dinosaurs.Sort(); Console.WriteLine(); foreach(string dinosaur in dinosaurs) { Console.WriteLine(dinosaur); } Console.WriteLine("\nBinarySearch and Insert \"Coelophysis\":"); int index = dinosaurs.BinarySearch("Coelophysis"); if (index < 0) { dinosaurs.Insert(~index, "Coelophysis"); } Console.WriteLine(); foreach(string dinosaur in dinosaurs) { Console.WriteLine(dinosaur); } Console.WriteLine("\nBinarySearch and Insert \"Tyrannosaurus\":"); index = dinosaurs.BinarySearch("Tyrannosaurus"); if (index < 0) { dinosaurs.Insert(~index, "Tyrannosaurus"); } Console.WriteLine(); foreach(string dinosaur in dinosaurs) { Console.WriteLine(dinosaur); } }
public static List<IRating> ImportFromDataset(string filename, List<string> users, List<string> artists, int limit = int.MaxValue) { TextReader reader = new StreamReader(filename); var ratings = new List<IRating>(); string line; var sep = new[] {"\t"}; while ((line = reader.ReadLine()) != null && limit > 0) { limit--; var parts = line.Split(sep, StringSplitOptions.None); var userIndex = users.BinarySearch(parts[0]); if (userIndex < 0) continue; ratings.Add(new Rating( userIndex, artists.BinarySearch(parts[2]), float.Parse(parts[3], CultureInfo.InvariantCulture) )); } reader.Close(); return ratings; }
static void Main() { Console.WriteLine("Enter the word:"); string word = Console.ReadLine(); List<char> wordSymbols = new List<char>(); for (int i = 0; i < word.Length; i++) { wordSymbols.Add(word[i]); } //using the ACII table for filling o f the array with leters List<char> letters = new List<char>(); for (int i = 65; i < 122; i++) { letters.Add((char)i); //jump to lowercase "a" if (i==90) { i = 96; } } //sorting the char array in order to use BinarySearch for representation of the letter index letters.Sort(); for (int i = 0; i < wordSymbols.Count; i++) { Console.WriteLine("The postion of the letter {0} is {1}",wordSymbols[i], letters.BinarySearch(wordSymbols[i])); } Console.WriteLine("\nThe array with letters is ordered as follows /index -> value/:"); for (int i = 0; i < letters.Count; i++) { Console.Write("{1} -> {0}; ", letters[i], i); } Console.WriteLine(); }
static void Main(string[] args) { List<Contact> phoneBook = new List<Contact>(); Contact p1 = new Contact("Gerry", "123"); Contact p2 = new Contact("Test", "456"); Contact p3 = new Contact("Test3", "789"); //add one contact phoneBook.Add(p1); //add two contacts phoneBook.AddRange(new Contact[]{p2,p3}); //remove the first contact //phoneBook.RemoveAt(0); //find the contact in the List, based on the compareTo method Contact ctofind = new Contact("Gerry", ""); //write Console.WriteLine(phoneBook.BinarySearch(ctofind)); foreach (Contact p in phoneBook) Console.WriteLine(p.Name + " " + p.Telnumber); Console.ReadLine(); }
static void Main(string[] args) { checked { Stopwatch sw = new Stopwatch(); List<BigInteger> squares = new List<BigInteger>(); BigInteger pmax = 0; sw.Start(); for (BigInteger i = 1; i < 1000; i++) { //Console.WriteLine(i); BigInteger temp = i * i; squares.Add(temp); } for (int D = 2; D < 1001; D++) { if (squares.BinarySearch(D) >= 0) continue; BigInteger limit = (BigInteger)Math.Sqrt(D); int result = 0; BigInteger m = 0; BigInteger d = 1; BigInteger a = limit; BigInteger x1 = 1; BigInteger x = a; BigInteger y1 = 0; BigInteger y = 1; while (x * x - D * y * y != 1) { m = d * a - m; d = (D - m * m) / d; a = (limit + m) / d; BigInteger numm2 = x1; x1 = x; BigInteger denm2 = y1; y1 = y; x = a * x1 + numm2; y = a * y1 + denm2; } if (x > pmax) { pmax = x; result = D; Console.WriteLine("*************D={0} Y={1} x={2}", D, y, x); } } sw.Stop(); Console.WriteLine("Elapsed time {0} ms", sw.ElapsedMilliseconds); } }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is a referece type of string"); try { string[] strArray = { "apple", "banana", "chocolate", "dog", "food" }; List<string> listObject = new List<string>(strArray); int result = listObject.BinarySearch("egg"); if (result != -5) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,The result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int"); try { int[] iArray = { 1, 9, 3, 6, 5, 8, 7, 2, 4, 0 }; List<int> listObject = new List<int>(iArray); listObject.Sort(); int i = this.GetInt32(0, 10); int result = listObject.BinarySearch(i); if (result != i) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,The result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; }
public override List<Vertex> FindVertices(List<Vertex> vertices, Vector3 position, double maxDistanceToConsiderVertexAsSame) { List<Vertex> foundVertexes = new List<Vertex>(); Vertex testPos = new Vertex(position); int index = vertices.BinarySearch(testPos, this); if (index < 0) { index = ~index; } // we have the starting index now get all the vertices that are close enough starting from here double maxDistanceToConsiderVertexAsSameSquared = maxDistanceToConsiderVertexAsSame * maxDistanceToConsiderVertexAsSame; for (int i = index; i < vertices.Count; i++) { if (Math.Abs(vertices[i].Position.x - position.x) > maxDistanceToConsiderVertexAsSame) { // we are too far away in x, we are done with this direction break; } AddToListIfSameEnough(vertices, position, foundVertexes, maxDistanceToConsiderVertexAsSameSquared, i); } for (int i = index - 1; i >= 0; i--) { if (Math.Abs(vertices[i].Position.x - position.x) > maxDistanceToConsiderVertexAsSame) { // we are too far away in x, we are done with this direction break; } AddToListIfSameEnough(vertices, position, foundVertexes, maxDistanceToConsiderVertexAsSameSquared, i); } return foundVertexes; }
public static IList<Peak> FindAllPeaks(List<Peak> peakList, double minMz, double maxMz) { //var index = peakList.BinarySearch(new Peak(mz, 0.0), comparer); //return index < 0 ? null : peakList[index]; var index = peakList.BinarySearch(new Peak((minMz + maxMz) / 2, 0)); if (index < 0) index = ~index; var matchedPeakList = new List<Peak>(); // go down var i = index - 1; while (i >= 0 && i < peakList.Count) { if (peakList[i].Mz <= minMz) break; matchedPeakList.Add(peakList[i]); --i; } // go up i = index; while (i >= 0 && i < peakList.Count) { if (peakList[i].Mz >= maxMz) break; matchedPeakList.Add(peakList[i]); ++i; } matchedPeakList.Sort(); return matchedPeakList; }
static void Main() { List<int> list = new List<int>(); Console.WriteLine("Enter array elements: \nFor end enter 'n'"); while (true) { string number = Console.ReadLine(); int value; bool isNum = int.TryParse(number, out value); if (isNum) { list.Add(value); } else { break; } } Console.Write("Searchrd element is: "); int n = int.Parse(Console.ReadLine()); list.Sort(); int index = list.BinarySearch(n); Console.WriteLine("Index of searched element is: {0}", list[index]); }
public static int GetClosestMassIdx(List<float> argPeaks, float argMZ) { if (argPeaks.Count == 0) { return -1; } int KeyIdx = argPeaks.BinarySearch(argMZ); if (KeyIdx < 0) { KeyIdx = ~KeyIdx; } int ClosetIdx = 0; double ClosestValue = 10000.0; for (int i = KeyIdx - 2; i <= KeyIdx + 2; i++) { if (i >= 0 && i < argPeaks.Count) { if (Math.Abs(argPeaks[i] - argMZ) <= ClosestValue) { ClosestValue = Math.Abs(argPeaks[i] - argMZ); ClosetIdx = i; } } } return ClosetIdx; }
static void Main(string[] args) { List<string> nameList = new List<string>(); while (true) { Console.WriteLine("Enter a name."); string newName = Console.ReadLine(); if (newName == "") { break; } int result = nameList.BinarySearch(newName); if (result < 0) { int index = ~result; Console.WriteLine("Insert at index {0}.", index); nameList.Insert(index, newName); } else { int index = result; Console.WriteLine("Found at index {0}.", index); } for (int index = 0; index < nameList.Count(); ++index) { Console.WriteLine(index + ": " + nameList[index]); } Console.WriteLine(); } }
static void Main(string[] args) { List<int> firstArr = new List<int>(); int num = 1; int l1 = 0; Console.Write("Element {0} of the array(write some bad input to finish):", l1); l1++; while (int.TryParse(Console.ReadLine(), out num)) { Console.Write("Element {0} of the array(write some bad input to finish):", l1); firstArr.Add(num); l1++; } Console.Write("Element:"); int element = int.Parse(Console.ReadLine()); firstArr.TrimExcess(); firstArr.Sort(); Console.WriteLine(); Console.WriteLine(); DateTime start = DateTime.Now; int index = firstArr.BinarySearch(element); DateTime stop = DateTime.Now; Console.WriteLine("The index of the element found with Binary Search: {0}",index); Console.WriteLine("It took {0} milliseconds",stop-start); }
private static void addName(List<string> list, string name) { name = NavNode.CalcDisplayName(name); // int index = list.BinarySearch(name); if (index < 0) list.Insert(~index, name); }
static void Main() { List<int> array = new List<int>{5,3,2,8,4,1,3,6}; array = QuickSort(array); Console.WriteLine(String.Join(" ", array)); Console.WriteLine(array.BinarySearch(10)); }
static void Main(string[] args) { List<int> list = new List<int>() { 1, 2, 4, 5 }; Console.WriteLine(list.BinarySearch(3)); Program p = new Program(); Console.WriteLine(p.LengthOfLIS(new int[] { 10, 9, 2, 5, 3, 7, 101, 18 })); }
static void Main(string[] args) { string[] inputArr = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); int c = int.Parse(inputArr[0]); int n = int.Parse(inputArr[1]); string[] cArr = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); Dictionary<int, int> leftMostPositions = new Dictionary<int, int>(); List<int> leftMostPositionsArr = new List<int>(); for (int i = 0; i < cArr.Length; i++) { int current = int.Parse(cArr[i]); if (current != 0) { if (!leftMostPositions.ContainsKey(current)) { leftMostPositions.Add(current, i); leftMostPositionsArr.Add(int.Parse(cArr[i])); } else { leftMostPositions[current] = i; } } } int[] needles = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); List<int> resultArr = new List<int>(n); for (int i = 0; i < needles.Length; i++) { int index = leftMostPositionsArr.BinarySearch(needles[i]); if (index == 0) { resultArr.Add(0); } else if (index > 0 && index < leftMostPositionsArr.Count) { resultArr.Add(leftMostPositions[leftMostPositionsArr[index - 1]] + 1); } else { index = ~index; if (index == 0) { resultArr.Add(0); } else { resultArr.Add(leftMostPositions[leftMostPositionsArr[index - 1]] + 1); } } } Console.WriteLine(string.Join(" ", resultArr)); }
static void Main() { string input = "input.txt"; string blacklist = "blacklist.txt"; List<string> inputWords = new List<string>(); List<string> blacklistWords = new List<string>(); try { StreamReader reader = new StreamReader(input); using (reader) { inputWords = reader.ReadToEnd().Split( new char[] {'\r','\n', ' '}, StringSplitOptions.RemoveEmptyEntries).ToList(); } reader = new StreamReader(blacklist); using (reader) { blacklistWords = reader.ReadToEnd().Split( new char[] { '\r', '\n', ' '}, StringSplitOptions.RemoveEmptyEntries).ToList(); } blacklistWords.Sort(); for (int i = 0; i < inputWords.Count; i++) { if (blacklistWords.BinarySearch(inputWords[i]) >= 0) { inputWords.RemoveAt(i--); } } StreamWriter writer = new StreamWriter(input); using (writer) { foreach (var word in inputWords) { writer.WriteLine(word); } } } catch (FileNotFoundException) { Console.Error.WriteLine("That file is not there :("); } catch (UnauthorizedAccessException) { Console.Error.WriteLine("You don't have rights to open that file :("); } catch (IOException) { Console.Error.WriteLine("Someone is using that file and it can't be opened :("); } catch (Exception) { Console.Error.WriteLine("The file can't be read :("); } }
public static bool czyIstniejeBinary(List<byte[]> _list, byte[] _node) { if (_list.Count > 1) { int i = _list.BinarySearch(_node); } return false; }
public static bool CheckLoop(string Next, List<string> Closed) { if (Closed.BinarySearch(Next) < 0) { return false; } else { return true; } }
public static void CD(List<List<NHIRD_DataTypes.ActionBasedData_CD>> ActionBasedData_CD, string str_CDpath, int int_DataGroupCount) { Console.WriteLine("Call: GetActionBasedData.CD"); Console.WriteLine(" - CD path: {0}", str_CDpath); ActionBasedData_CD = new List<List<NHIRD_DataTypes.ActionBasedData_CD>>(); //讀取CD檔 int errorCount = 0; using (var sr = new StreamReader(str_CDpath)) { // -- 取得欄位index List<string> title = new List<string>(sr.ReadLine().Split('\t')); int int_FEE_YM_index = title.FindIndex(x => x.IndexOf("FEE_YM") >= 0); int int_HOSP_ID_index = title.FindIndex(x => x.IndexOf("HOSP_ID") >= 0); int int_APPL_DATE_index = title.FindIndex(x => x.IndexOf("APPL_DATE") >= 0); int int_SEQ_NO_index = title.FindIndex(x => x.IndexOf("SEQ_NO") >= 0); int int_ID_index = title.FindIndex(x => x == "ID"); int int_Birthday_index = title.FindIndex(x => x.IndexOf("ID_BIRTHDAY") >= 0); int int_FuncDate_index = title.FindIndex(x => x.IndexOf("FUNC_DATE") >= 0); int int_Gender_index = title.FindIndex(x => x.IndexOf("ID_SEX") >= 0); int int_ICD_index = title.FindIndex(x => x.IndexOf("ACODE_ICD9_1") >= 0); int int_FuncType_index = title.FindIndex(x => x.IndexOf("FUNC_TYPE") >= 0); // -- streamreader 迴圈 int datacount = 0; while (!sr.EndOfStream) { string[] SplitLine = sr.ReadLine().Split('\t'); NHIRD_DataTypes.ActionBasedData_CD DataToAdd = new NHIRD_DataTypes.ActionBasedData_CD(int_DataGroupCount); DataToAdd.str_Fee_YM = SplitLine[int_FEE_YM_index]; DataToAdd.str_HospID = SplitLine[int_HOSP_ID_index]; DataToAdd.str_ApplDate = SplitLine[int_APPL_DATE_index]; DataToAdd.str_SeqNO = SplitLine[int_SEQ_NO_index]; DataToAdd.str_ID = SplitLine[int_ID_index]; DataToAdd.str_Birthday = SplitLine[int_Birthday_index]; DataToAdd.str_FuncDate = SplitLine[int_FuncDate_index]; DataToAdd.str_Gender = SplitLine[int_Gender_index]; DataToAdd.array_ICD = new string[] { SplitLine[int_ICD_index], SplitLine[int_ICD_index + 1], SplitLine[int_ICD_index + 2] }; DataToAdd.str_FuncType = SplitLine[int_FuncType_index]; // 使用ActionBasedData_OrderComparer 依序存入ActionBasedData List int SearchIndex = ActionBasedData_CD.BinarySearch( DataToAdd, new NHIRD_DataTypes.ActionBasedData_OrderComparer()); if (SearchIndex < 0) { ActionBasedData_CD.Insert(-SearchIndex - 1, DataToAdd); datacount++; if (datacount % 10000 == 0) Console.WriteL("Data Readed: {0}\r", datacount); } else { errorCount++; } } } Console.WriteLine("\nRetrun: {0} Action based data was loaded, error count: {1}. \r\n", ActionBasedData_CD.Count(), errorCount); }
static void Main(string[] args) { Stopwatch sw = new Stopwatch(); int m = 0; int d = 1; int a = 0; int a0 = 0; int N = 13; int j = 0; int odds = 0; int steps = 0; sw.Start(); List<int> square = new List<int>(); for (int i = 2; i < Math.Sqrt(10000) + 1; i++) { square.Add(i * i); } for (N = 2; N <= 10000; N++) { if (square.BinarySearch(N) >= 0) continue; a0 = (int)Math.Sqrt(N); a = a0; j = 0; m = 0; d = 1; steps = 0; while (true) { steps++; j++; m = d * a - m; d = (N - m * m) / d; a = (a0 + m) / d; //Console.WriteLine("a {0} m {1} d {2} Number {3}", a, m, d, N); if (a == 2*a0) break; } //Console.WriteLine("-----------------------------"); if (steps % 2 != 0) odds++; //Console.WriteLine("Period of {1} = {0}", steps,N); } sw.Stop(); Console.WriteLine("Number of nums with odd periods {0}. Elapsed time {1} ms", odds,sw.ElapsedMilliseconds); }
static int GetIndexOfCommand(string command, ref List<Executable> list) { /* Results the index of the underlying Executable type in either of the executable list types */ int i = 0; if (list != null & command != "") { i = list.BinarySearch(new Executable("", command)); return i; } else throw new InvalidDataException("The argument passed is invalid"); }
static void Main(String[] args) { StringBuilder str = new StringBuilder(); int N = Convert.ToInt32(Console.ReadLine()); int[] size = new int[N]; List<double> data = new List<double>(); string[] commands = new string[N]; for(int i = 0; i < N ; i++){ string tmp = Console.ReadLine(); string[] parse = tmp.Split(new Char[] {' ', '\t', '\n'}); commands[i] = parse[0].Trim(); size[i] = Convert.ToInt32(parse[1].Trim()); bool rem = true; if(commands[i] == "r"){ int index = data.BinarySearch(size[i]); if(index >= 0){ data.RemoveAt(index); } else{ rem = false; } } else{ var index = data.BinarySearch(size[i]); if (index < 0){ index = ~index; } data.Insert(index, size[i]); } if(!rem || data.Count == 0){ str.AppendLine("Wrong!"); } else{ str.AppendLine(calcularModa(data).ToString()); } } Console.WriteLine(str.ToString()); }
static void Main(string[] args) { List<DateTime> aList = new List<DateTime>(); Action<DateTime> listAction; aList.Add(new DateTime(1968, 4, 5)); aList.AddRange(new DateTime[] { new DateTime(1965, 1, 19), new DateTime(1994, 12, 3), new DateTime(1966, 2, 1), new DateTime(1997, 7, 2)}); Console.WriteLine("Count: {0}", aList.Count); Console.WriteLine("Capacity: {0}", aList.Capacity); PrintValues(aList); // Get second item in list DateTime dt = aList[1]; // no need to cast, no unboxing (DateTime items stored as an array of value types) Console.WriteLine("aList[1] = {0}", dt.ToShortDateString()); // Trim capacity aList.TrimExcess(); // c.f. TrimToSize in non-generic list Console.WriteLine("Count: {0}", aList.Count); Console.WriteLine("Capacity: {0}", aList.Capacity); // Get first three items List<DateTime> firstThree = aList.GetRange(0, 3); PrintValues(firstThree); // Remove next two aList.RemoveRange(3, 2); // sort and binary search aList.Sort(); int index = aList.BinarySearch(new DateTime(1968, 4, 5)); Console.WriteLine("Index of item '4 April 1968' is {0}.", index); PrintValues(aList); // foreach using Action delegate Console.WriteLine("Listing using ForEach"); listAction = PrintDate; aList.ForEach(listAction); // find using a Predicate List<DateTime> sixtiesDates = aList.FindAll(IsSixties); Console.WriteLine("Sixties dates"); PrintValues(sixtiesDates); }
static bool IsSumOfTwoAbundant( int n, List<int> abundantNumbers) { int ii = 0; while (abundantNumbers[ii] < n) { // We know the abundantNumbers array is sorted, so binary search is ok. if (abundantNumbers.BinarySearch(n - abundantNumbers[ii]) > -1) { return true; } ii++; } return false; }
public void Plot(PlotModel plotModel, List<double> timestamps, List<double> memoryUsage) { LineSeries series = new LineSeries (); series.Color = color; int index = timestamps.BinarySearch (start); if (index < 0) index = ~index; if (index == timestamps.Count) throw new Exception ("Why do we have an interval that does not have memoryUsage data"); while (timestamps [index] < end) { series.Points.Add (new DataPoint (timestamps [index], memoryUsage [index])); index++; } plotModel.Series.Add (series); }
static void Main ( string[] args ) { List<int> array = new List<int>() { 2 , 4 , 1 , 6 , 10 }; Console.WriteLine(array.BinarySearch(10 , Comparer<int>.Default)); List<int> sortedArrayBS = array.BubbleSort<int>(Comparer<int>.Default).ToList(); List<int> sortedArraySS = array.SelectionSort<int>(Comparer<int>.Default).ToList(); List<int> sortedArrayMS = array.MergeSort<int>(Comparer<int>.Default).ToList(); List<int> sortedArrayQS = array.QuickSort<int>(Comparer<int>.Default).ToList(); Console.Write("Original array: " + array.Count + "\n "); foreach(var item in array) { Console.Write(item + " "); } Console.WriteLine(); Console.Write("Bubble Sort: "); foreach(var item in sortedArrayBS) { Console.Write(item + " "); } Console.WriteLine(); Console.Write("Selection Sort: "); foreach(var item in sortedArraySS) { Console.Write(item + " "); } Console.WriteLine(); Console.Write("Merge Sort: "); foreach(var item in sortedArrayMS) { Console.Write(item + " "); } Console.WriteLine(); Console.Write("Quick Sort: "); foreach(var item in sortedArrayQS) { Console.Write(item + " "); } Console.WriteLine(); Console.ReadKey(); }
public void SortingBaseline() { List<int> list = new List<int>(); for (int i = 0; i < kHeapTestSize; ++i) { int value = Random.Range(int.MinValue + 1, int.MaxValue); int pos = list.BinarySearch(value); list.Insert((pos < 0 ? ~pos : pos), value); } float greatest = int.MaxValue; while (list.Count > 0) { float next = list[list.Count - 1]; list.RemoveAt(list.Count - 1); Assert.IsTrue(next <= greatest); greatest = next; } }
static void Main(string[] args) { #region Dizi - List int[] sayilar = new int[3]; sayilar[0] = 5; sayilar[1] = 5; sayilar[2] = 5; foreach (var item in sayilar) { Console.WriteLine(item); } Console.WriteLine("***********************************"); List <int> numbers = new List <int>(sayilar); numbers.Add(4); numbers.Add(4); numbers.Add(4); numbers.Add(4); foreach (var item in numbers) { Console.WriteLine(item); } numbers.Remove(5); numbers.RemoveAt(5); numbers.BinarySearch(5);//hangi indexde Console.WriteLine("***********************************"); foreach (var item in numbers) { Console.WriteLine(item); } #endregion #region ListCollection List <Customer> customers = new List <Customer>() { new Customer { Id = 1, Kodu = 1 }, new Customer { Id = 2, Kodu = 2 } }; foreach (var item in customers) { Console.WriteLine("Id: " + item.Id + " ******** " + "Kodu: " + item.Kodu); } var customer = new Customer[] { new Customer { Id = 6, Kodu = 7 }, new Customer { Id = 8, Kodu = 9 } }; customers.AddRange(customer); Console.WriteLine("AddRanged List"); foreach (var item in customers) { Console.WriteLine("Id: " + item.Id + " ******** " + "Kodu: " + item.Kodu); } List <Customer> cst = customers.Where(a => a.Id == 1).ToList(); Console.WriteLine(cst.Capacity); #endregion Console.ReadLine(); }
public int BinarySearch(AkRoom room) { return(rooms.BinarySearch(room, s_compareByPriority)); }
private int SearchFor(EvaluatedMove evaluatedMove) { return(_evaluatedMoves.BinarySearch(evaluatedMove)); }
public int BinarySearch(Line item, IComparer <Line> comparer) { return(lines.BinarySearch(item, comparer)); }
public void Add(T item) { list.Insert(~list.BinarySearch(item), item); }
// deleteRule will drop the rule and matching set before creating the rule and set, use this is you don't care to update the rule and set in place private List <uint> UpdateRule(string ruleName, string action, IEnumerable <string> ipAddresses, List <uint> existingIPAddresses, string hashType, int maxCount, bool deleteRule, IEnumerable <PortRange> allowPorts, CancellationToken cancelToken, out bool result) { string ipFile = GetSetFileName(ruleName); string ipFileTemp = ipFile + ".tmp"; List <uint> newIPAddressesUint = new List <uint>(); uint value = 0; // add and remove the appropriate ip addresses from the set using (StreamWriter writer = File.CreateText(ipFileTemp)) { if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } writer.WriteLine($"create {ruleName} hash:{hashType} family {inetFamily} hashsize {hashSize} maxelem {maxCount} -exist"); foreach (string ipAddress in ipAddresses) { if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } // only allow ipv4 for now if (IPAddressRange.TryParse(ipAddress, out IPAddressRange range) && range.Begin.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && range.End.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && // if deleting the rule, don't track the uint value (!deleteRule || (value = IPBanFirewallUtility.ParseIPV4(ipAddress)) != 0)) { try { if (range.Begin.Equals(range.End)) { writer.WriteLine($"add {ruleName} {range.Begin} -exist"); } else { writer.WriteLine($"add {ruleName} {range.ToCidrString()} -exist"); } if (!deleteRule) { newIPAddressesUint.Add(value); } } catch { // ignore invalid cidr ranges } } } newIPAddressesUint.Sort(); // if the rule was deleted, no need to add del entries if (!deleteRule) { // for ip that dropped out, remove from firewall foreach (uint droppedIP in existingIPAddresses.Where(e => newIPAddressesUint.BinarySearch(e) < 0)) { writer.WriteLine($"del {ruleName} {IPBanFirewallUtility.IPV4ToString(droppedIP)} -exist"); } } } if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } else { // TODO: Is there an easier way to move to a file that exists? if (File.Exists(ipFile)) { DeleteFile(ipFile); } File.Move(ipFileTemp, ipFile); if (deleteRule) { DeleteRule(ruleName); } // restore the file to get the set updated result = (RunProcess("ipset", true, $"restore < \"{ipFile}\"") == 0); // ensure rule exists for the set CreateOrUpdateRule(ruleName, action, hashType, maxCount, allowPorts, cancelToken); } return(newIPAddressesUint); }
public int IndexOf(T item) { var index = list.BinarySearch(item); return(index < 0 ? -1 : index); }
/// <summary> /// Searches the entire sorted System.Collections.Generic.List<IFeature> for an element using the default comparer and returns the zero-based index of the element. /// </summary> /// <param name="item">The object to locate. The value can be null for reference types.</param> /// <returns>The zero-based index of item in the sorted System.Collections.Generic.List<IFeature>, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of System.Collections.Generic.List<IFeature>.Count.</returns> /// <exception cref="System.InvalidOperationException">The default comparer System.Collections.Generic.Comparer<IFeature>.Default cannot find an implementation of the System.IComparable<IFeature> generic interface or the System.IComparable interface for type IFeature.</exception> public virtual int BinarySearch(IFeature item) { return(_list.BinarySearch(item)); }
/// <inheritdoc cref="List{T}.BinarySearch(int, int, T, IComparer{T})" /> public int BinarySearch(int index, int count, T item, IComparer <T> comparer) { using (EnterReadLock.Enter(LockObject)) return(_lstData.BinarySearch(index, count, item, comparer)); }
public void Solve() { var xs = new List <int>(); var n = ri; var a = new int[n]; var b = new int[n]; var c = new int[n + 1]; for (int i = 0; i < n; i++) { a[i] = ri; b[i] = ri; if (a[i] < b[i]) { b[i] = a[i]; } xs.Add(a[i]); xs.Add(b[i]); } for (int i = 0; i < n + 1; i++) { c[i] = ri; xs.Add(c[i]); } Array.Sort(c); var q = ri; var u = new int[q]; var v = new int[q]; for (int i = 0; i < q; i++) { u[i] = ri; v[i] = ri; if (u[i] < v[i]) { v[i] = u[i]; } xs.Add(u[i]); xs.Add(v[i]); } xs = xs.Distinct().ToList(); xs.Sort(); for (int i = 0; i < n; i++) { a[i] = xs.BinarySearch(a[i]); b[i] = xs.BinarySearch(b[i]); } for (int i = 0; i < n + 1; i++) { c[i] = xs.BinarySearch(c[i]); } for (int i = 0; i < q; i++) { u[i] = xs.BinarySearch(u[i]); v[i] = xs.BinarySearch(v[i]); } Array.Sort(b, a); var ys = c.Distinct().ToList(); ys.Sort(); var k = ys.Count; var max = 0; var G = Enumerate(n + k + 1, x => new List <P>()); var D = Enumerate(n + k + 1, x => 100000000); var deq = new Deque <int>(); //greedy matching { var s = new Set <int>(); s.IsMultiSet = true; for (int i = 0; i < n + 1; i++) { s.Add(c[i]); } for (int i = 0; i < k - 1; i++) { G[n + i + 1].Add(new KeyValuePair <int, int>(n + i, 0)); } for (int i = n - 1; i >= 0; i--) { var p = s.LowerBound(a[i]); if (p < s.Count) { max++; //Debug.WriteLine("+1 {0} {1}", xs[a[i]], xs[s[p]]); var t = ys.BinarySearch(s[p]); var tt = ys.BinarySearch(b[i]); if (tt < 0) { tt = ~tt; } s.RemoveAt(p); G[i].Add(new P(n + t, 1)); G[n + tt].Add(new P(i, 0)); } else { p = s.LowerBound(b[i]); if (p == s.Count) { for (int j = 0; j < q; j++) { IO.Printer.Out.WriteLine(-1); } return; } //Debug.WriteLine("+-0 {0} {1}", xs[a[i]], xs[s[p]]); s.RemoveAt(p); } } //Debug.WriteLine(max); var pos = ys.BinarySearch(s[0]); D[n + pos] = 0; deq.PushBack(n + pos); } //augment { while (deq.Count > 0) { var p = deq.PopFront(); //Debug.WriteLine(p); foreach (var e in G[p]) { if (D[e.Key] > D[p] + e.Value) { D[e.Key] = D[p] + e.Value; if (e.Value == 0) { deq.PushFront(e.Key); } else { deq.PushBack(e.Key); } } } } } Debug.WriteLine(D.Skip(n).AsJoinedString()); for (int i = 0; i < q; i++) { var pb = ys.BinarySearch(v[i]); var pa = ys.BinarySearch(u[i]); if (pb < 0) { pb = ~pb; } if (pa < 0) { pa = ~pa; } var x = max - D[n + pb]; var y = max - D[n + pa] + 1; var z = Max(x, y); if (z < 0) { IO.Printer.Out.WriteLine(-1); } else { IO.Printer.Out.WriteLine(z); } } }
static void Main(string[] args) { List <int> arr = new List <int>(); arr.Add(2); arr.Add(3); arr.Add(5); arr.Add(7); //Список чисел 2 и нечётные до 1 000 000 с первичной обработкой; for (int i = 11; i < 1000000; i += 2) { if (i % 3 != 0 && i % 5 != 0 && i % 7 != 0) { arr.Add(i); } } //Поиск простых чисел от 2 до 1 000 000; Console.WriteLine("Выполняется обработка..."); int x = 0; for (int i = 0; i < arr.Count; i++) { x = arr[i]; for (int j = i + 1; j < arr.Count; j++) { if (arr[j] % x == 0) { arr.RemoveAt(j); j--; } } } //Поиск circular prime; int y = 0; for (int i = 0; i < arr.Count; i++) { y = arr[i]; if (y > 10 && y < 100) { int count = 2; int[] mas = new int[count]; mas[0] = y / 10; mas[1] = y % 10; y = mas[1] * 10 + mas[0]; if (arr.BinarySearch(y) < 0) { arr.RemoveAt(i); i--; } } else if (y > 100 && y < 1000) { int count = 3; int[] mas = new int[count]; for (int j = 1; j < count; j++) { mas[0] = y / 100; mas[1] = y % 100 / 10; mas[2] = y % 10; y = mas[2] * 100 + mas[0] * 10 + mas[1]; if (arr.BinarySearch(y) < 0) { arr.RemoveAt(i); i--; break; } } } else if (y > 1000 && y < 10000) { int count = 4; int[] mas = new int[count]; for (int j = 1; j < count; j++) { mas[0] = y / 1000; mas[1] = y % 1000 / 100; mas[2] = y % 100 / 10; mas[3] = y % 10; y = mas[3] * 1000 + mas[0] * 100 + mas[1] * 10 + mas[2]; if (arr.BinarySearch(y) < 0) { arr.RemoveAt(i); i--; break; } } } else if (y > 10000 && y < 100000) { int count = 5; int[] mas = new int[count]; for (int j = 1; j < count; j++) { mas[0] = y / 10000; mas[1] = y % 10000 / 1000; mas[2] = y % 1000 / 100; mas[3] = y % 100 / 10; mas[4] = y % 10; y = mas[4] * 10000 + mas[0] * 1000 + mas[1] * 100 + mas[2] * 10 + mas[3]; if (arr.BinarySearch(y) < 0) { arr.RemoveAt(i); i--; break; } } } else if (y > 100000 && y < 1000000) { int count = 6; int[] mas = new int[count]; for (int j = 1; j < count; j++) { mas[0] = y / 100000; mas[1] = y % 100000 / 10000; mas[2] = y % 10000 / 1000; mas[3] = y % 1000 / 100; mas[4] = y % 100 / 10; mas[5] = y % 10; y = mas[5] * 100000 + mas[0] * 10000 + mas[1] * 1000 + mas[2] * 100 + mas[3] * 10 + mas[4]; if (arr.BinarySearch(y) < 0) { arr.RemoveAt(i); i--; break; } } } } Console.WriteLine("Количество circular prime = " + arr.Count); //Вывод на экран circular prime; foreach (int z in arr) { Console.Write(z + " "); } Console.ReadLine(); }
private int KeyToIndex(object key) { return(keys.BinarySearch((TKey)key)); }
public int BinarySearch(T item) { lock (lockList) return(list.BinarySearch(item)); }
public NetworkTracerOutputCollection Trace(INetworkFeatureClass network, NetworkTracerInputCollection input, gView.Framework.system.ICancelTracker cancelTraker) { if (network == null || !CanTrace(input)) { return(null); } GraphTable gt = new GraphTable(network.GraphTableAdapter()); NetworkSourceInput source = input.Collect(NetworkTracerInputType.SourceNode)[0] as NetworkSourceInput; NetworkWeighInput weight = input.Contains(NetworkTracerInputType.Weight) ? input.Collect(NetworkTracerInputType.Weight)[0] as NetworkWeighInput : null; Dijkstra dijkstra = new Dijkstra(cancelTraker); dijkstra.reportProgress += this.ReportProgress; dijkstra.MaxDistance = _properties.Distance; if (weight != null) { dijkstra.GraphWeight = weight.Weight; dijkstra.WeightApplying = weight.WeightApplying; } dijkstra.ApplySwitchState = input.Contains(NetworkTracerInputType.IgnoreSwitches) == false && network.HasDisabledSwitches; Dijkstra.ApplyInputIds(dijkstra, input); dijkstra.Calculate(gt, source.NodeId); NetworkTracerOutputCollection output = new NetworkTracerOutputCollection(); #region Knoten/Kanten <= Distance Dijkstra.Nodes dijkstraNodes = dijkstra.DijkstraNodesWithMaxDistance(_properties.Distance); if (dijkstraNodes == null) { return(null); } List <int> edgeIds = new List <int>(); foreach (Dijkstra.Node dijkstraNode in dijkstraNodes) { if (dijkstraNode.EId < 0) { continue; } int index = edgeIds.BinarySearch(dijkstraNode.EId); if (index < 0) { edgeIds.Insert(~index, dijkstraNode.EId); } if (Math.Abs(dijkstraNode.Dist - _properties.Distance) < double.Epsilon) { // ToDo: Flag einfügen!! } } output.Add(new NetworkEdgeCollectionOutput(edgeIds)); #endregion #region Knoten/Kanten > Distance Dijkstra.Nodes cnodes = dijkstra.DijkstraNodesDistanceGreaterThan(_properties.Distance); foreach (Dijkstra.Node cnode in cnodes) { Dijkstra.Node node = dijkstra.DijkstraNodes.ById(cnode.Pre); if (node == null) { continue; } IGraphEdge graphEdge = gt.QueryEdge(cnode.EId); if (graphEdge == null) { continue; } RowIDFilter filter = new RowIDFilter(String.Empty); filter.IDs.Add(graphEdge.Eid); IFeatureCursor cursor = network.GetEdgeFeatures(filter); if (cursor == null) { continue; } IFeature feature = cursor.NextFeature; if (feature == null) { continue; } IPath path = null; if (cnode.Id != graphEdge.N2 && cnode.Id == graphEdge.N1) { ((Polyline)feature.Shape)[0].ChangeDirection(); } double trimDist = _properties.Distance - node.Dist; string label = _properties.Distance.ToString(); if (weight != null) { double w = gt.QueryEdgeWeight(weight.Weight.Guid, cnode.EId); switch (weight.WeightApplying) { case WeightApplying.Weight: trimDist *= w; break; case WeightApplying.ActualCosts: trimDist = ((IPolyline)feature.Shape)[0].Length * trimDist * w; // ??? Prüfen break; } label += "\n(" + Math.Round(node.GeoDist + trimDist, 2).ToString() + ")"; } path = ((IPolyline)feature.Shape)[0].Trim(trimDist); Polyline polyline = new Polyline(); polyline.AddPath(path); output.Add(new NetworkEdgePolylineOutput(cnode.EId, polyline)); output.Add(new NetworkFlagOutput( polyline[0][polyline[0].PointCount - 1], label)); } #endregion return(output); }
//////////////////////////////////////////////////////////////////// // Write object to PDF file //////////////////////////////////////////////////////////////////// internal override void WriteObjectToPdfFile() { // we have at least one contents object if (ContentsArray != null) { // page has one contents object if (ContentsArray.Count == 1) { Dictionary.AddFormat("/Contents", "[{0} 0 R]", ContentsArray[0].ObjectNumber); Dictionary.Add("/Resources", BuildResourcesDictionary(ContentsArray[0].ResObjects, true)); } // page is made of multiple contents else { // contents dictionary entry StringBuilder ContentsStr = new StringBuilder("["); // build contents dictionary entry foreach (PdfContents Contents in ContentsArray) { ContentsStr.AppendFormat("{0} 0 R ", Contents.ObjectNumber); } // add terminating bracket ContentsStr.Length--; ContentsStr.Append(']'); Dictionary.Add("/Contents", ContentsStr.ToString()); // resources array of all contents objects List <PdfObject> ResObjects = new List <PdfObject>(); // loop for all contents objects foreach (PdfContents Contents in ContentsArray) { // make sure we have resources if (Contents.ResObjects != null) { // loop for resources within this contents object foreach (PdfObject ResObject in Contents.ResObjects) { // check if we have it already int Ptr = ResObjects.BinarySearch(ResObject); if (Ptr < 0) { ResObjects.Insert(~Ptr, ResObject); } } } } // save to dictionary Dictionary.Add("/Resources", BuildResourcesDictionary(ResObjects, true)); } } // call PdfObject routine base.WriteObjectToPdfFile(); // exit return; }
private void HienThongTinLenEditValue(GridLookUpEdit grid, List <string> list, string ma) { int index = list.BinarySearch(ma); grid.EditValue = grid.Properties.GetKeyValue(index); }
/// <summary> /// Perform a binary search on the input list attempting to locate an object represented by /// inCompareParam. Return values are the same as List.BinarySearch(). /// </summary> public static bool SortedListContains <T>(List <T> inList, T inValue) { return(inList.BinarySearch(inValue) >= 0); }
/** Returns randomly selected points on the specified nodes with each point being separated by \a clearanceRadius from each other. * Selecting points ON the nodes only works for TriangleMeshNode (used by Recast Graph and Navmesh Graph) and GridNode (used by GridGraph). * For other node types, only the positions of the nodes will be used. * * clearanceRadius will be reduced if no valid points can be found. */ public static List <Vector3> GetPointsOnNodes(List <GraphNode> nodes, int count, float clearanceRadius = 0) { if (nodes == null) { throw new System.ArgumentNullException("nodes"); } if (nodes.Count == 0) { throw new System.ArgumentException("no nodes passed"); } System.Random rnd = new System.Random(); List <Vector3> pts = Pathfinding.Util.ListPool <Vector3> .Claim(count); // Square clearanceRadius *= clearanceRadius; if (nodes[0] is TriangleMeshNode || nodes[0] is GridNode) { //Assume all nodes are triangle nodes or grid nodes List <float> accs = Pathfinding.Util.ListPool <float> .Claim(nodes.Count); float tot = 0; for (int i = 0; i < nodes.Count; i++) { TriangleMeshNode tnode = nodes[i] as TriangleMeshNode; if (tnode != null) { float a = System.Math.Abs(Polygon.TriangleArea(tnode.GetVertex(0), tnode.GetVertex(1), tnode.GetVertex(2))); tot += a; accs.Add(tot); } else { GridNode gnode = nodes[i] as GridNode; if (gnode != null) { GridGraph gg = GridNode.GetGridGraph(gnode.GraphIndex); float a = gg.nodeSize * gg.nodeSize; tot += a; accs.Add(tot); } else { accs.Add(tot); } } } for (int i = 0; i < count; i++) { //Pick point int testCount = 0; int testLimit = 10; bool worked = false; while (!worked) { worked = true; //If no valid points can be found, progressively lower the clearance radius until such a point is found if (testCount >= testLimit) { clearanceRadius *= 0.8f; testLimit += 10; if (testLimit > 100) { clearanceRadius = 0; } } float tg = (float)rnd.NextDouble() * tot; int v = accs.BinarySearch(tg); if (v < 0) { v = ~v; } if (v >= nodes.Count) { // This shouldn't happen, due to NextDouble being smaller than 1... but I don't trust floating point arithmetic. worked = false; continue; } TriangleMeshNode node = nodes[v] as TriangleMeshNode; Vector3 p; if (node != null) { // Find a random point inside the triangle float v1; float v2; do { v1 = (float)rnd.NextDouble(); v2 = (float)rnd.NextDouble(); } while (v1 + v2 > 1); p = ((Vector3)(node.GetVertex(1) - node.GetVertex(0))) * v1 + ((Vector3)(node.GetVertex(2) - node.GetVertex(0))) * v2 + (Vector3)node.GetVertex(0); } else { GridNode gnode = nodes[v] as GridNode; if (gnode != null) { GridGraph gg = GridNode.GetGridGraph(gnode.GraphIndex); float v1 = (float)rnd.NextDouble(); float v2 = (float)rnd.NextDouble(); p = (Vector3)gnode.position + new Vector3(v1 - 0.5f, 0, v2 - 0.5f) * gg.nodeSize; } else { //Point nodes have no area, so we break directly instead pts.Add((Vector3)nodes[v].position); break; } } // Test if it is some distance away from the other points if (clearanceRadius > 0) { for (int j = 0; j < pts.Count; j++) { if ((pts[j] - p).sqrMagnitude < clearanceRadius) { worked = false; break; } } } if (worked) { pts.Add(p); break; } else { testCount++; } } } Pathfinding.Util.ListPool <float> .Release(accs); } else { for (int i = 0; i < count; i++) { pts.Add((Vector3)nodes[rnd.Next(nodes.Count)].position); } } return(pts); }
string VarDrawingString() { string result = ""; List <double> lengts = new List <double>(); List <uint> counts = new List <uint>(); //рассовываем длины в стопочки for (int i = 0; i < length_data.GetLength(0); i++) { double l = Math.Round(length_data[i] / 10) * 10; int index = lengts.BinarySearch(l); if (index >= 0) { counts[index]++; } else { counts.Add(1); lengts.Add(l); } } bool all_ones = true; //определяем, всех ли по одному for (int i = 0; i < counts.Count; i++) { if (counts[i] != 1) { all_ones = false; break; } } if (all_ones) { //случай когда всех длин по одной for (int i = 0; i < lengts.Count; i++) { result += string.Format("{0:0}", lengts[i]); if (i != lengts.Count - 1) { result += ";"; } else { result += " "; } } result += "по 1шт"; return(result); } for (int i = 0; i < counts.Count; i++) { result += string.Format("{0:0}", lengts[i]) + " " + counts[i] + "шт"; //ставим разделители if (i == counts.Count - 1) { result += "."; } else { result += "; "; } } return(result); }
public int BinarySearch(int index, int count, T item, IComparer <T> comparer) { return(list.BinarySearch(index, count, item, comparer)); }
Tuple <List <KeyValuePair <int, int> >, List <KeyValuePair <int, double> >, List <int> > MatchesFromIndex(List <int> ids, IndexGeneric index, IndexGeneric ids_index, LinqDbTypes type) { List <KeyValuePair <int, int> > res_int = null; List <KeyValuePair <int, double> > res_double = null; int max = Int32.MinValue; bool is_sorted = true; int curr = Int32.MinValue; for (int i = 0; i < ids.Count(); i++) { if (max < ids[i]) { max = ids[i]; } if (is_sorted && curr > ids[i]) { is_sorted = false; } curr = ids[i]; } int max_size = 300000000; if (max < max_size) { List <bool> check_list = new List <bool>(max + 1); for (int i = 0; i < max + 1; i++) { check_list.Add(false); } foreach (var id in ids) { check_list[id] = true; } if (type == LinqDbTypes.int_) { res_int = new List <KeyValuePair <int, int> >(ids.Count()); for (int i = 0; i < index.Parts.Count(); i++) { var val_part = index.Parts[i]; var iids = ids_index.Parts[i].IntValues; int icount = iids.Count(); for (int j = 0; j < icount; j++) { var id = iids[j]; if (id <= max && check_list[id]) { res_int.Add(new KeyValuePair <int, int>(id, val_part.IntValues[j])); } } } } else { res_double = new List <KeyValuePair <int, double> >(ids.Count()); for (int i = 0; i < index.Parts.Count(); i++) { var val_part = index.Parts[i]; var iids = ids_index.Parts[i].IntValues; int icount = iids.Count(); for (int j = 0; j < icount; j++) { var id = iids[j]; if (id <= max && check_list[id]) { res_double.Add(new KeyValuePair <int, double>(id, val_part.DoubleValues[j])); } } } } return(new Tuple <List <KeyValuePair <int, int> >, List <KeyValuePair <int, double> >, List <int> >(res_int, res_double, null)); } else { int bloom_size = 30000000; List <bool> bloom_filter = new List <bool>(bloom_size); for (int i = 0; i < bloom_size; i++) { bloom_filter.Add(false); } foreach (var id in ids) { bloom_filter[id % bloom_size] = true; } if (!is_sorted) { ids = ids.OrderBy(f => f).ToList(); } if (type == LinqDbTypes.int_) { res_int = new List <KeyValuePair <int, int> >(ids.Count()); for (int i = 0; i < ids_index.Parts.Count(); i++) { var val_part = index.Parts[i]; var iids = ids_index.Parts[i].IntValues; int icount = iids.Count(); for (int j = 0; j < icount; j++) { var id = iids[j]; if (bloom_filter[id % bloom_size] && ids.BinarySearch(id) >= 0) { res_int.Add(new KeyValuePair <int, int>(id, val_part.IntValues[j])); } } } } else { res_double = new List <KeyValuePair <int, double> >(ids.Count()); for (int i = 0; i < ids_index.Parts.Count(); i++) { var val_part = index.Parts[i]; var iids = ids_index.Parts[i].IntValues; int icount = iids.Count(); for (int j = 0; j < icount; j++) { var id = iids[j]; if (bloom_filter[id % bloom_size] && ids.BinarySearch(id) >= 0) { res_double.Add(new KeyValuePair <int, double>(id, val_part.DoubleValues[j])); } } } } return(new Tuple <List <KeyValuePair <int, int> >, List <KeyValuePair <int, double> >, List <int> >(res_int, res_double, ids)); } }
public static bool SortedListContains <T>(List <T> inList, T inValue, IComparer <T> comparer) { return(inList.BinarySearch(inValue, comparer) >= 0); }
public void BinarySearchTest(int searchFor) { IList <int> iList = _list; iList.BinarySearch(searchFor, (a, b) => a.CompareTo(b)).Should().Be(_list.BinarySearch(searchFor)); }
public int GetExactIndex(Keyframe value) { return(_keyframes.BinarySearch(value)); }
private static void GetStreamingAssetsInfoFromJar(string apkPath, List <string> paths, List <PartInfo> parts) { using (var stream = File.OpenRead(apkPath)) using (var reader = new BinaryReader(stream)) { if (!stream.CanRead) { throw new ArgumentException(); } if (!stream.CanSeek) { throw new ArgumentException(); } long expectedNumberOfEntries; long centralDirectoryStart; ZipArchiveUtils.ReadEndOfCentralDirectory(stream, reader, out expectedNumberOfEntries, out centralDirectoryStart); try { stream.Seek(centralDirectoryStart, SeekOrigin.Begin); long numberOfEntries = 0; ZipCentralDirectoryFileHeader header; const int prefixLength = 7; const string prefix = "assets/"; const string assetsPrefix = "assets/bin/"; Debug.Assert(prefixLength == prefix.Length); while (ZipCentralDirectoryFileHeader.TryReadBlock(reader, out header)) { if (header.CompressedSize != header.UncompressedSize) { #if UNITY_ASSERTIONS var fileName = Encoding.UTF8.GetString(header.Filename); if (fileName.StartsWith(prefix) && !fileName.StartsWith(assetsPrefix)) { Debug.LogAssertionFormat("BetterStreamingAssets: file {0} seems to be a Streaming Asset, but is compressed. If this is a App Bundle build, see README for a possible workaround.", fileName); } #endif // we only want uncompressed files } else { var fileName = Encoding.UTF8.GetString(header.Filename); if (fileName.EndsWith("/")) { // there's some strangeness when it comes to OBB: directories are listed as files // simply ignoring them should be enough Debug.Assert(header.UncompressedSize == 0); } else if (fileName.StartsWith(prefix)) { // ignore normal assets... if (fileName.StartsWith(assetsPrefix)) { // Note: if you put bin directory in your StreamingAssets you will get false negative here } else { var relativePath = fileName.Substring(prefixLength - 1); var entry = new PartInfo() { crc32 = header.Crc32, offset = header.RelativeOffsetOfLocalHeader, // this offset will need fixing later on size = header.UncompressedSize }; var index = paths.BinarySearch(relativePath, StringComparer.OrdinalIgnoreCase); if (index >= 0) { throw new System.InvalidOperationException("Paths duplicate! " + fileName); } paths.Insert(~index, relativePath); parts.Insert(~index, entry); } } } numberOfEntries++; } if (numberOfEntries != expectedNumberOfEntries) { throw new ZipArchiveException("Number of entries does not match"); } } catch (EndOfStreamException ex) { throw new ZipArchiveException("CentralDirectoryInvalid", ex); } // now fix offsets for (int i = 0; i < parts.Count; ++i) { var entry = parts[i]; stream.Seek(entry.offset, SeekOrigin.Begin); if (!ZipLocalFileHeader.TrySkipBlock(reader)) { throw new ZipArchiveException("Local file header corrupt"); } entry.offset = stream.Position; parts[i] = entry; } } }
static void Main() { string tmpString; List <int> ListInt = new List <int>(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); int maxCount = 3; ListInt.RemoveRange(maxCount, ListInt.Count - maxCount); ListInt = new List <int>(new[] { 0 }); List <int> ListIntToAdd = new List <int>(new[] { 2, 3, 4, 5, 6, 7, 8, 9 }); if (ListInt.Count + ListIntToAdd.Count > maxCount) { int itemToRemove; if ((itemToRemove = maxCount - ListInt.Count) > 0) { ListIntToAdd.RemoveRange(itemToRemove, ListIntToAdd.Count - itemToRemove); } } ListInt = new List <int>(); ListInt.Add(5); ListInt.Add(3); ListInt.Add(1); if (ListInt.Contains(1)) { Console.WriteLine("ListInt.Contains(1)"); } int a = 1, idx; if ((idx = ListInt.BinarySearch(a)) >= 0) { tmpString = "\"" + a + "\" was found @ ListInt[" + idx + "]=\"" + ListInt[idx] + "\""; } else { if ((idx = ~idx) >= ListInt.Count) { --idx; } tmpString = "\"" + a + "\" was not found. The next larger object is at index " + idx + " (ListInt[" + idx + "]=\"" + ListInt[idx] + "\")"; } Console.WriteLine(tmpString); ListInt.Sort(); if ((idx = ListInt.BinarySearch(a)) >= 0) { tmpString = "\"" + a + "\" was found @ ListInt[" + idx + "]=\"" + ListInt[idx] + "\""; } else { if ((idx = ~idx) >= ListInt.Count) { --idx; } tmpString = "\"" + a + "\" was not found. The next larger object is at index " + idx + " (ListInt[" + idx + "]=\"" + ListInt[idx] + "\")"; } Console.WriteLine(tmpString); a = 4; if ((idx = ListInt.BinarySearch(a)) >= 0) { tmpString = "\"" + a + "\" was found @ ListInt[" + idx + "]=\"" + ListInt[idx] + "\""; } else { if ((idx = ~idx) >= ListInt.Count) { --idx; } tmpString = "\"" + a + "\" was not found. The next larger object is at index " + idx + " (ListInt[" + idx + "]=\"" + ListInt[idx] + "\")"; } Console.WriteLine(tmpString); Point <int> Point = new Point <int>(10, 20); Console.WriteLine(Point.ToString()); Point.ResetPoint(); Console.WriteLine(Point.ToString()); List <string> ListString = new List <string>(); ListString.Add("First"); ListString.Add("Second"); ListString.Add("Third"); ListString.Add("Fourth"); ListString.Add("Fifth"); for (int i = 0; i < ListString.Count; ++i) { Console.WriteLine("ListString[{0}]=\"{1}\"", i, ListString[i]); } foreach (string s in ListString) { Console.WriteLine(s); } List <string> .Enumerator e = ListString.GetEnumerator(); while (e.MoveNext()) { Console.WriteLine(e.Current); } }
public static int BinarySearch <T>(this List <T> list, T item, Func <T, T, int> compare) { return(list.BinarySearch(item, new ComparisonComparer <T>(compare))); }
internal int BinarySearch(long pos) { return(List.BinarySearch(pos)); }
/// <summary> /// Partitions the items consumed by the batchable object into buckets, where each bucket contains a set of items that /// have the same value set on all item metadata consumed by the object. /// </summary> /// <remarks> /// PERF NOTE: Given n items and m batching metadata that produce l buckets, it is usually the case that n > l > m, /// because a batchable object typically uses one or two item metadata to control batching, and only has a handful of /// buckets. The number of buckets is typically only large if a batchable object is using single-item batching /// (where l == n). Any algorithm devised for bucketing therefore, should try to minimize n and l in its complexity /// equation. The algorithm below has a complexity of O(n*lg(l)*m/2) in its comparisons, and is effectively O(n) when /// l is small, and O(n*lg(n)) in the worst case as l -> n. However, note that the comparison complexity is not the /// same as the operational complexity for this algorithm. The operational complexity of this algorithm is actually /// O(n*m + n*lg(l)*m/2 + n*l/2 + n + l), which is effectively O(n^2) in the worst case. The additional complexity comes /// from the array and metadata operations that are performed. However, those operations are extremely cheap compared /// to the comparison operations, which dominate the time spent in this method. /// </remarks> /// <returns>ArrayList containing ItemBucket objects (can be empty), each one representing an execution batch.</returns> private static List <ItemBucket> BucketConsumedItems ( Lookup lookup, Dictionary <string, ICollection <ProjectItemInstance> > itemListsToBeBatched, Dictionary <string, MetadataReference> consumedMetadataReferences, ElementLocation elementLocation ) { ErrorUtilities.VerifyThrow(itemListsToBeBatched.Count > 0, "Need item types consumed by the batchable object."); ErrorUtilities.VerifyThrow(consumedMetadataReferences.Count > 0, "Need item metadata consumed by the batchable object."); List <ItemBucket> buckets = new List <ItemBucket>(); // Get and iterate through the list of item names that we're supposed to batch on. foreach (KeyValuePair <string, ICollection <ProjectItemInstance> > entry in itemListsToBeBatched) { string itemName = (string)entry.Key; // Use the previously-fetched items, if possible ICollection <ProjectItemInstance> items = entry.Value; if (items == null) { items = lookup.GetItems(itemName); } if (items != null) { foreach (ProjectItemInstance item in items) { // Get this item's values for all the metadata consumed by the batchable object. Dictionary <string, string> itemMetadataValues = GetItemMetadataValues(item, consumedMetadataReferences, elementLocation); // put the metadata into a dummy bucket we can use for searching ItemBucket dummyBucket = ItemBucket.GetDummyBucketForComparisons(itemMetadataValues); // look through all previously created buckets to find a bucket whose items have the same values as // this item for all metadata consumed by the batchable object int matchingBucketIndex = buckets.BinarySearch(dummyBucket); ItemBucket matchingBucket = (matchingBucketIndex >= 0) ? (ItemBucket)buckets[matchingBucketIndex] : null; // If we didn't find a bucket that matches this item, create a new one, adding // this item to the bucket. if (null == matchingBucket) { matchingBucket = new ItemBucket(itemListsToBeBatched.Keys, itemMetadataValues, lookup, buckets.Count); // make sure to put the new bucket into the appropriate location // in the sorted list as indicated by the binary search // NOTE: observe the ~ operator (bitwise complement) in front of // the index -- see MSDN for more information on the return value // from the ArrayList.BinarySearch() method buckets.Insert(~matchingBucketIndex, matchingBucket); } // We already have a bucket for this type of item, so add this item to // the bucket. matchingBucket.AddItem(item); } } } // Put the buckets back in the order in which they were discovered, so that the first // item declared in the project file ends up in the first batch passed into the target/task. List <ItemBucket> orderedBuckets = new List <ItemBucket>(buckets.Count); for (int i = 0; i < buckets.Count; ++i) { orderedBuckets.Add(null); } foreach (ItemBucket bucket in buckets) { orderedBuckets[bucket.BucketSequenceNumber] = bucket; } return(orderedBuckets); }
protected override void Update() { base.Update(); float drawHeight = DrawHeight; // Remove all panels that should no longer be on-screen scrollableContent.RemoveAll(delegate(Panel p) { float panelPosY = p.Position.Y; bool remove = panelPosY <Current - p.DrawHeight || panelPosY> Current + drawHeight || !p.IsPresent; return(remove); }); // Find index range of all panels that should be on-screen Trace.Assert(panels.Count == yPositions.Count); int firstIndex = yPositions.BinarySearch(Current - Panel.MAX_HEIGHT); if (firstIndex < 0) { firstIndex = ~firstIndex; } int lastIndex = yPositions.BinarySearch(Current + drawHeight); if (lastIndex < 0) { lastIndex = ~lastIndex; // Add the first panel of the last visible beatmap group to preload its data. if (lastIndex != 0 && panels[lastIndex - 1] is BeatmapSetHeader) { lastIndex++; } } // Add those panels within the previously found index range that should be displayed. for (int i = firstIndex; i < lastIndex; ++i) { Panel panel = panels[i]; if (panel.State == PanelSelectedState.Hidden) { continue; } // Only add if we're not already part of the content. if (!scrollableContent.Contains(panel)) { // Makes sure headers are always _below_ panels, // and depth flows downward. panel.Depth = i + (panel is BeatmapSetHeader ? panels.Count : 0); scrollableContent.Add(panel); } } // Update externally controlled state of currently visible panels // (e.g. x-offset and opacity). float halfHeight = drawHeight / 2; foreach (Panel p in scrollableContent.Children) { updatePanel(p, halfHeight); } }