Tuesday, April 10, 2012

Program 9TH in C++

PROBLEM STATEMENT :


Give an array of integers, which are in repeated format except one integer, write a function to return that integer
example
[2,2,3,3,4,4,4,5,5] = 4
[2,2,2,3,3,3,3,4,4,4] = 3


SOLUTION:




#include <iostream.h>
#include <cstdio>


using namespace std;


void check(int str[],int size)
{
int i=0;
int count=1;
int count1=1;
//for counting the length of first string pattern


while(i < size)
{
if(str[i] == str[i+1])
{
count++;
i++;
}
else
{
break;
}
}
i++;


//for the length of second string pattern whose length is not equal to length of first string pattern


while(i < size-1)
{
if(str[i] == str[i+1])
{
count1++;
i++;
}
else
{
if(count1 == count)
{
count1=1;
i++;
}
else
{
break;
}
}
}
i++;


//if the common length is equal to first string length found then odd pattern's character is at i-1
if(i == size || str[i] == str[i+count-1])
{
cout<<"\n\nOutput is : "<<str[i-1];
}


//else the common length is equal to second pattern length and hence the odd pattern starts at index 0


else
{
cout<<"\n\nOutput is : "<<str[0];
}
}


int main()
{


int arr1[] = {1,1,2,2,2,2,3,3,4,4,5,5};
int arr2[] = {1,1,1,1,2,2,2,3,3,3,4,4,4};
int arr3[] = {1,1,2,2,3,3,4};


check(arr1,sizeof(arr1)/sizeof(int));
check(arr2,sizeof(arr2)/sizeof(int));
check(arr3,sizeof(arr3)/sizeof(int));


}


No comments:

Post a Comment