Home > Blockchain >  How do you check if there is a unique element in a matrix in C
How do you check if there is a unique element in a matrix in C

Time:03-22

I need help in making a program to check whether there is a unique element in a matrix or none at all. First, the program asks for the number of the rows and columns. Then it asks for the elements of the matrix. If there is a unique element found in the matrix, then it prints "Unique element found." If there is no unique element, then it prints "No unique element."

int rows, cols;
 printf("Enter the number of rows: ");
 scanf("%d", &rows);
 printf("Enter the number of columns: ");
 scanf("%d", &cols);
 
 int matrix[rows][cols];
 for(int row = 0; row < rows; row  ){
     for(int col = 0; col < cols; col  ){
         scanf("%d", &matrix[row][col]);
     }
}

i appreciate the help, thank you very much.

CodePudding user response:

Even n-dimensional arrays are linear in memory. You may sort a linear array inplace and look for unique elements.

int compare_ints(const void* a, const void* b) {
  const int arg1 = *(const int*)a;
  const int arg2 = *(const int*)b;
 
  if (arg1 < arg2) return -1;
  if (arg1 > arg2) return 1;
  return 0;
 
  // return (arg1 > arg2) - (arg1 < arg2); // possible shortcut
  // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present)
}

// ... your Q code here

const size_t n = rows * cols;
int* arr = (int*)matrix;
qsort(arr, n, sizeof(int), compare_ints);
for (size_t i = 0; i < n - 1; i  ) {
  if (arr[i] == arr[i   1]) {
    puts("No unique element.");
    return;
  }
}
puts("Unique element found.");

CodePudding user response:

A straightforward approach is to interpret the matrix as a one-dimensional array

For example

int unique = 0;
size_t n = rows * cols;
int *a = ( int * ) matrix;

for ( size_t i = 0; !unique && i < n; i   )
{
    size_t j = 0;
    while ( j < i && a[j] != a[i] )   j;

    if ( j   == i )
    {
        while ( j != n && a[j] != a[i] )   j;

        unique = j == n;
    }
}  

if ( unique ) puts( "Unique element found." );
else puts( "No unique element." );

To get the row and the column of the unique element all you need is to declare the variable i outside the nested loops. For example

int *a = ( int * ) matrix;
int unique = 0;
size_t n = rows * cols;
size_t i = 0;

for ( ; !unique && i < n; i  = !unique )
{
    size_t j = 0;
    while ( j < i && a[j] != a[i] )   j;

    if ( j   == i )
    {
        while ( j != n && a[j] != a[i] )   j;

        unique = j == n;
    }
}  

if ( unique ) 
{
    size_t row = i / cols;
    size_t col = i % cols;
    printf( "Unique element found at %zu row and %zu column.\n", row, col );
}
else 
{
    puts( "No unique element." );
}
  • Related