Jump to content

user404 - challenge #2


user404
 Share

Recommended Posts

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;
}
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...