It is necessary to count the number of columns in which all the numbers are different.
For example:
import java.util.Random;
import java.util.Scanner;
public class Practica {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = sc.nextInt();
System.out.print("Enter the number of columns: ");
int columns = sc.nextInt();
Random rnd = new Random();
int[][] mas = new int[rows][columns];
System.out.println("\nMatrix:");
for (int i = 0; i < mas.length; i++) {
for (int j = 0; j < mas.length; j++) {
mas[i][j] = rnd.nextInt(50) + 1;
System.out.print(mas[i][j] + "\t");
}
System.out.println("");
}
int count = 0;
boolean sinRep = true;
String nCol = "";
for (int j = 0; j < mas.length; j++) {
nCol = "";
sinRep = true;
for (int i = 0; (i < mas.length) && (sinRep == true); i++) {
if (nCol.contains(Integer.toString(mas[i][j]))) {
sinRep = false;
}
nCol += mas[i][j] + "/";
}
if (sinRep == true) {
count++;
}
}
System.out.println("Quantity of columns with diferents numbers: " + count);
}
}
Output:
Enter the number of rows: 5
Enter the number of columns: 5
Matrix:
38 4 37 39 38
50 49 15 43 37
38 22 14 12 38
19 50 24 32 49
42 43 39 23 22
In this case the columns 2,3,4 would be counted, the answer would be 3 columns.
Defines two variables (for example: int cont=0; boolean found;).
An idea that occurs to me is that you have a boolean variable that defaults to
true
. That is, you assume that there are no repeated values in the column. So if a duplicate value is found, let it exit the loop and move on to checking the next column.Then I would do the loops in reverse, to check for every column every row.
Finally, I would make a counter to store the number of columns in which there is no repeated value and I would add
String
the numbers that have already been output for that column to a counter. Once this is done, it would check with the functioncontains
to see if the new number that we are going to compare is already in the string.I have put a separator between number and number (
/
) insideString
so that the numbers do not overlap.Translated to code it would be: