In: Computer Science
C++
CODE:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
//function given an int array and size int
bool isThreeCommon(int a[],int n){
//same is the output boolean
bool same = false;
//traversing the array
for(int i=0;i<n-2;i++){
//checking for 3 numbers after each index
for(int j=i;j<i+3;j++){
//if any of the three in a row is not same the loop breaks
if(a[i] != a[j])
break;
//if it didn't break it returns true
if(j == i+2)
same = true;
}
if(same)
return same;
}
//otherwise returns false
return same;
}
//function given an int array and size int
bool isThreeInFileCommon(string filename){
fstream file;
file.open(filename.c_str(),ios::in);
string line;
string *a = new string[100];
int num = 0;
//getting the lines from a file and storing in an array
while(getline(file,line)){
a[num] = line;
num += 1;
}
//same is the output boolean
bool same = false;
//traversing the array
for(int i=0;i<num-2;i++){
//checking for 3 lines after each index
for(int j=i;j<i+3;j++){
//if any of the three in a row is not same the loop breaks
if(a[i] != a[j])
break;
//if it didn't break it returns true
if(j == i+2)
same = true;
}
if(same)
return same;
}
//otherwise returns false
return same;
}
//function given an int array and size int
bool isTwoCommon(string s){
//same is the output boolean
bool same = false;
s = s + " ";
//an array of all the words in the string
string *a = new string[s.length()];
int lastSpace = 0,words = 0;
for(int i = 0;i<s.length();i++){
if(s.at(i) == ' '){
a[words] = s.substr(lastSpace,i-lastSpace);
words += 1;
lastSpace = i+1;
}
}
//traversing the array
for(int i=0;i<words-1;i++){
//checking for 3 numbers after each index
for(int j=i;j<i+2;j++){
//if any of the two in a row is not same the loop breaks
if(a[i] != a[j])
break;
//if it didn't break it returns true
if(j == i+1)
same = true;
}
if(same)
return same;
}
//otherwise returns false
return same;
}
int main(){
//array of int
int nums[] = {1,12,12,1,1,0,1,5,6,6};
//a line
string line = "All I to say is hello hello";
//calling all the three functions
cout<<"Three consecutive integers are same in the array:
"<<isThreeCommon(nums,10)<<endl;
cout<<"Three consecutive lines are same in the file:
"<<isThreeInFileCommon("input.txt")<<endl;
cout<<"Two consecutive words are same in a line:
"<<isTwoCommon(line)<<endl;
return 0;
}
________________________________________
CODE IMAGES:
input.txt:
Hello
this
file
file
file
contains
three
lines
same
same
_________________________________________
OUTPUT:
__________________________________________
Feel free to ask any questions in the comments section
Thank You!