0

I need a function to find out the Kaprekar numbers inside this 2d array, I searched in web but none of the results worked for 2D array.

This is the array that I made:

int **matrix;
int row, column;
long s, k;

srand(time(NULL));
printf("Number of rows: ");
scanf("%d", &row);

printf("Number of column: ");
scanf("%d", &column);


matrix = (int **) calloc(row, sizeof(int*));


for(i = 0; i < row; i++)
    matrix[i] = (int *) calloc(column, sizeof(int));


for(s = 0; s < row; s++)
{
    for(k = 0; k < column; k++)
    {

        matrix[s][k]=(rand()%1000) * (rand()%1000);
    }
}

any help or suggestions to convert this code to be able to work for 2D array?

bool iskaprekar(int n) 
{ 
    if (n == 1) 
       return true; 


    int sq_n = n * n; 
    int count_digits = 0; 
    while (sq_n) 
    { 
        count_digits++; 
        sq_n /= 10; 
    } 

    sq_n = n*n;  


    for (int r_digits=1; r_digits<count_digits; r_digits++) 
    { 
         int eq_parts = pow(10, r_digits); 

         if (eq_parts == n) 
            continue; 


         int sum = sq_n/eq_parts + sq_n % eq_parts; 
         if (sum == n) 
           return true; 
    } 


    return false; 
} 
Tasneem Akkad
  • 37
  • 1
  • 9
  • OT: this is not a 2D array but an array of pointers. It can be used the same but it is not contiguous. And best practices recommend [not to cast malloc](https://stackoverflow.com/q/605845/3545273) in C. – Serge Ballesta May 27 '20 at 08:18

1 Answers1

1

You have 2D array, you have also the function that verifies the number is Kaprekar or not. The simple way is using the for loop to check all number in 2D array as you did when you initialize the values of array using rand() function.

for(s = 0; s < row; s++) {
   for(k = 0; k < column; k++) {
      if(iskaprekar(matrix[s][k])) {
          printf("%d ", matrix[s][k]);
      } 
   }
}

if you want to store all Kaprekar numbers, you can use pointer then reallocate for it after each time you meet one Kaprekar number. Then remove the duplicated numbers if you want.

int * numbers = 0;
if(!numbers) {return -1;}
int count = 0;
for(s = 0; s < row; s++) {
   for(k = 0; k < column; k++) {
      if(iskaprekar(matrix[s][k])) {
          numbers = realloc(numbers, sizeof(int) (count+1));
          if(!numbers) {return -1;}
          numbers[count] = matrix[s][k];
          count++;
      } 
   }
}

// Remove the duplicated numbers here, if you want
Hitokiri
  • 3,607
  • 1
  • 9
  • 29