Advertisement
m1o2

Pattern, m1o2, fxp, elsf, C, gcd

Dec 21st, 2011
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.63 KB | None | 0 0
  1. void printArr( int arr[], int n ){
  2.  
  3.     int index;
  4.     for( index = 0; index < n; ++index )
  5.         printf("%d ", arr[ index ] );
  6.  
  7. }
  8.  
  9. int gcd( int a, int b ){
  10.  
  11.     while( 0 != b ){
  12.  
  13.         int temp = b;
  14.         b = a % b;
  15.         a = temp;
  16.     }
  17.  
  18.     return a;
  19. }
  20. int is_serial( int arr[], int n ){
  21.  
  22.     int digits[10] = {0};
  23.     int *pattern;
  24.     int index, current;
  25.     int length = 0, min = 0;
  26.     int gcdResult = 1, patternLength = 0;
  27.  
  28.     for( index = 0; index < n; ++index )        // O(n)
  29.         ++digits[ arr[ index ] ];
  30.  
  31.     for( index = 0; index < 10; ++index ){ //O(1)
  32.  
  33.         if( 0 < digits[ index ] ){
  34.  
  35.             if( min == 0 || digits[ index ] < min )
  36.                 min = digits[ index ];
  37.  
  38.             length += digits[ index ];
  39.         }
  40.     }
  41.    
  42.     gcdResult = gcd( length, min );
  43.  
  44.     if( 0 != (n % gcdResult ) )
  45.         return 0;
  46.  
  47.     patternLength = ( length/ gcdResult );
  48.     pattern = (int*)malloc( sizeof(int) * ( patternLength ) );
  49.     // check if malloc failed.
  50.  
  51.     for( index = 0; index < patternLength; ++index )
  52.         pattern[ index ] = arr[ index ];
  53.  
  54.     for( index = length, current = 0; index < n; ++index, current = ( ( current + 1 ) % patternLength ) ){
  55.  
  56.         if( arr[ index ] != pattern[ current ] ){
  57.  
  58.             free( pattern );
  59.             return 0;
  60.         }
  61.     }
  62.  
  63.     printf("\n\n the pattern appears %d times : ", length/patternLength);
  64.     printArr( pattern, patternLength );
  65.     free( pattern );
  66.     return 1;
  67. }
  68.  
  69.  
  70.  
  71. int main( int argc, char *argv[] ){
  72.  
  73. //  int arr[] = {1,2,3,1,1,3,1,1,2,3,1,1,3,1};
  74. //  int n = 14;
  75.  
  76.     int arr[] = {1,2,3,1,2,3,1,2,3};
  77.     int n = 9;
  78.  
  79.     int isSerial;
  80.     printf("Arr: " );
  81.     printArr( arr, n );
  82.  
  83.     isSerial = is_serial( arr, n );
  84.  
  85.     printf("\n\n is serial : %d ", isSerial );
  86.  
  87.     getch();
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement