As you can tell, the elements that have a vector A and that does not have a vector B and vice versa

0

I have two vectors and would like to print the elements that do not have a vector A but not those that are repeated in the Vector B .

This I have so far

static void interseccion_A_entre_B(int[] vectora, int[] vectorb)
    {
        for(int c = 0; c < vectora.Length; c++)
        {
            for(int c2 = 0; c2 < vectorb.Length; c2++)
            {
                if (vectora[c] != vectorb[c2])
                {
                    Console.Write(vectora[c]);
                }
            }
        }
        Console.ReadKey();
    
asked by Duvca 16.03.2018 в 21:14
source

1 answer

0

Make it easier, with Linq you can get it on a line with Except :

static void Main(string[] args)
        {
            int[] v1 = { 2, 3, 1, 3, 8, 9 };
            int[] v2 = { 4, 2, 1, 6 };
            var items = v1.Except(v2);

            foreach (int item in items)
            {
                Console.Write(String.Format("{0},", item));
            }
            Console.ReadLine();
        }

The result will be 3, 8, 9 (elements of v1 that are not in v2)

More info: link

I add more information with your question. Except returns an IEnumerable. With a simple ToArray() you would already have a new array with the difference:

int[] items = v1.Except(v2).ToArray();

And if you want to toggle between v1 and v2, pass them as parameters to your function:

static void Main(string[] args)
        {
            int[] v1 = { 2, 3, 1, 3, 8, 9 };
            int[] v2 = { 4, 2, 1, 6 };

            int[] items1 = interseccion_A_entre_B(v1, v2);
            int[] items2 = interseccion_A_entre_B(v2, v1);

            Console.WriteLine("Elementos en v1 que no están en v2");
            foreach (int item in items1)
            {
                Console.Write(String.Format("{0},", item));
            }
            Console.WriteLine();
            Console.WriteLine("Elementos en v2 que no están en v1");
            foreach (int item in items2)
            {
                Console.Write(String.Format("{0},", item));
            }
            Console.ReadLine();
        }

        static int[] interseccion_A_entre_B(int[] vectora, int[] vectorb)
        {
            return vectora.Except(vectorb).ToArray();
        }

Result:

Elements in v1 that are not in v2 3,8,9, Elements in v2 that are not in v1 4.6,

If you want to go deeper, I recommend the msdn documentation on operations with arrays: link

There you will see methods to copy (Copy, CopyTo) and many other features.

And Linq's: link

Think that there are many ways already implemented that greatly facilitate the handling of data sets.

    
answered by 16.03.2018 / 21:46
source