1
"Write a method frequency which receives data from a matrix A that has integers between 0 and x; generates a vector with the occurrences of each integer between 0 and x. Write a method greater that takes an integer vector and returns the largest element of the vector. Write the main module, which fills a matrix only with values between 0 and x and displays which value was the most frequent (call the methods obligatory frequency, greater and leMatriz). "
I’ve already set up the matrix by drawing the numbers, now I’m trying to create the method frequency. I have two doubts:
1) How do I get the algorithm to "jump" the count of numbers that have already been counted? For example, if the matrix is: (0 0 1); (2 3 0); (1 2 3), the program will count 0 three times, then when it passes to the next, it will count 0 three times again.
2) How to declare the vector that will store the counted frequencies without knowing their size? I thought about creating a string and then converting it to an integer vector, but repeating the frequency count would still be a problem. I also thought of leaving the elements of the matrix in ascending order to find the highest value. With this I would know the size of the vector that stores the frequencies. But I’m not able to sort using Arrays.Sort()...
public class Freq_Maior {
static Scanner ent = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Digite o número de linhas e colunas da matriz: ");
int m = ent.nextInt();
int n = ent.nextInt();
System.out.print("Digite o valor máximo do intervalo usado para preencher a matriz: ");
int x = ent.nextInt();
int [][] A = new int[m][n];
leMatrizR(A, x);
}
// método para ler a matriz
public static void leMatrizR(int matriz[][], int a) {
Random rnd = new Random();
for (int i=0; i<matriz.length; i++) {
for (int j=0; j<matriz[0].length; j++) {
matriz[i][j] = rnd.nextInt(a+1);
}
}
}
public static void Freq(int matriz[][]) {
????
}
}
But how do I compare the elements already counted with what I’m counting on at the moment? The program is also printing the vector values, but I didn’t have it printed... strange.
– Cristiane Dos Santos Costa
The first
for
varies the variablee
for all possible element values, ensuring that we check all of them. Then, in theif ( matriz[i][j] == e )
, We check if the current element of the matrix is what we are counting. Only in case it is the element being contact, we increment the respective position of this element in the frequency vector. I would like to point out that the algorithm I have implemented is inefficient, and it is possible to reimplement it by performing only one passage in the entire matrix.– Vinícius Gobbo A. de Oliveira
Thanks for your help! I found another way to do it based on your suggestion.
– Cristiane Dos Santos Costa