How to join two vectors in another that does not have repeated values?

Asked

Viewed 991 times

0

I need to make a program that reads the values of two vectors R and S, and store its values in a third vector called V. The detail is that it cannot contain any repeated element in the vector V.

I managed to get the program to show the vector V whole resulting from the union of R and S, but I still haven’t been able to figure out a way not to put repeat elements in V.

Follow the algorithm I made:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exercício6Testes
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] R = new int[10];
            int[] S = new int[10];
            int[] V = new int[20];


            Console.WriteLine("Este programa lê dois vetores e mostra a união dos dois sem valores repetidos");
            Console.WriteLine("Digite os 10 valores do vetor R: ");
            Console.WriteLine("\n");



            for (int i = 0; i < 10; i++)
            {

                Console.Write("Digite o valor de  R{0}: ", i + 1);   //LÊ O 1° VETOR
                R[i] = int.Parse(Console.ReadLine());

            }




            Console.Clear();
            Console.WriteLine("Agora digite os valores do vetor S: ");

            for (int j = 0; j < 10; j++)
            {
                Console.Write("Digite o valor de S{0}: ", j + 1); //LÊ O SEGUNDO VETOR
                S[j] = int.Parse(Console.ReadLine());


            }


            for (int k = 0; k < 10; k++)
            {
                V[k] = R[k];     //AQUI COLOCA TODOS OS VALORES DO VETOR R NAS
                                 //10 PRIMEIRAS POSIÇÕES DO VETOR V
            }



            int kw = 10;
            for (int L = 0; L < 10; L++)
            {
                V[kw] = S[L];  //AQUI COLOCA TODOS OS VALORES DO VETOR S NA
                kw++;          //SEGUNDA METADO DO VETOR V
            }



            Console.Clear();
            Console.WriteLine("União dos dois vetores: ");
            for(int mostra = 0; mostra < 20; mostra++)
            {
                Console.Write(V[mostra] + "\t");      //AQUI MOSTRA A UNIÃO DOS DOIS VETORES R e S DENTRO
                                                      //DO VETOR V.
                                                      //MOSTRA TUDO, ATÉ OS REPETIDOS!+......
            }




            Console.ReadKey();

        }
    }
}
  • 2

    Is this for educational purposes? Is it a job? I wonder why in C# there are much simpler ways to do what you want.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

2

There are several ways to do this and easier, but following the requested algorithm, making it smarter and simpler, without changing too much would be this:

using static System.Console;

namespace Exercício6Testes {
    public class Program {
        public static void Main() {
            int[] r = new int[10];
            int[] s = new int[10];
            int[] v = new int[20];
            WriteLine("Este programa lê dois vetores e mostra a união dos dois sem valores repetidos");
            WriteLine("Digite os 10 valores do vetor R:\n");
            var j = 0;
            for (var i = 0; i < 10; i++) {
                Write($"Digite o valor de  R{i + 1}: ");
                if (!int.TryParse(ReadLine(), out r[i])) {
                    i--;
                    continue;
                }
                if (!EhRepetido(v, r[i], j)) v[j++] = r[i];
            }
            WriteLine("Agora digite os valores do vetor S: ");
            for (var i = 0; i < 10; i++) {
                Write($"Digite o valor de S{i + 1}: ");
                if (!int.TryParse(ReadLine(), out s[i])) {
                    i--;
                    continue;
                }
                if (!EhRepetido(v, s[i], j)) v[j++] = s[i]; 
            }
            WriteLine("União dos dois vetores: ");
            for (int i = 0; i < j; i++) Write($"{v[i]}\t");
        }
        public static bool EhRepetido(int[] vetor, int item, int posicao) {
            for (int i = 0; i < posicao; i++) if (vetor[i] == item) return true;
            return false;
        }
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

I modernized the code. I don’t understand why people keep programming in C# as it was in 2002.

I did validation of the typing, the way I was if the person typed something wrong would break the application, you can put an error message there or do something else to make it clear that you need to type again. Countdown the counter because the countdown can only go forward with valid data, and does not perform anything else below.

I made a routine to identify the repeated (not the best performance, but it’s how I was doing). In addition to being easier to avoid using flags, avoids repetition. Actually even data entry could avoid repetition. And I have already checked straight into data entry which is easier and faster.

In the algorithm posted did nothing filter. To filter repeated have to scan the whole array up to the current position to see if it has repeated, if it has terminates the search, and only if none is repeated is guaranteed not to be repeated.

Finally, I only print the quantity of items that is valid in V. How do you not use R and S for nothing, nor should have created these variables.

  • Thank you jhow!+.......

  • @davidgomezsouza see in [tour] the best way to say thank you (accepting the answer) and do this in everything you have ever asked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.