Jump to content

user404

Active Members
  • Posts

    6
  • Joined

  • Last visited

Posts posted by user404

  1. problem 3:

    find out from how many not falling sequences is the matrix made of

    e.g.

    4 32 5 1 2 6 7

    answer 3

    solution:


    #include <stdio.h>
    
    int main(void){
      int matrix[]={3,3,5,6,3,25,6,3,6,7,8,6}; //answer should be 5
      int counter=1;
    
      int i;
      for(i=1; i<sizeof(matrix)/sizeof(matrix[0]); i++){
        if(matrix[i-1]>matrix[i])
          counter++;
      }
    
      printf(" %d sequences\n", counter);
    
      return 0;
    }

    ~
    ~
    ~
    ~

  2. 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;
    }
  3. Hello!

    I'm learning C, so I'll be posting the problems I'm solving here, join in if you want and post your solutions in your favorite language. :smile:

    Challenge 1:

    Write a program that reads numbers, until it reads 0, and then outputs them in reverse order.

    Solution:

    #include <stdio.h>
    
    #define MAX 100
    
    int main(void){
      int matrix[MAX];
      int num, i=0;
    
      printf(" Input at most %d integers, stop with 0\n", MAX);
      do{
        printf(" number[%d] = ", i); scanf("%d", &num);
        if(num==0) break;
        matrix[i]=num;
        i++;
      } while( i< MAX );
    
      while(i--) printf(" %d", matrix[i]);
    
      printf("\n");
    
      return 0;
    }
    
×
×
  • Create New...