Advertisement
n4wn4w

C# Arrays

Apr 15th, 2015
360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 41.64 KB | None | 0 0
  1.            
  2.             var arr = new[]
  3.             {
  4.                 new{ Name= "pesho", Age = 15},
  5.                
  6.                 new{ Name= "agosho", Age = 17},
  7.                  new{ Name= "esho", Age = 16},
  8.             };
  9.  
  10.             Array.Sort(arr, (a, b) => a.Age.CompareTo(b.Age));
  11.             string[] kom = Array.ConvertAll(arr, a=> a.Name);
  12.  
  13.             foreach (var item in arr)
  14.             {
  15.                 Console.WriteLine(item);
  16.             }
  17.  
  18.             foreach (var item in kom)
  19.             {
  20.                 Console.WriteLine(item);
  21.             }
  22.  
  23. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  24.  //string input = Console.ReadLine();
  25.             string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  26.  
  27.             int[] nums = new int[STRnumbers.Length];
  28.             nums = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
  29.             //for (int i = 0; i < nums.Length; i++)
  30.             //{
  31.             //    nums[i] = int.Parse(Console.ReadLine());
  32.             //}
  33.  
  34.             Array.Sort(nums);
  35.             Console.WriteLine();
  36.  
  37.             for (int i = 0; i < nums.Length; i++)
  38.             {
  39.                 Console.WriteLine(nums[i]);
  40.             }
  41.  
  42.             Console.WriteLine();
  43.             Console.WriteLine(nums.Sum());
  44.             Console.WriteLine();
  45.             Console.WriteLine(nums.Skip(3).First());// propusni purvite 3 i mi vzemi sledvashtoto koeto sledva
  46.             Console.WriteLine();
  47.             /////////////////////
  48.             foreach (var i in nums.Skip(3).Take(2).Reverse())// vzemi mi 4 ot  masiva i mi  vzemi  sledvashtite 2 i mi gi reversni
  49.             {
  50.                 Console.Write(i + " ");
  51.             }
  52.  
  53. /////////////////////////////////////////////////////
  54.  
  55.  
  56. string[] names = { "Peter", "Maria", "Katya", "Todor", "A9ll" , "Zoro","4543" };
  57.            
  58.             foreach (var name in names)
  59.             {
  60.                 Console.WriteLine(name);
  61.             }
  62.  
  63.             Console.WriteLine();
  64.  
  65.             Array.Sort(names);
  66.             foreach (var name in names)
  67.             {
  68.                 Console.WriteLine(name);
  69.             }
  70.             ////
  71.             Console.WriteLine();
  72.             names[0] = names[0] + " (junior)";
  73.            
  74.             Array.Reverse(names);
  75.             foreach (var name in names)
  76.             {
  77.                 Console.WriteLine(name);
  78.             }
  79.  
  80.  
  81. ////////////////////////////////////////////////////////
  82.  
  83. reverse array ////////////
  84.  
  85.             int[] array = new int[] { 1, 2, 3, 4, 5 };
  86.  
  87.             // Get array size
  88.             // int length = array.Length;
  89.  
  90.             // Declare and create the reversed array
  91.             int[] reversed = new int[array.Length];
  92.  
  93.  
  94.             for (int index = 0; index < array.Length; index++)
  95.             {
  96.                 Console.WriteLine(array[index]);
  97.             }
  98.  
  99.             // Initialize the reversed array
  100.             for (int index = 0; index < array.Length; index++) //////// za da di printi 54321
  101.             {
  102.                 reversed[array.Length - index - 1] = array[index];
  103.             }
  104.  
  105.             //for (int index = 0; index < array.Length - 1; index++) //////// za da di printi 43210
  106.             //{
  107.             //    reversed[array.Length - index - 2] = array[index];
  108.             //}
  109.  
  110.             Console.WriteLine();
  111.             // Print the reversed array elements
  112.             for (int index = 0; index < reversed.Length; index++)
  113.             {
  114.                 Console.WriteLine(reversed[index]);
  115.             }
  116.  
  117. //// simetrichen array ////////
  118.  
  119.              // primer 1 2 3 2 1
  120.             // Declaring the array
  121.  
  122.             //string input = Console.ReadLine();
  123.             string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  124.  
  125.             int[] nums = new int[STRnumbers.Length];
  126.             nums = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
  127.  
  128.  
  129.             // Declaring the array
  130.            
  131.  
  132.             bool isSymmetric = true;
  133.             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
  134.             {                                         // pri vtoroto zavurtane mi vzima 1 i 3 element i taka natatuk
  135.                 if (nums[i] != nums[nums.Length - i - 1])
  136.                 {
  137.                     isSymmetric = false;
  138.                     break;
  139.                 }
  140.             }
  141.  
  142.             Console.WriteLine("Symmetric? --> {0}", isSymmetric);
  143.  
  144.  
  145. //////////////////////////////////////////////////////////////
  146. //// natrupvane ot edin masiv v drug masiv
  147.  
  148.             int[] arr = { 1, 2, 3, 4, 5, 6 };
  149.             int[] arr2 = new int[arr.Length];
  150.  
  151.             for (int i = 0; i < arr.Length; i++)
  152.             {
  153.                 arr2[i] = arr[i] * arr[i];
  154.             }
  155.             //////////////////
  156.             for (int i = 0; i < arr2.Length; i++)
  157.             {
  158.                 Console.Write("arr2 = {0} ", arr2[i]);
  159.             }
  160.  
  161.             //////// reversvane na masiv 2 variant
  162.             Console.WriteLine();
  163.             for (int i = arr.Length - 1; i > -1; i--)
  164.             {
  165.                 Console.Write("arr = {0} ", arr[i]);
  166.                
  167.             }
  168.             Console.WriteLine();
  169.  
  170.             for (int i = arr.Length - 1; i > -1; i--)
  171.             {
  172.                 Console.Write("arr2 = {0} ", arr2[i]);
  173.             }
  174.             Console.WriteLine();
  175.  
  176.  
  177.  
  178. ////////////////////////// umnojavane   ///////////////////////////////////////////
  179.  
  180.             int[] arr = { 1, 2, 3, 4, 5, 6 };
  181.             int[] arr2 = new int[arr.Length /2];
  182.             bool ishui = false;
  183.  
  184.             for (int i = 0 , j =0; i < arr.Length-1; i +=2 , j++)
  185.             {
  186.                 if (ishui ==  true)  // nachin da ne se pravi neshto pri purvata iteracia na cikula
  187.                 {
  188.                     arr2[j] = arr2[j] + 1;
  189.                 }
  190.                 arr2[j] = arr[i] + arr[i + 1];
  191.                 ishui = true;
  192.                
  193.             }
  194.             //////////////////
  195.             Console.WriteLine();
  196.             for (int i = 0; i < arr.Length; i ++)
  197.             {
  198.                  if (i == 3) ///////  za propuskane iteracia v cikul
  199.                 {
  200.                     continue;
  201.                 }
  202.                 Console.Write("arr2 = {0} ", arr[i]);
  203.             }
  204.             Console.WriteLine();
  205.             //////// reversvane na masiv 2 variant
  206.             Console.WriteLine();
  207.             for (int i = arr.Length - 1; i > -1; i--)
  208.             {
  209.                 Console.Write("arr = {0} ", arr[i]);
  210.                
  211.             }
  212.             Console.WriteLine();
  213.  
  214.             for (int i = arr2.Length - 1; i > -1; i--)
  215.             {
  216.                 Console.Write("arr2 = {0} ", arr2[i]);
  217.             }
  218.             Console.WriteLine();
  219.  
  220.  
  221. ////////////////////////////////////
  222.  
  223.  
  224.  
  225. //////////////////////////  array homework    /////////////////////////////////////
  226.  
  227.  
  228.  
  229.  
  230.  
  231. 1 zadacha
  232.  
  233.  
  234. /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.
  235.  
  236.                 int[] nums = new int[20];
  237.         for (int i = 0; i < nums.Length; i++)
  238.         {
  239.             nums[i] = i * 5;
  240.         }
  241.  
  242.         for (int i = 0; i < nums.Length; i++)
  243.         {
  244.             Console.Write(i != nums.Length - 1 ? nums[i] + ", " : nums[i] + "\n");
  245.         }
  246.        
  247.  
  248.  
  249.  
  250. //ОПИСАНИЕ: Инициализираме масив от 20 елемента. С for цикъл обхождаме елементите му всеки един от които го умножаваме по 5.
  251. //След това с втория for цикъл принтираме резултата на конзолата.
  252.  
  253.  
  254. Problem 2. Compare arrays///////////////////////////////////////////////////////////////////////////////////
  255.  //Write a program that reads two arrays from the console and compares them element by element
  256.  
  257.           Console.WriteLine("Pleas enter the lenght of the FIRST Array:");
  258.             //string input = Console.ReadLine();
  259.             string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  260.  
  261.             int[] firstArr = new int[STRnumbers.Length];
  262.             firstArr = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
  263.  
  264.  
  265.            Console.WriteLine("Pleas enter the lenght of the SECOND Array:");
  266.             //string input1 = Console.ReadLine();
  267.             string[] STRnumbers1 = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  268.  
  269.             int[] secondArr = new int[STRnumbers1.Length];
  270.             secondArr = Array.ConvertAll<string, int>(STRnumbers1, int.Parse);
  271.  
  272.  
  273.          
  274.  
  275.             if (firstArr.Length != secondArr.Length)
  276.             {
  277.                 Console.WriteLine("Error! The FIRST Array lenght and the SECOND Array lenght are not equal. Please try again and enter EQUAL array lenghts");
  278.             }
  279.             else
  280.             {
  281.                 bool areEqual = true;
  282.                 for (int i = 0; i < secondArr.Length; i++)
  283.                 {
  284.                     if (firstArr[i] != secondArr[i])
  285.                     {
  286.                         areEqual = false;
  287.                         Console.WriteLine("The two arrays are NOT the same: {0}", areEqual);
  288.                         break;
  289.                     }
  290.                 }
  291.                 if (areEqual == true)
  292.                 {
  293.                      Console.WriteLine("The two arrays are the same: {0}", areEqual);
  294.                 }
  295.                
  296.             }
  297.     }
  298. }
  299.  
  300. //ОБЯСНЕНИЕ: Първото нещо, което правим е да инициализираме самия размер на двата масива.
  301. //Макар и незадължително по условие, с помоща на if условието проверяваме дали броя на елементите в двата масива са равни.
  302. //Това може и да не го правим, ако просто накараме потребителя веднъж да въведе число за размера на масивите (веднъж като го въведе ще го ползваме същата променлива при инициализацията и на втория масив).
  303. //След това с помощта на for цикли въвеждаме самите стойности из одтелните позиции на двата масива.
  304. //Преминаваме към същинската част на задачата - сравняване на самите отделни стойности в масива една по една. Използваме булева променлива, в която изначално казваме че елементите в двата масива са равни, до доказване на противното.
  305. //С помощта на for цикъл започваме да сравняваме отделните елементи на масивите един по един.
  306. //В случай че два елемента от една и съща позиция в масивите се случи да не са равни се изпълнява if условието, променливата, която съзадохе по-горе вече става false и се прехвърляме към break оператъра, тъй като при това положение няма смисъл да продължаваме да сравняваме останалите елементи из масивите.
  307. //Отпечатваме резолтата на конзолата.
  308.  
  309.  
  310.  
  311.  
  312. Problem 3. Compare char arrays ////////////////////////////////////////////////////////////////////////////
  313.  
  314.  
  315. //Write a program that reads two arrays from the console and compares them element by element
  316.  
  317.             Console.WriteLine("Pleas enter the lenght of the FIRST Array:");
  318.             //string input = Console.ReadLine();
  319.             string STRnumbers = Console.ReadLine();
  320.  
  321.             char[] firstArr = STRnumbers.ToCharArray();
  322.             //firstArr = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
  323.  
  324.  
  325.            Console.WriteLine("Pleas enter the lenght of the SECOND Array:");
  326.             //string input1 = Console.ReadLine();
  327.             string STRnumbers1 = Console.ReadLine();
  328.  
  329.             char[] secondArr = STRnumbers1.ToCharArray();
  330.             //secondArr = Array.ConvertAll<string, int>(STRnumbers1, int.Parse);
  331.  
  332.  
  333.             if (firstArr.Length != secondArr.Length)
  334.             {
  335.                 Console.WriteLine("Error! The FIRST Array lenght and the SECOND Array lenght are not equal. Please try again and enter EQUAL array lenghts");
  336.             }
  337.  
  338.             bool areEqual = true;
  339.             for (int i = 0; i < secondArr.Length; i++)
  340.             {
  341.                 if (firstArr[i] != secondArr[i])
  342.                 {
  343.                     areEqual = false;
  344.                     break;
  345.                 }
  346.             }
  347.  
  348.             Console.WriteLine("The two arrays are equal: {0}", areEqual);
  349.            
  350.  
  351.  
  352.  
  353. // sushtoto kato  to 2 zadacha samo che smenqme s charove  firstArr[i] = char.Parse(Console.ReadLine());
  354. //ОБЯСНЕНИЕ: решението е почти същото като на задача 2 от Масиви.
  355. //Разликата е че зададох char-овете предварително в самия код, защото не се сетих как може да се направи, така че потребителя сам самичък да си ги въведене...
  356.  
  357.  
  358.  
  359. Problem 4. Maximal sequence/////////////////////////////////////////////////////////////////
  360. //Write a program that finds the maximal sequence of equal elements in an array.
  361.  
  362.            
  363.  class Program
  364.     {
  365.  
  366.  
  367.  
  368.      static int bestLength = 0;
  369.      static int bestElement = 0;
  370.  
  371.     static void Main()
  372.     {
  373.         Console.WriteLine("Enter a lenght of the array:");
  374.  
  375.         string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  376.  
  377.         int[] firstArr = new int[STRnumbers.Length];
  378.         firstArr = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
  379.  
  380.  
  381.  
  382.         FindBestSequence(firstArr);
  383.  
  384.         Console.Write("The array contains following elements: " + "{" + string.Join(", ", firstArr) + "}\n");
  385.         Console.Write("The maximal sequence of equal elements in the array is: {");
  386.         for (int i = 0; i < bestLength; i++)
  387.         {
  388.             Console.Write(i != bestLength - 1 ? bestElement + ", " : bestElement + "}\n");
  389.         }
  390.     }
  391.  
  392.     private static void FindBestSequence(int[] nums)
  393.     {
  394.         int currLength = 1;
  395.         int currElement = nums[0];
  396.  
  397.         if (nums.Length == 1)
  398.         {
  399.             bestElement = currElement;
  400.             bestLength = 1;
  401.             return;
  402.         }
  403.  
  404.         for (int i = 1; i < nums.Length; i++)
  405.         {
  406.             if (nums[i] == currElement)
  407.             {
  408.                 currLength++;
  409.             }
  410.             else
  411.             {
  412.                 currElement = nums[i];
  413.                 currLength = 1;
  414.             }
  415.  
  416.             if (currLength >= bestLength)
  417.             {
  418.                 bestLength = currLength;
  419.                 bestElement = currElement;
  420.             }
  421.         }
  422.  
  423.  
  424.         }
  425.  
  426.            
  427. //ОБЯСНЕНИЕ: Заделяме масив и го инициализираме. Създаваме три нови променливи: counter, longestSequence и value.
  428. //В първата ще записваме текущото проверявано повторение от числа, във втората ще записваме най-гоямото повтореине от числа и в последната (value) ще запишем елемента, който съзава най-дългата поредица.
  429. //С for цикъла сравняваме числата позиция по позиция. Ако намерим две еднакви се изпълнява if условието, в което са събрани трите променливи.
  430. //Накрая яко longestSequence е различно от 0 т.е. ако сме открили някаква повтаряща се поредица, изписваме колко е голяма тя на конзолата.
  431.  
  432.  
  433.  
  434.  
  435. Problem 5. Maximal increasing sequence/////////////////////////////////////////////////////
  436.  
  437.   //Write a program that finds the maximal increasing sequence in an array.
  438.  
  439.            //Write a program that finds the maximal increasing sequence in an array.
  440.  
  441.             //string input = Console.ReadLine();
  442.             string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  443.  
  444.             int[] array = new int[STRnumbers.Length];
  445.             array = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
  446.  
  447.             int maxSequence = 0;
  448.             int sequence = 1;
  449.             string sequenceNumbers = "";
  450.             string maxSequenceNumbers = "";
  451.             for (int i = 0; i < array.Length - 1; i++)
  452.             {
  453.  
  454.                 if (array[i + 1] - array[i] == 1)
  455.                 {
  456.                     sequence++;
  457.                     sequenceNumbers += array[i] + " ";
  458.                 }
  459.                 else
  460.                 {
  461.                     if (maxSequence < sequence)
  462.                     {
  463.                         maxSequence = sequence;
  464.                         sequenceNumbers += array[i] + " ";
  465.                         maxSequenceNumbers = sequenceNumbers;
  466.                     }
  467.                     sequence = 1;
  468.                     sequenceNumbers = "";
  469.                 }
  470.             }
  471.  
  472.             if (maxSequence < sequence)
  473.             {
  474.                 sequenceNumbers += array[array.Length - 1];
  475.                 maxSequenceNumbers = sequenceNumbers;
  476.             }
  477.  
  478.             Console.WriteLine("The maximal increasing sequence in an array is: ");
  479.             Console.WriteLine(maxSequenceNumbers);
  480.  
  481.  
  482.  
  483. //ОБЯСНЕНИЕ: Създаваме си масив от някакви числа, които въвеждаме ръчно от конзолата. Създаваме си първоначално 4 променливи.
  484. //В maxSequence ще отброяваме броя на нарастващите последователности, ако може така да се каже. Примерно ако имаме поредица от числата 1,2,5,1 в тази променлива ще се запише 3.
  485. //В sequence променливата ще записваме броя на моментните повторения, които цикълът е открил.
  486. //В sequenceNumbers ще се записват самите числа, които в момента цикъла проверява.
  487. //В maxSequenceNumbers ще се съдържа максималната, най-голямата последователност от нанрастващи числа, която е открита до момента.
  488. //Пускаме един нормален for цикъл, с който да срявняваме числата в поредицата, като в зависимост от това дали числото е по-малко или по-голямо от следващото сравнявано в редицата се изпълнява едно от if условията.
  489. //Когато програмата премине през скобите със самите if условия, "зачистваме"  sequence и sequenceNumbers променливите, съответно с числото 1 и "". След което останалато е лесно - програмата се връща отново горе във for цикъла,
  490. //минава и сравнява останалите числа по редицата и накрая прогрмата принтира резултата
  491.  
  492.  
  493. Problem 6. Maximal K sum //////////////////////////////////////////////////////////
  494.  
  495.  
  496. //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.
  497.  
  498.  
  499.        
  500.             Console.Write("Enter N: ");
  501.             //string input = Console.ReadLine();
  502.             string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  503.  
  504.             int[] array = new int[STRnumbers.Length];
  505.             array = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
  506.             Console.Write("Enter K: ");
  507.             int k = int.Parse(Console.ReadLine());
  508.  
  509.             string bestSeq = "";
  510.             int sum = 0;
  511.             int bestSum = int.MinValue;
  512.             int arrayLen = array.Length;
  513.             string currentSeq = "";
  514.             for (int i = 0; i < arrayLen; i++)
  515.             {
  516.                
  517.                 if (i + k > arrayLen)
  518.                 {
  519.                     break;
  520.                 }
  521.  
  522.                 for (int j = i; j < i + k; j++)
  523.                 {
  524.                     sum = sum + array[j];
  525.                     //j != i + k - 1 ? currentSeq + ", " : currentSeq;
  526.                     if (j == 0)
  527.                     {
  528.                         currentSeq = "" + array[j];
  529.                         continue;
  530.                     }
  531.                     currentSeq = currentSeq + ',' + array[j];
  532.                 }
  533.  
  534.                 if (sum > bestSum)
  535.                 {
  536.                     bestSeq = currentSeq;
  537.                     bestSum = sum;
  538.                 }
  539.                 sum = 0;
  540.                 currentSeq = "";
  541.             }
  542.             Console.WriteLine(bestSeq);
  543.             Console.WriteLine(bestSum);
  544.  
  545.     }
  546. }
  547.  
  548. //ОБЯСНЕНИЕ: Решението е подобно като на задача 5. Особеното е че с if условие се прави проверка i + k > arrayLen, дали случайно не сме излезнали от рамките на масива.
  549. //След това за всяка "заградена" съвкупност от i+k индекси до края на масива правим сравнеиня на самите суми и намираме, коя е най-голямата.
  550.  
  551.  
  552. 7 sort array ////////////////////////////////////////////////////////////////
  553.  
  554.  
  555.             int[] myArray = { 12, 5, 90, 35, 358 };
  556.  
  557.             Array.Sort(myArray);
  558.  
  559.             for (int i = 0; i < myArray.Length; i++)
  560.             {
  561.  
  562.                 Console.Write(i != myArray.Length - 1 ? myArray[i] + ", " : myArray[i] + "\n");
  563.             }
  564.             Console.WriteLine();
  565.  
  566.  
  567.  
  568. Problem 8. Maximal sum  /////////////////////////////////////////////////////////////
  569.  
  570.  
  571.  //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)?
  572.             //Example: {2, 3, -6, -1, 2, -1, 6, 4, -8, 8}  ->  {2, -1, 6, 4}
  573.  
  574.  
  575.             int[] array = { 2, 3, -6, -1, 2, -1, 6, 4, -8, 8 };// ako si sloja 9 she mi zeme do 9
  576.  
  577.             int currentSum = array[0];
  578.             int startIndex = 0;
  579.             int endIndex = 0;
  580.             int tempStartIndex = 0;
  581.             int maxSum = array[0];
  582.  
  583.             for (int i = 1; i < array.Length; i++)
  584.             {
  585.                 if (currentSum < 0)
  586.                 {
  587.                     currentSum = array[i];
  588.                     tempStartIndex = i;
  589.                 }
  590.                 else
  591.                 {
  592.                     currentSum += array[i];
  593.                 }
  594.                 if (currentSum > maxSum)
  595.                 {
  596.                     maxSum = currentSum;
  597.  
  598.                     startIndex = tempStartIndex;
  599.                     endIndex = i;
  600.                 }
  601.             }
  602.  
  603.             Console.WriteLine("The best sum is: {0} ", maxSum);
  604.  
  605.             Console.WriteLine("The best sequence is:");
  606.  
  607.             for (int i = startIndex; i <= endIndex; i++)
  608.             {
  609.                 Console.Write(i != endIndex ? array[i] + ", " : array[i] + "\n");
  610.             }
  611.             Console.WriteLine();
  612.            
  613.  
  614.  
  615. *
  616. ОБЯСНЕНИЕ: За решението на тази задача трябва да се използва алгоритъма на Кадан - http://en.wikipedia.org/wiki/Kadane%27s_algorithm
  617. Инициализираме си масив. Създаваме си 5-те основни променливи, които ще използваме в алгоритъма на Кадан. След това принтираме резултата на конзолата.
  618. */
  619.  
  620.  
  621. Problem 9. Frequent number /////////////////////////////////////////////
  622.  
  623. //Write a program that finds the most frequent number in an array
  624.  
  625.  
  626.  
  627. /////////////// vadi poslednoto ako  ima ravni povtarqshti se
  628.  
  629.             var watch = System.Diagnostics.Stopwatch.StartNew();
  630.  
  631.             Console.Write("Enter length of the array: ");
  632.             //string input = Console.ReadLine();
  633.             string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  634.  
  635.             int[] array1 = new int[STRnumbers.Length];
  636.             array1 = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
  637.  
  638.             Array.Sort(array1);
  639.  
  640.             //for (int i = 0; i < array1.Length - 1; i++)
  641.             //{
  642.             //    for (int j = i + 1; j < array1.Length; j++)
  643.             //    {
  644.             //        if (array1[i] >= array1[j])
  645.             //        {
  646.             //            int a = array1[i];
  647.             //            array1[i] = array1[j];
  648.             //            array1[j] = a;
  649.             //        }
  650.             //    }
  651.             //}
  652.             int counter = 0;
  653.             int bigCounter = 0;
  654.             int whatNum = 0;
  655.             for (int i = 0; i < array1.Length - 1; i++)
  656.             {
  657.                 if (array1[i] == array1[i + 1])
  658.                 {
  659.                     counter++;
  660.                     if (bigCounter <= counter)
  661.                     {
  662.                         bigCounter = counter;
  663.                         whatNum = array1[i];
  664.                     }
  665.                 }
  666.                 else
  667.                 {
  668.                     counter = 0;
  669.                 }
  670.             }
  671.             Console.WriteLine("We have {0} members of the number \"{1}\" in the array", bigCounter + 1, whatNum);
  672.             watch.Stop();
  673.  
  674.             string elapsedMs = watch.ElapsedMilliseconds.ToString();
  675.             System.Diagnostics.Debug.WriteLine(elapsedMs);
  676.             Console.WriteLine(elapsedMs);
  677.         }
  678.     }
  679. }
  680.  
  681. ////////////////// 2 reshenie vadi purvoto ako ima ravno povtarqsti se elementi /////////////////////////////////
  682.  
  683.  
  684.  Console.Write("Enter length of the array: ");
  685.             //string input = Console.ReadLine();
  686.             string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  687.  
  688.             int[] nums = new int[STRnumbers.Length];
  689.             nums = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
  690.  
  691.  
  692.            
  693.  
  694.             Dictionary<int, int> occurences = new Dictionary<int, int>();
  695.             for (int i = 0; i < nums.Length; i++)
  696.             {
  697.                 if (!occurences.ContainsKey(nums[i]))
  698.                 {
  699.                     occurences.Add(nums[i], 1);
  700.                 }
  701.                 else
  702.                 {
  703.                     occurences[nums[i]]++;
  704.                 }
  705.             }
  706.  
  707.             List<KeyValuePair<int, int>> myList = occurences.ToList();
  708.  
  709.             myList.Sort(
  710.                 delegate(KeyValuePair<int, int> firstPair,
  711.                 KeyValuePair<int, int> nextPair)
  712.                 {
  713.                     return firstPair.Value.CompareTo(nextPair.Value);
  714.                 }
  715.             );
  716.  
  717.             //////  moga da sortiram i po KEY ne samo po VALUE
  718.            // myList.Sort(
  719.            //    delegate(KeyValuePair<int, int> firstPair,
  720.            //    KeyValuePair<int, int> nextPair)
  721.            //    {
  722.            //        return firstPair.Key.CompareTo(nextPair.Key);
  723.            //    }
  724.            //);
  725.  
  726.            
  727.             myList.Reverse();
  728.            
  729.             var k = 0;
  730.             foreach (var dr in myList)
  731.             {
  732.                
  733.                 if (dr.Value == dr.Value)
  734.                 {
  735.                     Console.WriteLine("{0} = {1,3}", dr.Key, dr.Value);
  736.                     k++;
  737.                     if (k > 3)
  738.                     {
  739.                         break;
  740.                     }
  741.                 }
  742.             }
  743.  
  744.  
  745.  
  746. /////////////////////////// 3 reshenie nai-pravilno da mi izkarva vsi4ki nai-mnogo povtarqshti se //////////////////////////////////////////
  747.  
  748. Console.WriteLine("Enter a number for N:");
  749.         int N = int.Parse(Console.ReadLine());
  750.  
  751.         int[] nums = new int[N];
  752.         Console.WriteLine("Enter {0} number(s) to array:", N);
  753.         for (int i = 0; i < N; i++)
  754.         {
  755.             nums[i] = int.Parse(Console.ReadLine());
  756.         }
  757.  
  758.         Dictionary<int, int> occurences = new Dictionary<int, int>();
  759.         for (int i = 0; i < N; i++)
  760.         {
  761.             if (!occurences.ContainsKey(nums[i]))
  762.             {
  763.                 occurences.Add(nums[i], 1);
  764.             }
  765.             else
  766.             {
  767.                 occurences[nums[i]]++;
  768.             }
  769.         }
  770.  
  771.         int max = occurences.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
  772.  
  773.         Console.WriteLine("Array's elements: {0}", string.Join(", ", nums));
  774.         Console.WriteLine("Most frequent number: ");
  775.         foreach (KeyValuePair<int, int> pair in occurences)
  776.         {
  777.             if (pair.Value == occurences[max])
  778.             {
  779.                 Console.WriteLine("{0} ({1} times)", pair.Key, occurences[pair.Key]);
  780.             }
  781.         }
  782.  
  783.  
  784.  
  785.  
  786.  
  787.     //ОБЯСНЕНИЕ: С първите два for цикъла първо подреждаме самия масив от числа във възходящ ред. Стандартен алгоритъм за сортиране си е това, нищо сложно.
  788.     //След което правим класическите три променливи, в които да отброяваме: броя на повторенията към момента, най-голямото повтериение и самото число, което е с най-голямото повторение.
  789.     //Пускаме трети for цикъл, с който започваме да с сравняваме един по един елементите по елементите из масива и съответно ако има еднакви числа в поредица едно до друго if и else конструкцията в кода се грижат за това накрая конзолата да ни ги изпечата правилното решение на задачата.
  790.  
  791.  
  792. Problem 10. Find sum in array //////////////////////////////////////////////////////////////////////////////
  793.  
  794.  
  795. ///Write a program that finds in given array of integers a sequence of given sum S (if present).
  796.             //Example:   {4, 3, 1, 4, 2, 5, 8}, S=11  {4, 2, 5} 
  797.  
  798.             int[] array = { 4, 3, 1, 4, 2, 5, 8 };
  799.  
  800.             Console.WriteLine("Enter sumS:");
  801.             int sumS = int.Parse(Console.ReadLine());
  802.             int currentSum = array[0];
  803.  
  804.             int startIndex = 0;
  805.             int endIndex = 0;
  806.             int CurrSum = 0;
  807.             for (int i = 0; i < array.Length - 1; i++)
  808.             {
  809.                 CurrSum += array[i];
  810.                 startIndex = i;
  811.                 for (int p = i + 1; p < array.Length; p++)
  812.                 {
  813.                     CurrSum += array[p];
  814.                     endIndex = p;
  815.                     if (CurrSum == sumS)
  816.                     {
  817.                         for (int k = startIndex; k <= endIndex; k++)
  818.                         {
  819.                             Console.Write(k != endIndex ? array[k] + ", " : array[k] + "\n");
  820.                         }
  821.                         return;
  822.                     }
  823.                 }
  824.                 CurrSum = 0;
  825.             }
  826.             Console.WriteLine("The sumS is not present in the array.");
  827.  
  828.  
  829.  
  830. /*
  831. ОБЯСНЕНИЕ: Тук търсим в масив последователна поредица от числа, чиято сума да е равна на числото S. Правим си три променливи по подобие на 8-ма задача: startIndex, endIndex, CurrSum.
  832. С два for цикъла обхождаме масива събирайки отляво-надясно елементите му. В момента, в който открием елементи, чиято сума да удовлетворява if условието (а именно - временната CurrSum да бъде равна на sumS)
  833. влизаме в третия for цикъл, който ни отпечатва индексите (startIndex e нейното начало, а endIndex нейния край) на търсената поредица от числа. Ако не намерим такава поредица от елементи - изписваме, че в масива няма такава поредица.
  834. */
  835.  
  836. Problem 11. Binary search/////////////////////////////////////////////////////////////
  837.  
  838.  
  839. static int BinSearch(int[] array, int key)
  840.     {
  841.         Array.Sort(array);
  842.         int iMax = array.Length - 1;
  843.         int iMin = 0;
  844.         while (iMax >= iMin)
  845.         {
  846.             int iMidpoint = (iMin + iMax) / 2;
  847.             if (array[iMidpoint] < key)
  848.             {
  849.                 iMin = iMidpoint + 1;
  850.             }
  851.             else if (array[iMidpoint] > key)
  852.             {
  853.                 iMax = iMidpoint - 1;
  854.             }
  855.             else
  856.             {
  857.                 return iMidpoint;
  858.             }
  859.         }
  860.         return -1;
  861.     }
  862.  
  863.     static void Main()
  864.     {
  865.         int[] myArray = { 4, 7, 4, 6, 2, 7, 5, 12, 22, 13, };
  866.         int key = 7;
  867.         Console.WriteLine(BinSearch(myArray, key));
  868.     }
  869. }
  870.  
  871. //ОПИСАНИЕ: Задача имаща за цел да ни запознае с един от основните алгоритми в програмирането - Binary Search. Повече инфо за него тук - http://en.wikibooks.org/wiki/Algorithm_Implementation/Search/Binary_search
  872.  
  873.  
  874. Problem 12. Index of letters /////////////////////////////////////////////////////////////
  875.  
  876.             string kkk = Console.ReadLine();
  877.             string[] stringk = kkk.Split(' ');
  878.  
  879.             string restOfArray = string.Join("", stringk);
  880.  
  881.             // ETO TAKA OT STRING ARR to char arr
  882.             char[] alphabet = restOfArray.ToCharArray();
  883.  
  884.             for (int i = 0; i < alphabet.Length; i++)
  885.             {
  886.                 int ssh = 0;
  887.                 if (alphabet[i] > 'Z')
  888.                 {
  889.                     ssh = alphabet[i] - 96;
  890.                 }
  891.                 else
  892.                 {
  893.                     ssh = alphabet[i] - '@';
  894.                 }
  895.  
  896.                 int kur = alphabet[i];
  897.                 if (ssh > 0 && ssh <= 26)
  898.                 {
  899.                     Console.WriteLine("{0}-->{1}--{2}", kur, ssh, alphabet[i]);
  900.                 }
  901.             }
  902.  
  903.  
  904.  
  905. Problem 15. Prime numbers /////////////////////////////////////////////////
  906.  
  907. class PrintNumberUsingSieveOfEratosthenes
  908. {
  909.     static List<int> SieveLINQ(int upTo)
  910.     {
  911.         int index = 1;
  912.         List<int> result = Enumerable.Range(2, upTo - 2).ToList();
  913.  
  914.         while (index <= Math.Sqrt(upTo))
  915.         {
  916.             index = result.First(i => i > index);
  917.             result.RemoveAll(i => i != index && i % index == 0);
  918.         }
  919.         return result;
  920.     }
  921.     static void Sieve(int upTo)
  922.     {
  923.         bool[] notPrime = new bool[upTo];
  924.         notPrime[0] = notPrime[1] = true;
  925.         for (int i = 2; i < Math.Sqrt(notPrime.Length); i++)
  926.         {
  927.             if (!notPrime[i])
  928.             {
  929.                 for (int j = i * 2; j < notPrime.Length; j += i)
  930.                 {
  931.                     notPrime[j] = true;
  932.                 }
  933.             }
  934.         }
  935.         //Print(notPrime);
  936.     }
  937.     static void Print(bool[] arr)
  938.     {
  939.         for (int i = 0; i < arr.Length; i++)
  940.         {
  941.             if (arr[i] == false)
  942.             {
  943.                 Console.Write(i + " ");
  944.             }
  945.         }
  946.     }
  947.     static void Main()
  948.     {
  949.         DateTime first = DateTime.Now;
  950.         Sieve(10000000);
  951.         TimeSpan normalSieveTime = DateTime.Now - first;
  952.         DateTime second = DateTime.Now;
  953.         List<int> linqResult = SieveLINQ(10000000);
  954.         TimeSpan linqSieveTime = DateTime.Now - second;
  955.  
  956.         Console.WriteLine("Sieve with LINQ: {0}", linqSieveTime);
  957.         Console.WriteLine("Sieve with bool: {0}", normalSieveTime);
  958.     }
  959. }
  960.  
  961.  
  962.  
  963.  
  964.  
  965. ///////////////////////////////////////// 16     //////////////////////////////////////////////////////////
  966.  
  967.  
  968.  
  969. long S = long.Parse(Console.ReadLine());
  970.         int N = Int32.Parse(Console.ReadLine());
  971.  
  972.         long[] numbers = new long[N];
  973.         for (int i = 0; i < N; i++) numbers[i] = long.Parse(Console.ReadLine());
  974.  
  975.         Dictionary<long, int> sums = new Dictionary<long, int> { { 0, 1 } };
  976.         foreach (var currentElement in numbers)
  977.         {
  978.             Dictionary<long, int> copyOfSums = new Dictionary<long, int>(sums);
  979.             foreach (KeyValuePair<long, int> pair in copyOfSums)
  980.             {
  981.                 var currentSum = currentElement + pair.Key;
  982.                 if (!sums.ContainsKey(currentSum)) sums.Add(currentSum, pair.Value);
  983.                 else sums[currentSum] += pair.Value;
  984.             }
  985.         }
  986.         sums[0]--; //remove the empty subset
  987.         Console.WriteLine(sums.ContainsKey(S) ? sums[S] : 0);
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994.  
  995. 17 //////////////////////////////// 17 //////////////////////////////////////////////////////////////////////////
  996.  
  997. Console.WriteLine("Enter a size of array: ");
  998.         int size = int.Parse(Console.ReadLine());
  999.  
  1000.         Console.WriteLine("Enter a number of elements in subset: ");
  1001.         int elements = int.Parse(Console.ReadLine());
  1002.  
  1003.         if (size < elements)
  1004.         {
  1005.             Console.WriteLine("Number of elements must be smaller or equal than the array's length!");
  1006.             return;
  1007.         }
  1008.  
  1009.         Console.WriteLine("Enter a number for a sum that we are going to looking for: ");
  1010.         int sum = int.Parse(Console.ReadLine());
  1011.  
  1012.         int[] numbers = new int[size];
  1013.         Console.WriteLine("Enter {0} number(s) to array: ", size);
  1014.         for (int i = 0; i < numbers.Length; i++)
  1015.         {
  1016.             numbers[i] = int.Parse(Console.ReadLine());
  1017.         }
  1018.  
  1019.         PrintElementOfArray(numbers);
  1020.         FindAndPrintSubsetsWithMaxSum(numbers, elements, sum);
  1021.     }
  1022.  
  1023.     static void FindAndPrintSubsetsWithMaxSum(int[] numbers, int elements, int sum)
  1024.     {
  1025.         Console.Write("Subsets with {0} elements and sum {1}: ", elements, sum);
  1026.  
  1027.         int totalSubsets = (int)(Math.Pow(2, numbers.Length) - 1); // Total subsets = 2^n - 1
  1028.         bool isFoundSubset = false;
  1029.  
  1030.         for (int i = 1; i <= totalSubsets; i++)
  1031.         {
  1032.             if (ElementsInSubset(i) == elements)
  1033.             {
  1034.                 List<int> currentSubset = numbers.Where((t, j) => ((i >> j) & 1) == 1).ToList();
  1035.  
  1036.                 if (currentSubset.Sum() == sum)
  1037.                 {
  1038.                     isFoundSubset = true;
  1039.                     PrintSubsetWithGivenSum(currentSubset);
  1040.                 }
  1041.             }
  1042.         }
  1043.  
  1044.         if (!isFoundSubset) Console.WriteLine("There are no subsets with {0} elements and Sum {1}...", elements, sum);
  1045.     }
  1046.  
  1047.     static int ElementsInSubset(int currentNumber)
  1048.     {
  1049.         int elementsInSubset = 0;
  1050.         while (currentNumber != 0)
  1051.         {
  1052.             elementsInSubset += currentNumber & 1;
  1053.             currentNumber >>= 1;
  1054.         }
  1055.         return elementsInSubset;
  1056.     }
  1057.  
  1058.     static void PrintElementOfArray(int[] numbers)
  1059.     {
  1060.         Console.WriteLine("Array's elements: {0}", string.Join(", ", numbers));
  1061.     }
  1062.  
  1063.     static void PrintSubsetWithGivenSum(List<int> subset)
  1064.     {
  1065.         Console.WriteLine(string.Join(", ", subset));
  1066.     }
  1067.  
  1068.  
  1069.  
  1070. 18 ///////////////////////////////// 18 /////////////////////////////////////////////////////////////////////////
  1071.  
  1072.  
  1073. static List<int>[] allBestSubsets = new List<int>[40];
  1074.     static int index = 0;
  1075.  
  1076.     static void Main()
  1077.     {
  1078.         Console.WriteLine("Enter a number for the array's length: ");
  1079.         int n = int.Parse(Console.ReadLine());
  1080.  
  1081.         int[] numbers = new int[n];
  1082.         Console.WriteLine("Enter {0} number(s) to array: ", n);
  1083.         for (int i = 0; i < numbers.Length; i++)
  1084.         {
  1085.             numbers[i] = int.Parse(Console.ReadLine());
  1086.         }
  1087.  
  1088.         FindAllSubsetsWithGivenSum(numbers);
  1089.         PrintLongestSubsets(numbers);
  1090.     }
  1091.  
  1092.     static void PrintLongestSubsets(int[] numbers)
  1093.     {
  1094.         Console.WriteLine("Array's elements: {0}", string.Join(", ", numbers));
  1095.  
  1096.         Console.WriteLine("Longest subset(s) with increasing elements: ");
  1097.         for (int i = 0; i < index; i++) Console.WriteLine(string.Join(", ", allBestSubsets[i]));
  1098.     }
  1099.  
  1100.     // Find all subsets using BITWISE REPRESENTATION
  1101.     static void FindAllSubsetsWithGivenSum(int[] numbers)
  1102.     {
  1103.         List<int> subset = new List<int>();
  1104.         long bestLength = 0;
  1105.         long totalSubsets = (long)(Math.Pow(2, numbers.Length) - 1); // Number of subsets
  1106.  
  1107.         for (long i = totalSubsets; i >= 1; i--)
  1108.         {
  1109.             long elementInSubset = ElementsInSubset(i);
  1110.  
  1111.             if (elementInSubset < bestLength) continue;
  1112.  
  1113.             subset.Clear();
  1114.  
  1115.             subset.AddRange(numbers.Where((t, j) => ((i >> j) & 1) == 1));
  1116.  
  1117.             if (IsIncreasingElements(subset))
  1118.             {
  1119.                 if (bestLength < elementInSubset)
  1120.                 {
  1121.                     allBestSubsets = new List<int>[40];
  1122.                     index = 0;
  1123.                 }
  1124.                 bestLength = elementInSubset;
  1125.                 allBestSubsets[index++] = new List<int>(subset);
  1126.             }
  1127.         }
  1128.     }
  1129.  
  1130.     // Optimization method
  1131.     static long ElementsInSubset(long currentNumber)
  1132.     {
  1133.         long elementsInSubset = 0;
  1134.  
  1135.         while (currentNumber != 0)
  1136.         {
  1137.             elementsInSubset += currentNumber & 1;
  1138.             currentNumber >>= 1;
  1139.         }
  1140.         return elementsInSubset;
  1141.     }
  1142.  
  1143.     static bool IsIncreasingElements(List<int> numbers)
  1144.     {
  1145.         for (int i = 0; i < numbers.Count - 1; i++)
  1146.             if (numbers[i] > numbers[i + 1])
  1147.                 return false;
  1148.  
  1149.         return true;
  1150.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement