avoid repeated number in an array in c #?

4

I am trying to create a small program in C# that requests 7 number and validates and avoids the repetition of an array number (whole),

this is my code:

/*

24. Arreglos 2. Un programa que lea 7 valores enteros diferentes y
los introduzca a un arreglo. (El programa debe validar que no se introduzca un número repetido). 

*/
using System;

public class Program
{
    public static void Main()
    {
           int[] arreglo = new int[7]; //creo el array
               int num;

           //Capturar arreglo 
            for (int i = 0; i < 7; i++) { 
                Console.Write ("Ingresa numero "); 

               string valor = Console.ReadLine();

               num = Convert.ToInt32(valor);

                if(num== arreglo[num]){
                 arreglo[num] = Convert.ToInt32 (Console.ReadLine()); 
                }else{

                    Console.Write("es un numero repetido");
                }
            }}}// 

Does anyone have any idea what my mistake is?

    
asked by Gilberto 25.01.2018 в 04:47
source

2 answers

7

Another option that you have, since you want a collection of elements that do not repeat themselves, is to use a collection that specifically does not allow duplicates. In .Net we have HashSet<T> .

  

Class HashSet<T> provides high performance set operations. A set is a collection that contains no duplicate elements and whose elements are in no particular order.

The method Add of this collection returns a Boolean value that indicates whether the value was added or not. Using this HashSet , your code could be something similar to the following:

var hash = new HashSet<int>();
int num;
while (hash.Count<7)
{
    Console.Write("Ingresa numero ");
    string valor = Console.ReadLine();
    num = Convert.ToInt32(valor);
    if (!hash.Add(num))
    {
        Console.WriteLine("es un numero repetido");
    }
}

Edit: I see that it is probably a school work and that surely you must use arrays obligatorily. But I will leave my answer in case it can serve some other user,

    
answered by 25.01.2018 в 09:53
6

The for code is correct the idea of iterating 7 times to request 7 different numbers, but then you have very specific errors.

1.- if(num== arreglo[num]) is asking if the number entered is equal to the position num which is incorrect, because if we enter the number 13 for example, we will be accessing position 13 of the array, but this only has 7 , which would give a IndexOutRangeException .

2.- arreglo[num] = Convert.ToInt32 (Console.ReadLine()); the same thing happens, but now try to store the value of the entry in the position of the number entered which would give the previous exception.

The following steps could theoretically be carried out.

-Request the number and then iterate the elements to know if it is or is not

int[] arreglo = new int[7]; //creo el array
int num;
// Variable Bandera
bool seEncuentra = false;
//Capturar arreglo 
for (int i = 0; i < 7;)
{
    //Inicializamos en noSeEncuentra
    seEncuentra = false;
    Console.Write("Ingresa numero ");
    //Obtenemos el número
    num = Convert.ToInt32(Console.ReadLine());

    //Iteramos sobre el array para verificar que no se encuentre
    for(int j=0;j<arreglo.Length && !seEncuentra; j++)
    {
        // si es igual , se encuentra cambiamos la bandera
        if (arreglo[j] == num) seEncuentra = true;
    }
    //si se encuentra
    if (seEncuentra)
    {
        //regresamos y mostramos el mensaje respectivo
        Console.Write("Número Ingresado ya existe ");
    }
    else
    {
        //caso contrario añadimos el valor al array
        // e incrementamos el numero de eementos ingresados
        // i++ .
        arreglo[i] = num;
        i++;
    }
}

Of course, this for can be simplified and use contains to verify if the element exists in the array.

int[] arreglo = new int[7]; //creo el array
int num;
//Capturar arreglo sin incrementar el i ,
// seincrementará cuando encuentre un número no repetido
for (int i = 0; i < 7; )
{
    Console.Write("Ingresa numero ");

    num = Convert.ToInt32(Console.ReadLine());

    // Verificamos si existe en el array
    if (!arreglo.Contains(num))
    {
        arreglo[i] = num;
        i++;
    }
    else
    {
        Console.Write("Es un numero repetido");
    }
}
    
answered by 25.01.2018 в 06:09