I have an algorithm where I fill a 10 x 10 matrix. I want that at the moment of printing the matrix, no number is repeated.
This is my code:
int posi = 0, posj = 0, mayor = 0;//declaracion de variables para la posicion y el numero mayor
Console.WriteLine("Matriz de 10*10\n");
int[,] matriz = new int[10, 10]; //Creacion de la matriz de 10*10 (10filas, 10 columnas)
Random aleatorio = new Random();//declaracion del random para llenar la matriz
//se recorre la matriz para asignar los valores
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
{
matriz[i,j]=aleatorio.Next(0, 100);
//matriz[i, j] = aleatorio.Next(0, 100);
}
// se recorre nuevamente para leer sus valores y validar cual es mayor y capturar su respectiva posicion
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (matriz[i, j] > mayor)//si matriz en la posicion i,j es > mayor
{
mayor = matriz[i, j]; // a mayor -> el valor que hay en la posicion i, j
posi = i; // a la posicion i -> i
posj = j;// a la posicion j -> j
}
//imprimir matriz
Console.Write(matriz[i, j].ToString() + " ");
}
Console.WriteLine();
}
//impresion del numero mayor y su posicion.
Console.WriteLine("El numero mayor es:{0} y esta en la posicion {1},{2}", mayor.ToString(), posi.ToString(), posj.ToString());
Console.ReadLine();
Console.ReadLine();
}
}
}
A very efficient way to avoid duplicates is to generate a
HashSet
first (which already takes care of duplicates) and then fill your array with the values taken from there.Then you can use
Buffer.BlockCopy
to give it the shape of an array.and finally you can search the maximum as you are already doing
If you are going to fill a matrix with values from 0 to 99 you can do it like this (I have done it in a 5x5). You only do the loop to fill the array.
If you know what values you are going to enter, to get the index of the maximum value with an if when you "get" the value from the list you already have it.