/// <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;
        }
Example #2
0
    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);
        }
    }
 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();
 }
Example #4
0
        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();
        }
Example #5
0
        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 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;
        }
Example #7
0
 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));
 }
Example #8
0
        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;
        }
Example #9
0
        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();
            }
        }
Example #10
0
		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;
		}
Example #11
0
    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;
    }
Example #12
0
    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]);
    }
Example #13
0
    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;
    }
        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);
        }
Example #15
0
        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;
        }
Example #16
0
 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);
 }
Example #17
0
        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 }));
        }
Example #18
0
    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 :(");
        }
    }
        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));
        }
Example #20
0
        public static bool czyIstniejeBinary(List<byte[]> _list, byte[] _node)
        {
            if (_list.Count > 1)
            {
                int i = _list.BinarySearch(_node);
            }

            return false;
        }
Example #21
0
 public static bool CheckLoop(string Next, List<string> Closed)
 {
     if (Closed.BinarySearch(Next) < 0)
     {
         return false;
     }
     else
     {
         return true;
     }
 }
Example #22
0
        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);
        }
Example #23
0
        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);
        }
Example #27
0
        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;
        }
Example #28
0
    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();
        }
Example #30
0
	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;
		}
	}