Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void printArr( int arr[], int n ){
- int index;
- for( index = 0; index < n; ++index )
- printf("%d ", arr[ index ] );
- }
- int gcd( int a, int b ){
- while( 0 != b ){
- int temp = b;
- b = a % b;
- a = temp;
- }
- return a;
- }
- int is_serial( int arr[], int n ){
- int digits[10] = {0};
- int *pattern;
- int index, current;
- int length = 0, min = 0;
- int gcdResult = 1, patternLength = 0;
- for( index = 0; index < n; ++index ) // O(n)
- ++digits[ arr[ index ] ];
- for( index = 0; index < 10; ++index ){ //O(1)
- if( 0 < digits[ index ] ){
- if( min == 0 || digits[ index ] < min )
- min = digits[ index ];
- length += digits[ index ];
- }
- }
- gcdResult = gcd( length, min );
- if( 0 != (n % gcdResult ) )
- return 0;
- patternLength = ( length/ gcdResult );
- pattern = (int*)malloc( sizeof(int) * ( patternLength ) );
- // check if malloc failed.
- for( index = 0; index < patternLength; ++index )
- pattern[ index ] = arr[ index ];
- for( index = length, current = 0; index < n; ++index, current = ( ( current + 1 ) % patternLength ) ){
- if( arr[ index ] != pattern[ current ] ){
- free( pattern );
- return 0;
- }
- }
- printf("\n\n the pattern appears %d times : ", length/patternLength);
- printArr( pattern, patternLength );
- free( pattern );
- return 1;
- }
- int main( int argc, char *argv[] ){
- // int arr[] = {1,2,3,1,1,3,1,1,2,3,1,1,3,1};
- // int n = 14;
- int arr[] = {1,2,3,1,2,3,1,2,3};
- int n = 9;
- int isSerial;
- printf("Arr: " );
- printArr( arr, n );
- isSerial = is_serial( arr, n );
- printf("\n\n is serial : %d ", isSerial );
- getch();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement