c - find and then delete the longest occurring sequence of 0 in an array -


my array has 0 n 1 . arr[]={00111000011} need find , delete longest sequence of 0 , count remaining elements in array.

int longestsequence(int[] arr, int size) {     int longest = 0;     int length = 1;     (int = 1; < size; i++)         if (arr[i] == arr[i - 1])         {             length++;         }         else         {             length = 1;         }     if (length > longest)     {         longest = length;     }     return longest;      int count = 0;     (int = 1; < size; i++)     {         if (arr[i] == 0)             count++;     }     if (count > longest)         longest = count; } 

if have understood correctly assignment function can following way shown in demonstrative program below. @ least can used base own function

#include <stdio.h> #include <string.h>  size_t longestsequence( int *a, size_t n ) {     int *longest_start = a, *longest_end = a;     int *start;     int found = 0;      int *current = a;     ( ; current != + n; ++current )     {         if ( *current == 0 && !found )          {             found = 1;             start = current;         }                     else if ( *current == 1 && found )         {             found = 0;             if ( longest_end - longest_start < current - start )             {                 longest_start = start;                 longest_end = current;             }         }     }      if ( found )     {         if ( longest_end - longest_start < current - start )         {             longest_start = start;             longest_end = current;         }     }     if ( longest_start != longest_end )    {                 memmove( longest_start, longest_end, ( + n - longest_end ) * sizeof( *a ) );    }              n -= longest_end - longest_start;      return n; }  int main( void )  {     int arr[] = { 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, };     size_t n = sizeof( arr ) / sizeof( *arr );      ( size_t = 0; < n; i++ ) printf( "%d ", arr[i] );     printf( "\n" );      n = longestsequence( arr, n );      ( size_t = 0; < n; i++ ) printf( "%d ", arr[i] );     printf( "\n" ); }     

the program output is

0 0 1 1 1 0 0 0 0 1 1  0 0 1 1 1 1 1  

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -