BorislavBorisov

Task.Intersection and union

Oct 27th, 2015
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.83 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. class IntersectionAndUnion
  4. {
  5.     static void Main()
  6.     {
  7.         int[] firstArray = {1,2,3};
  8.         Console.Write("First array: ");
  9.         PrintArray(firstArray);
  10.         Console.Write("Second array: ");
  11.         int[] secondArray = { 23, 34, 45, 3};
  12.         PrintArray(secondArray);
  13.  
  14.         int[] union = CreateUnion(firstArray, secondArray);
  15.         Console.WriteLine("Without repeate numbers: ");
  16.         PrintArray(union);
  17.         Console.WriteLine("Numbers occur in both arrays:");
  18.         CreateIntersetion(firstArray, secondArray);//направо ги принтя в метода
  19.     }
  20.  
  21.     static void CreateIntersetion(int[] firstArray, int[] secondArray)
  22.     {
  23.         Console.Write("{");
  24.         foreach (int element in firstArray)
  25.         {
  26.             if(Array.IndexOf(secondArray, element) >= 0)
  27.             {
  28.                 Console.Write(element + " ");
  29.             }
  30.         }
  31.         Console.Write("}");
  32.         Console.WriteLine();
  33.     }
  34.  
  35.     static int[] CreateUnion(int[] firstArray, int[] secondArray)
  36.     {
  37.         List<int> union = new List<int>();
  38.         union.AddRange(firstArray);
  39.  
  40.         foreach (int element in secondArray)
  41.         {
  42.             //if (Array.IndexOf(firstArray, element) == -1)//Може и така да се направи
  43.             //{
  44.             //    union.Add(element);
  45.             //}
  46.             if (!union.Contains(element))
  47.             {
  48.                 union.Add(element);
  49.             }
  50.         }
  51.         return union.ToArray();
  52.     }
  53.  
  54.     private static void PrintArray(int[] firstArray)
  55.     {
  56.         Console.Write("{");
  57.  
  58.         foreach (int elements in firstArray)
  59.         {
  60.             Console.Write(elements + " ");
  61.         }
  62.         Console.Write("}");
  63.  
  64.         Console.WriteLine();
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment