Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*WAP (write a program) which generate random values from 1 to 16 and put it in a matrix of 4*4.
- Obviously each element of this matrix should be distinct.*/
- /*this code generate a matrix of n*n with all its elements are distinct*/
- /*very interesting program it is used while making the number puzzle game*/
- //youtube: https://youtu.be/fjExIt0YIRI
- #include<stdio.h>
- #include<malloc.h>
- #include<time.h>
- int main()
- { int n, *mat,row,col;
- int i,j,flag,num;
- srand(time(0));
- printf("Enter value of n for n*n matrix: ");
- scanf("%d",&n);
- mat = calloc(n*n, sizeof(int));
- for(i=0;i<n*n;i++)
- { num = rand()%(n*n) + 1;
- flag=0;
- /*compare the newly generated number with all the previous elements of matrix*/
- for(j=0;j<i;j++)
- {
- if(mat[j] == num)
- {
- flag++;
- break;
- }
- }
- if(flag == 0)//it mean the generated number is unique
- {
- row = i/n;
- col = i%n;
- mat[row * n + col] = num;
- }
- /*if generated number is not unique then run the loop again*/
- else i--;
- }
- /*Now its time to display the dynamically allocated matrix*/
- for(i=0;i<n;i++)
- {
- for(j=0;j<n;j++)
- printf("%2d ",mat[i*n + j]);
- printf("\n");
- }
- free(mat);
- return 0;
- }//main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement