user404 Posted April 1, 2016 Share Posted April 1, 2016 On to problem 2: Given n, write a random permutation of numbers from 1 to n. e.g. n=6 3 5 4 1 2 6 my solution: #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX 50 int main(void){ int n; int rand_matrix[MAX]; int permutation[MAX]; srand(time(NULL)); printf(" n (max %d) = ", MAX); scanf("%d", &n); int i; for(i=0; i<n; i++){ //puts n random numbers in matrix rand_matrix[i]=rand(); } int min_matrix=RAND_MAX; int min_i; int j=0; i=0; do{ if(rand_matrix[i]<=min_matrix){ //have I found a smaller number? min_matrix=rand_matrix[i]; min_i = i; } i++; if(i==n){ //one cycle through the matrix permutation[j++]=min_i+1; rand_matrix[min_i]=RAND_MAX; //prepare for next cycle i=0; min_matrix=RAND_MAX; } }while(j<=n && j<MAX); for(i=0; i<n; i++){ printf(" %d", permutation[i]); } printf("\n"); return 0; } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.