Advertisement
Mr_kindle

distinctmatrix.c

Nov 13th, 2022 (edited)
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | None | 0 0
  1. /*WAP (write a program) which generate random values from 1 to 16 and put it in a matrix of 4*4.
  2. Obviously each element of this matrix should be distinct.*/
  3. /*this code generate a matrix of n*n with all its elements are distinct*/
  4. /*very interesting program it is used while making the number puzzle game*/
  5.  
  6. //youtube: https://youtu.be/fjExIt0YIRI
  7.  
  8. #include<stdio.h>
  9. #include<malloc.h>
  10. #include<time.h>
  11. int main()
  12. {   int n, *mat,row,col;
  13.     int i,j,flag,num;
  14.     srand(time(0));
  15.  
  16.     printf("Enter value of n for n*n matrix: ");
  17.     scanf("%d",&n);
  18.     mat = calloc(n*n, sizeof(int));
  19.     for(i=0;i<n*n;i++)
  20.         {   num = rand()%(n*n) + 1;
  21.             flag=0;
  22.             /*compare the newly generated number with all the previous elements of matrix*/
  23.             for(j=0;j<i;j++)
  24.                 {
  25.                     if(mat[j] == num)
  26.                         {
  27.                             flag++;
  28.                             break;
  29.                         }
  30.                 }
  31.             if(flag == 0)//it mean the generated number is unique
  32.                 {
  33.                     row = i/n;
  34.                     col = i%n;
  35.                     mat[row * n + col] = num;
  36.                 }
  37.                 /*if generated number is not unique then run the loop again*/
  38.             else i--;
  39.         }
  40.         /*Now its time to display the dynamically allocated matrix*/
  41.         for(i=0;i<n;i++)
  42.           {
  43.               for(j=0;j<n;j++)
  44.                 printf("%2d  ",mat[i*n + j]);
  45.                 printf("\n");
  46.         }
  47.    
  48.     free(mat);
  49.  
  50. return 0;
  51. }//main
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement