Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var arr = new[]
- {
- new{ Name= "pesho", Age = 15},
- new{ Name= "agosho", Age = 17},
- new{ Name= "esho", Age = 16},
- };
- Array.Sort(arr, (a, b) => a.Age.CompareTo(b.Age));
- string[] kom = Array.ConvertAll(arr, a=> a.Name);
- foreach (var item in arr)
- {
- Console.WriteLine(item);
- }
- foreach (var item in kom)
- {
- Console.WriteLine(item);
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //string input = Console.ReadLine();
- string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- int[] nums = new int[STRnumbers.Length];
- nums = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
- //for (int i = 0; i < nums.Length; i++)
- //{
- // nums[i] = int.Parse(Console.ReadLine());
- //}
- Array.Sort(nums);
- Console.WriteLine();
- for (int i = 0; i < nums.Length; i++)
- {
- Console.WriteLine(nums[i]);
- }
- Console.WriteLine();
- Console.WriteLine(nums.Sum());
- Console.WriteLine();
- Console.WriteLine(nums.Skip(3).First());// propusni purvite 3 i mi vzemi sledvashtoto koeto sledva
- Console.WriteLine();
- /////////////////////
- foreach (var i in nums.Skip(3).Take(2).Reverse())// vzemi mi 4 ot masiva i mi vzemi sledvashtite 2 i mi gi reversni
- {
- Console.Write(i + " ");
- }
- /////////////////////////////////////////////////////
- string[] names = { "Peter", "Maria", "Katya", "Todor", "A9ll" , "Zoro","4543" };
- foreach (var name in names)
- {
- Console.WriteLine(name);
- }
- Console.WriteLine();
- Array.Sort(names);
- foreach (var name in names)
- {
- Console.WriteLine(name);
- }
- ////
- Console.WriteLine();
- names[0] = names[0] + " (junior)";
- Array.Reverse(names);
- foreach (var name in names)
- {
- Console.WriteLine(name);
- }
- ////////////////////////////////////////////////////////
- reverse array ////////////
- int[] array = new int[] { 1, 2, 3, 4, 5 };
- // Get array size
- // int length = array.Length;
- // Declare and create the reversed array
- int[] reversed = new int[array.Length];
- for (int index = 0; index < array.Length; index++)
- {
- Console.WriteLine(array[index]);
- }
- // Initialize the reversed array
- for (int index = 0; index < array.Length; index++) //////// za da di printi 54321
- {
- reversed[array.Length - index - 1] = array[index];
- }
- //for (int index = 0; index < array.Length - 1; index++) //////// za da di printi 43210
- //{
- // reversed[array.Length - index - 2] = array[index];
- //}
- Console.WriteLine();
- // Print the reversed array elements
- for (int index = 0; index < reversed.Length; index++)
- {
- Console.WriteLine(reversed[index]);
- }
- //// simetrichen array ////////
- // primer 1 2 3 2 1
- // Declaring the array
- //string input = Console.ReadLine();
- string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- int[] nums = new int[STRnumbers.Length];
- nums = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
- // Declaring the array
- bool isSymmetric = true;
- for (int i = 0; i < nums.Length / 2; i++)// na purvoto zavurtane na cikula size = 5 i za tova 5 - 0 - 1 = 4 index koito mi e 1 v slu4aq
- { // pri vtoroto zavurtane mi vzima 1 i 3 element i taka natatuk
- if (nums[i] != nums[nums.Length - i - 1])
- {
- isSymmetric = false;
- break;
- }
- }
- Console.WriteLine("Symmetric? --> {0}", isSymmetric);
- //////////////////////////////////////////////////////////////
- //// natrupvane ot edin masiv v drug masiv
- int[] arr = { 1, 2, 3, 4, 5, 6 };
- int[] arr2 = new int[arr.Length];
- for (int i = 0; i < arr.Length; i++)
- {
- arr2[i] = arr[i] * arr[i];
- }
- //////////////////
- for (int i = 0; i < arr2.Length; i++)
- {
- Console.Write("arr2 = {0} ", arr2[i]);
- }
- //////// reversvane na masiv 2 variant
- Console.WriteLine();
- for (int i = arr.Length - 1; i > -1; i--)
- {
- Console.Write("arr = {0} ", arr[i]);
- }
- Console.WriteLine();
- for (int i = arr.Length - 1; i > -1; i--)
- {
- Console.Write("arr2 = {0} ", arr2[i]);
- }
- Console.WriteLine();
- ////////////////////////// umnojavane ///////////////////////////////////////////
- int[] arr = { 1, 2, 3, 4, 5, 6 };
- int[] arr2 = new int[arr.Length /2];
- bool ishui = false;
- for (int i = 0 , j =0; i < arr.Length-1; i +=2 , j++)
- {
- if (ishui == true) // nachin da ne se pravi neshto pri purvata iteracia na cikula
- {
- arr2[j] = arr2[j] + 1;
- }
- arr2[j] = arr[i] + arr[i + 1];
- ishui = true;
- }
- //////////////////
- Console.WriteLine();
- for (int i = 0; i < arr.Length; i ++)
- {
- if (i == 3) /////// za propuskane iteracia v cikul
- {
- continue;
- }
- Console.Write("arr2 = {0} ", arr[i]);
- }
- Console.WriteLine();
- //////// reversvane na masiv 2 variant
- Console.WriteLine();
- for (int i = arr.Length - 1; i > -1; i--)
- {
- Console.Write("arr = {0} ", arr[i]);
- }
- Console.WriteLine();
- for (int i = arr2.Length - 1; i > -1; i--)
- {
- Console.Write("arr2 = {0} ", arr2[i]);
- }
- Console.WriteLine();
- ////////////////////////////////////
- ////////////////////////// array homework /////////////////////////////////////
- 1 zadacha
- /Write a program that allocates array of 20 integers and initializes each element by its index multiplied by 5. Print the obtained array on the console.
- int[] nums = new int[20];
- for (int i = 0; i < nums.Length; i++)
- {
- nums[i] = i * 5;
- }
- for (int i = 0; i < nums.Length; i++)
- {
- Console.Write(i != nums.Length - 1 ? nums[i] + ", " : nums[i] + "\n");
- }
- //ОПИСАНИЕ: Инициализираме масив от 20 елемента. С for цикъл обхождаме елементите му всеки един от които го умножаваме по 5.
- //След това с втория for цикъл принтираме резултата на конзолата.
- Problem 2. Compare arrays///////////////////////////////////////////////////////////////////////////////////
- //Write a program that reads two arrays from the console and compares them element by element
- Console.WriteLine("Pleas enter the lenght of the FIRST Array:");
- //string input = Console.ReadLine();
- string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- int[] firstArr = new int[STRnumbers.Length];
- firstArr = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
- Console.WriteLine("Pleas enter the lenght of the SECOND Array:");
- //string input1 = Console.ReadLine();
- string[] STRnumbers1 = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- int[] secondArr = new int[STRnumbers1.Length];
- secondArr = Array.ConvertAll<string, int>(STRnumbers1, int.Parse);
- if (firstArr.Length != secondArr.Length)
- {
- Console.WriteLine("Error! The FIRST Array lenght and the SECOND Array lenght are not equal. Please try again and enter EQUAL array lenghts");
- }
- else
- {
- bool areEqual = true;
- for (int i = 0; i < secondArr.Length; i++)
- {
- if (firstArr[i] != secondArr[i])
- {
- areEqual = false;
- Console.WriteLine("The two arrays are NOT the same: {0}", areEqual);
- break;
- }
- }
- if (areEqual == true)
- {
- Console.WriteLine("The two arrays are the same: {0}", areEqual);
- }
- }
- }
- }
- //ОБЯСНЕНИЕ: Първото нещо, което правим е да инициализираме самия размер на двата масива.
- //Макар и незадължително по условие, с помоща на if условието проверяваме дали броя на елементите в двата масива са равни.
- //Това може и да не го правим, ако просто накараме потребителя веднъж да въведе число за размера на масивите (веднъж като го въведе ще го ползваме същата променлива при инициализацията и на втория масив).
- //След това с помощта на for цикли въвеждаме самите стойности из одтелните позиции на двата масива.
- //Преминаваме към същинската част на задачата - сравняване на самите отделни стойности в масива една по една. Използваме булева променлива, в която изначално казваме че елементите в двата масива са равни, до доказване на противното.
- //С помощта на for цикъл започваме да сравняваме отделните елементи на масивите един по един.
- //В случай че два елемента от една и съща позиция в масивите се случи да не са равни се изпълнява if условието, променливата, която съзадохе по-горе вече става false и се прехвърляме към break оператъра, тъй като при това положение няма смисъл да продължаваме да сравняваме останалите елементи из масивите.
- //Отпечатваме резолтата на конзолата.
- Problem 3. Compare char arrays ////////////////////////////////////////////////////////////////////////////
- //Write a program that reads two arrays from the console and compares them element by element
- Console.WriteLine("Pleas enter the lenght of the FIRST Array:");
- //string input = Console.ReadLine();
- string STRnumbers = Console.ReadLine();
- char[] firstArr = STRnumbers.ToCharArray();
- //firstArr = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
- Console.WriteLine("Pleas enter the lenght of the SECOND Array:");
- //string input1 = Console.ReadLine();
- string STRnumbers1 = Console.ReadLine();
- char[] secondArr = STRnumbers1.ToCharArray();
- //secondArr = Array.ConvertAll<string, int>(STRnumbers1, int.Parse);
- if (firstArr.Length != secondArr.Length)
- {
- Console.WriteLine("Error! The FIRST Array lenght and the SECOND Array lenght are not equal. Please try again and enter EQUAL array lenghts");
- }
- bool areEqual = true;
- for (int i = 0; i < secondArr.Length; i++)
- {
- if (firstArr[i] != secondArr[i])
- {
- areEqual = false;
- break;
- }
- }
- Console.WriteLine("The two arrays are equal: {0}", areEqual);
- // sushtoto kato to 2 zadacha samo che smenqme s charove firstArr[i] = char.Parse(Console.ReadLine());
- //ОБЯСНЕНИЕ: решението е почти същото като на задача 2 от Масиви.
- //Разликата е че зададох char-овете предварително в самия код, защото не се сетих как може да се направи, така че потребителя сам самичък да си ги въведене...
- Problem 4. Maximal sequence/////////////////////////////////////////////////////////////////
- //Write a program that finds the maximal sequence of equal elements in an array.
- class Program
- {
- static int bestLength = 0;
- static int bestElement = 0;
- static void Main()
- {
- Console.WriteLine("Enter a lenght of the array:");
- string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- int[] firstArr = new int[STRnumbers.Length];
- firstArr = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
- FindBestSequence(firstArr);
- Console.Write("The array contains following elements: " + "{" + string.Join(", ", firstArr) + "}\n");
- Console.Write("The maximal sequence of equal elements in the array is: {");
- for (int i = 0; i < bestLength; i++)
- {
- Console.Write(i != bestLength - 1 ? bestElement + ", " : bestElement + "}\n");
- }
- }
- private static void FindBestSequence(int[] nums)
- {
- int currLength = 1;
- int currElement = nums[0];
- if (nums.Length == 1)
- {
- bestElement = currElement;
- bestLength = 1;
- return;
- }
- for (int i = 1; i < nums.Length; i++)
- {
- if (nums[i] == currElement)
- {
- currLength++;
- }
- else
- {
- currElement = nums[i];
- currLength = 1;
- }
- if (currLength >= bestLength)
- {
- bestLength = currLength;
- bestElement = currElement;
- }
- }
- }
- //ОБЯСНЕНИЕ: Заделяме масив и го инициализираме. Създаваме три нови променливи: counter, longestSequence и value.
- //В първата ще записваме текущото проверявано повторение от числа, във втората ще записваме най-гоямото повтореине от числа и в последната (value) ще запишем елемента, който съзава най-дългата поредица.
- //С for цикъла сравняваме числата позиция по позиция. Ако намерим две еднакви се изпълнява if условието, в което са събрани трите променливи.
- //Накрая яко longestSequence е различно от 0 т.е. ако сме открили някаква повтаряща се поредица, изписваме колко е голяма тя на конзолата.
- Problem 5. Maximal increasing sequence/////////////////////////////////////////////////////
- //Write a program that finds the maximal increasing sequence in an array.
- //Write a program that finds the maximal increasing sequence in an array.
- //string input = Console.ReadLine();
- string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- int[] array = new int[STRnumbers.Length];
- array = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
- int maxSequence = 0;
- int sequence = 1;
- string sequenceNumbers = "";
- string maxSequenceNumbers = "";
- for (int i = 0; i < array.Length - 1; i++)
- {
- if (array[i + 1] - array[i] == 1)
- {
- sequence++;
- sequenceNumbers += array[i] + " ";
- }
- else
- {
- if (maxSequence < sequence)
- {
- maxSequence = sequence;
- sequenceNumbers += array[i] + " ";
- maxSequenceNumbers = sequenceNumbers;
- }
- sequence = 1;
- sequenceNumbers = "";
- }
- }
- if (maxSequence < sequence)
- {
- sequenceNumbers += array[array.Length - 1];
- maxSequenceNumbers = sequenceNumbers;
- }
- Console.WriteLine("The maximal increasing sequence in an array is: ");
- Console.WriteLine(maxSequenceNumbers);
- //ОБЯСНЕНИЕ: Създаваме си масив от някакви числа, които въвеждаме ръчно от конзолата. Създаваме си първоначално 4 променливи.
- //В maxSequence ще отброяваме броя на нарастващите последователности, ако може така да се каже. Примерно ако имаме поредица от числата 1,2,5,1 в тази променлива ще се запише 3.
- //В sequence променливата ще записваме броя на моментните повторения, които цикълът е открил.
- //В sequenceNumbers ще се записват самите числа, които в момента цикъла проверява.
- //В maxSequenceNumbers ще се съдържа максималната, най-голямата последователност от нанрастващи числа, която е открита до момента.
- //Пускаме един нормален for цикъл, с който да срявняваме числата в поредицата, като в зависимост от това дали числото е по-малко или по-голямо от следващото сравнявано в редицата се изпълнява едно от if условията.
- //Когато програмата премине през скобите със самите if условия, "зачистваме" sequence и sequenceNumbers променливите, съответно с числото 1 и "". След което останалато е лесно - програмата се връща отново горе във for цикъла,
- //минава и сравнява останалите числа по редицата и накрая прогрмата принтира резултата
- Problem 6. Maximal K sum //////////////////////////////////////////////////////////
- //Write a program that reads two integer numbers N and K and an array of N elements from the console. Find in the array those K elements that have maximal sum.
- Console.Write("Enter N: ");
- //string input = Console.ReadLine();
- string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- int[] array = new int[STRnumbers.Length];
- array = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
- Console.Write("Enter K: ");
- int k = int.Parse(Console.ReadLine());
- string bestSeq = "";
- int sum = 0;
- int bestSum = int.MinValue;
- int arrayLen = array.Length;
- string currentSeq = "";
- for (int i = 0; i < arrayLen; i++)
- {
- if (i + k > arrayLen)
- {
- break;
- }
- for (int j = i; j < i + k; j++)
- {
- sum = sum + array[j];
- //j != i + k - 1 ? currentSeq + ", " : currentSeq;
- if (j == 0)
- {
- currentSeq = "" + array[j];
- continue;
- }
- currentSeq = currentSeq + ',' + array[j];
- }
- if (sum > bestSum)
- {
- bestSeq = currentSeq;
- bestSum = sum;
- }
- sum = 0;
- currentSeq = "";
- }
- Console.WriteLine(bestSeq);
- Console.WriteLine(bestSum);
- }
- }
- //ОБЯСНЕНИЕ: Решението е подобно като на задача 5. Особеното е че с if условие се прави проверка i + k > arrayLen, дали случайно не сме излезнали от рамките на масива.
- //След това за всяка "заградена" съвкупност от i+k индекси до края на масива правим сравнеиня на самите суми и намираме, коя е най-голямата.
- 7 sort array ////////////////////////////////////////////////////////////////
- int[] myArray = { 12, 5, 90, 35, 358 };
- Array.Sort(myArray);
- for (int i = 0; i < myArray.Length; i++)
- {
- Console.Write(i != myArray.Length - 1 ? myArray[i] + ", " : myArray[i] + "\n");
- }
- Console.WriteLine();
- Problem 8. Maximal sum /////////////////////////////////////////////////////////////
- //Write a program that finds the sequence of maximal sum in given array. Can you do it with only one loop (with single scan through the elements of the array)?
- //Example: {2, 3, -6, -1, 2, -1, 6, 4, -8, 8} -> {2, -1, 6, 4}
- int[] array = { 2, 3, -6, -1, 2, -1, 6, 4, -8, 8 };// ako si sloja 9 she mi zeme do 9
- int currentSum = array[0];
- int startIndex = 0;
- int endIndex = 0;
- int tempStartIndex = 0;
- int maxSum = array[0];
- for (int i = 1; i < array.Length; i++)
- {
- if (currentSum < 0)
- {
- currentSum = array[i];
- tempStartIndex = i;
- }
- else
- {
- currentSum += array[i];
- }
- if (currentSum > maxSum)
- {
- maxSum = currentSum;
- startIndex = tempStartIndex;
- endIndex = i;
- }
- }
- Console.WriteLine("The best sum is: {0} ", maxSum);
- Console.WriteLine("The best sequence is:");
- for (int i = startIndex; i <= endIndex; i++)
- {
- Console.Write(i != endIndex ? array[i] + ", " : array[i] + "\n");
- }
- Console.WriteLine();
- *
- ОБЯСНЕНИЕ: За решението на тази задача трябва да се използва алгоритъма на Кадан - http://en.wikipedia.org/wiki/Kadane%27s_algorithm
- Инициализираме си масив. Създаваме си 5-те основни променливи, които ще използваме в алгоритъма на Кадан. След това принтираме резултата на конзолата.
- */
- Problem 9. Frequent number /////////////////////////////////////////////
- //Write a program that finds the most frequent number in an array
- /////////////// vadi poslednoto ako ima ravni povtarqshti se
- var watch = System.Diagnostics.Stopwatch.StartNew();
- Console.Write("Enter length of the array: ");
- //string input = Console.ReadLine();
- string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- int[] array1 = new int[STRnumbers.Length];
- array1 = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
- Array.Sort(array1);
- //for (int i = 0; i < array1.Length - 1; i++)
- //{
- // for (int j = i + 1; j < array1.Length; j++)
- // {
- // if (array1[i] >= array1[j])
- // {
- // int a = array1[i];
- // array1[i] = array1[j];
- // array1[j] = a;
- // }
- // }
- //}
- int counter = 0;
- int bigCounter = 0;
- int whatNum = 0;
- for (int i = 0; i < array1.Length - 1; i++)
- {
- if (array1[i] == array1[i + 1])
- {
- counter++;
- if (bigCounter <= counter)
- {
- bigCounter = counter;
- whatNum = array1[i];
- }
- }
- else
- {
- counter = 0;
- }
- }
- Console.WriteLine("We have {0} members of the number \"{1}\" in the array", bigCounter + 1, whatNum);
- watch.Stop();
- string elapsedMs = watch.ElapsedMilliseconds.ToString();
- System.Diagnostics.Debug.WriteLine(elapsedMs);
- Console.WriteLine(elapsedMs);
- }
- }
- }
- ////////////////// 2 reshenie vadi purvoto ako ima ravno povtarqsti se elementi /////////////////////////////////
- Console.Write("Enter length of the array: ");
- //string input = Console.ReadLine();
- string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- int[] nums = new int[STRnumbers.Length];
- nums = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
- Dictionary<int, int> occurences = new Dictionary<int, int>();
- for (int i = 0; i < nums.Length; i++)
- {
- if (!occurences.ContainsKey(nums[i]))
- {
- occurences.Add(nums[i], 1);
- }
- else
- {
- occurences[nums[i]]++;
- }
- }
- List<KeyValuePair<int, int>> myList = occurences.ToList();
- myList.Sort(
- delegate(KeyValuePair<int, int> firstPair,
- KeyValuePair<int, int> nextPair)
- {
- return firstPair.Value.CompareTo(nextPair.Value);
- }
- );
- ////// moga da sortiram i po KEY ne samo po VALUE
- // myList.Sort(
- // delegate(KeyValuePair<int, int> firstPair,
- // KeyValuePair<int, int> nextPair)
- // {
- // return firstPair.Key.CompareTo(nextPair.Key);
- // }
- //);
- myList.Reverse();
- var k = 0;
- foreach (var dr in myList)
- {
- if (dr.Value == dr.Value)
- {
- Console.WriteLine("{0} = {1,3}", dr.Key, dr.Value);
- k++;
- if (k > 3)
- {
- break;
- }
- }
- }
- /////////////////////////// 3 reshenie nai-pravilno da mi izkarva vsi4ki nai-mnogo povtarqshti se //////////////////////////////////////////
- Console.WriteLine("Enter a number for N:");
- int N = int.Parse(Console.ReadLine());
- int[] nums = new int[N];
- Console.WriteLine("Enter {0} number(s) to array:", N);
- for (int i = 0; i < N; i++)
- {
- nums[i] = int.Parse(Console.ReadLine());
- }
- Dictionary<int, int> occurences = new Dictionary<int, int>();
- for (int i = 0; i < N; i++)
- {
- if (!occurences.ContainsKey(nums[i]))
- {
- occurences.Add(nums[i], 1);
- }
- else
- {
- occurences[nums[i]]++;
- }
- }
- int max = occurences.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
- Console.WriteLine("Array's elements: {0}", string.Join(", ", nums));
- Console.WriteLine("Most frequent number: ");
- foreach (KeyValuePair<int, int> pair in occurences)
- {
- if (pair.Value == occurences[max])
- {
- Console.WriteLine("{0} ({1} times)", pair.Key, occurences[pair.Key]);
- }
- }
- //ОБЯСНЕНИЕ: С първите два for цикъла първо подреждаме самия масив от числа във възходящ ред. Стандартен алгоритъм за сортиране си е това, нищо сложно.
- //След което правим класическите три променливи, в които да отброяваме: броя на повторенията към момента, най-голямото повтериение и самото число, което е с най-голямото повторение.
- //Пускаме трети for цикъл, с който започваме да с сравняваме един по един елементите по елементите из масива и съответно ако има еднакви числа в поредица едно до друго if и else конструкцията в кода се грижат за това накрая конзолата да ни ги изпечата правилното решение на задачата.
- Problem 10. Find sum in array //////////////////////////////////////////////////////////////////////////////
- ///Write a program that finds in given array of integers a sequence of given sum S (if present).
- //Example: {4, 3, 1, 4, 2, 5, 8}, S=11 {4, 2, 5}
- int[] array = { 4, 3, 1, 4, 2, 5, 8 };
- Console.WriteLine("Enter sumS:");
- int sumS = int.Parse(Console.ReadLine());
- int currentSum = array[0];
- int startIndex = 0;
- int endIndex = 0;
- int CurrSum = 0;
- for (int i = 0; i < array.Length - 1; i++)
- {
- CurrSum += array[i];
- startIndex = i;
- for (int p = i + 1; p < array.Length; p++)
- {
- CurrSum += array[p];
- endIndex = p;
- if (CurrSum == sumS)
- {
- for (int k = startIndex; k <= endIndex; k++)
- {
- Console.Write(k != endIndex ? array[k] + ", " : array[k] + "\n");
- }
- return;
- }
- }
- CurrSum = 0;
- }
- Console.WriteLine("The sumS is not present in the array.");
- /*
- ОБЯСНЕНИЕ: Тук търсим в масив последователна поредица от числа, чиято сума да е равна на числото S. Правим си три променливи по подобие на 8-ма задача: startIndex, endIndex, CurrSum.
- С два for цикъла обхождаме масива събирайки отляво-надясно елементите му. В момента, в който открием елементи, чиято сума да удовлетворява if условието (а именно - временната CurrSum да бъде равна на sumS)
- влизаме в третия for цикъл, който ни отпечатва индексите (startIndex e нейното начало, а endIndex нейния край) на търсената поредица от числа. Ако не намерим такава поредица от елементи - изписваме, че в масива няма такава поредица.
- */
- Problem 11. Binary search/////////////////////////////////////////////////////////////
- static int BinSearch(int[] array, int key)
- {
- Array.Sort(array);
- int iMax = array.Length - 1;
- int iMin = 0;
- while (iMax >= iMin)
- {
- int iMidpoint = (iMin + iMax) / 2;
- if (array[iMidpoint] < key)
- {
- iMin = iMidpoint + 1;
- }
- else if (array[iMidpoint] > key)
- {
- iMax = iMidpoint - 1;
- }
- else
- {
- return iMidpoint;
- }
- }
- return -1;
- }
- static void Main()
- {
- int[] myArray = { 4, 7, 4, 6, 2, 7, 5, 12, 22, 13, };
- int key = 7;
- Console.WriteLine(BinSearch(myArray, key));
- }
- }
- //ОПИСАНИЕ: Задача имаща за цел да ни запознае с един от основните алгоритми в програмирането - Binary Search. Повече инфо за него тук - http://en.wikibooks.org/wiki/Algorithm_Implementation/Search/Binary_search
- Problem 12. Index of letters /////////////////////////////////////////////////////////////
- string kkk = Console.ReadLine();
- string[] stringk = kkk.Split(' ');
- string restOfArray = string.Join("", stringk);
- // ETO TAKA OT STRING ARR to char arr
- char[] alphabet = restOfArray.ToCharArray();
- for (int i = 0; i < alphabet.Length; i++)
- {
- int ssh = 0;
- if (alphabet[i] > 'Z')
- {
- ssh = alphabet[i] - 96;
- }
- else
- {
- ssh = alphabet[i] - '@';
- }
- int kur = alphabet[i];
- if (ssh > 0 && ssh <= 26)
- {
- Console.WriteLine("{0}-->{1}--{2}", kur, ssh, alphabet[i]);
- }
- }
- Problem 15. Prime numbers /////////////////////////////////////////////////
- class PrintNumberUsingSieveOfEratosthenes
- {
- static List<int> SieveLINQ(int upTo)
- {
- int index = 1;
- List<int> result = Enumerable.Range(2, upTo - 2).ToList();
- while (index <= Math.Sqrt(upTo))
- {
- index = result.First(i => i > index);
- result.RemoveAll(i => i != index && i % index == 0);
- }
- return result;
- }
- static void Sieve(int upTo)
- {
- bool[] notPrime = new bool[upTo];
- notPrime[0] = notPrime[1] = true;
- for (int i = 2; i < Math.Sqrt(notPrime.Length); i++)
- {
- if (!notPrime[i])
- {
- for (int j = i * 2; j < notPrime.Length; j += i)
- {
- notPrime[j] = true;
- }
- }
- }
- //Print(notPrime);
- }
- static void Print(bool[] arr)
- {
- for (int i = 0; i < arr.Length; i++)
- {
- if (arr[i] == false)
- {
- Console.Write(i + " ");
- }
- }
- }
- static void Main()
- {
- DateTime first = DateTime.Now;
- Sieve(10000000);
- TimeSpan normalSieveTime = DateTime.Now - first;
- DateTime second = DateTime.Now;
- List<int> linqResult = SieveLINQ(10000000);
- TimeSpan linqSieveTime = DateTime.Now - second;
- Console.WriteLine("Sieve with LINQ: {0}", linqSieveTime);
- Console.WriteLine("Sieve with bool: {0}", normalSieveTime);
- }
- }
- ///////////////////////////////////////// 16 //////////////////////////////////////////////////////////
- long S = long.Parse(Console.ReadLine());
- int N = Int32.Parse(Console.ReadLine());
- long[] numbers = new long[N];
- for (int i = 0; i < N; i++) numbers[i] = long.Parse(Console.ReadLine());
- Dictionary<long, int> sums = new Dictionary<long, int> { { 0, 1 } };
- foreach (var currentElement in numbers)
- {
- Dictionary<long, int> copyOfSums = new Dictionary<long, int>(sums);
- foreach (KeyValuePair<long, int> pair in copyOfSums)
- {
- var currentSum = currentElement + pair.Key;
- if (!sums.ContainsKey(currentSum)) sums.Add(currentSum, pair.Value);
- else sums[currentSum] += pair.Value;
- }
- }
- sums[0]--; //remove the empty subset
- Console.WriteLine(sums.ContainsKey(S) ? sums[S] : 0);
- 17 //////////////////////////////// 17 //////////////////////////////////////////////////////////////////////////
- Console.WriteLine("Enter a size of array: ");
- int size = int.Parse(Console.ReadLine());
- Console.WriteLine("Enter a number of elements in subset: ");
- int elements = int.Parse(Console.ReadLine());
- if (size < elements)
- {
- Console.WriteLine("Number of elements must be smaller or equal than the array's length!");
- return;
- }
- Console.WriteLine("Enter a number for a sum that we are going to looking for: ");
- int sum = int.Parse(Console.ReadLine());
- int[] numbers = new int[size];
- Console.WriteLine("Enter {0} number(s) to array: ", size);
- for (int i = 0; i < numbers.Length; i++)
- {
- numbers[i] = int.Parse(Console.ReadLine());
- }
- PrintElementOfArray(numbers);
- FindAndPrintSubsetsWithMaxSum(numbers, elements, sum);
- }
- static void FindAndPrintSubsetsWithMaxSum(int[] numbers, int elements, int sum)
- {
- Console.Write("Subsets with {0} elements and sum {1}: ", elements, sum);
- int totalSubsets = (int)(Math.Pow(2, numbers.Length) - 1); // Total subsets = 2^n - 1
- bool isFoundSubset = false;
- for (int i = 1; i <= totalSubsets; i++)
- {
- if (ElementsInSubset(i) == elements)
- {
- List<int> currentSubset = numbers.Where((t, j) => ((i >> j) & 1) == 1).ToList();
- if (currentSubset.Sum() == sum)
- {
- isFoundSubset = true;
- PrintSubsetWithGivenSum(currentSubset);
- }
- }
- }
- if (!isFoundSubset) Console.WriteLine("There are no subsets with {0} elements and Sum {1}...", elements, sum);
- }
- static int ElementsInSubset(int currentNumber)
- {
- int elementsInSubset = 0;
- while (currentNumber != 0)
- {
- elementsInSubset += currentNumber & 1;
- currentNumber >>= 1;
- }
- return elementsInSubset;
- }
- static void PrintElementOfArray(int[] numbers)
- {
- Console.WriteLine("Array's elements: {0}", string.Join(", ", numbers));
- }
- static void PrintSubsetWithGivenSum(List<int> subset)
- {
- Console.WriteLine(string.Join(", ", subset));
- }
- 18 ///////////////////////////////// 18 /////////////////////////////////////////////////////////////////////////
- static List<int>[] allBestSubsets = new List<int>[40];
- static int index = 0;
- static void Main()
- {
- Console.WriteLine("Enter a number for the array's length: ");
- int n = int.Parse(Console.ReadLine());
- int[] numbers = new int[n];
- Console.WriteLine("Enter {0} number(s) to array: ", n);
- for (int i = 0; i < numbers.Length; i++)
- {
- numbers[i] = int.Parse(Console.ReadLine());
- }
- FindAllSubsetsWithGivenSum(numbers);
- PrintLongestSubsets(numbers);
- }
- static void PrintLongestSubsets(int[] numbers)
- {
- Console.WriteLine("Array's elements: {0}", string.Join(", ", numbers));
- Console.WriteLine("Longest subset(s) with increasing elements: ");
- for (int i = 0; i < index; i++) Console.WriteLine(string.Join(", ", allBestSubsets[i]));
- }
- // Find all subsets using BITWISE REPRESENTATION
- static void FindAllSubsetsWithGivenSum(int[] numbers)
- {
- List<int> subset = new List<int>();
- long bestLength = 0;
- long totalSubsets = (long)(Math.Pow(2, numbers.Length) - 1); // Number of subsets
- for (long i = totalSubsets; i >= 1; i--)
- {
- long elementInSubset = ElementsInSubset(i);
- if (elementInSubset < bestLength) continue;
- subset.Clear();
- subset.AddRange(numbers.Where((t, j) => ((i >> j) & 1) == 1));
- if (IsIncreasingElements(subset))
- {
- if (bestLength < elementInSubset)
- {
- allBestSubsets = new List<int>[40];
- index = 0;
- }
- bestLength = elementInSubset;
- allBestSubsets[index++] = new List<int>(subset);
- }
- }
- }
- // Optimization method
- static long ElementsInSubset(long currentNumber)
- {
- long elementsInSubset = 0;
- while (currentNumber != 0)
- {
- elementsInSubset += currentNumber & 1;
- currentNumber >>= 1;
- }
- return elementsInSubset;
- }
- static bool IsIncreasingElements(List<int> numbers)
- {
- for (int i = 0; i < numbers.Count - 1; i++)
- if (numbers[i] > numbers[i + 1])
- return false;
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement