I have a programming problem where I should make a program which will calculate the amount of pairs of letters (letters next to each other) which aren't 'a', 'e', 'i', 'o', 'u' (vowels).
Examples:
- jas 0
- olovo 0
- skok 1 (sk)
- stvarnost 4 (st, tv, rn, st)
Input consists of small letters which make a word not bigger than 200 characters, and the output should output the number of pairs of letters that aren't vowels (a, e, i, o, u).
Time limit:
- 1 sec
Memory limit:
- 64 MB
Examples provided in the problem I have been given:
- Input skok
- Output 1
However, when I enter the words 'skok' the program doesn't work (it seems to keep working in the background yet not displaying anything on screen). The word 'stvarnost' (reality) works however, displaying '4' - as given in the problem.
Out of 10 test-cases, two test-cases give me the right output, one gives me a wrong output, and seven other test-cases tell me I have exceeded my time-limit.
Now, I'd also like an advice on how I can avoid exceeding my given time-limit, and how to fix it in the program below.
Here's the code I've started:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char zbor[200];
cin.get(zbor, 200);
int length = strlen(zbor);
int j_value = 0;
int check_pairs = 0;
int pairs = 0;
int non_vowels = 0;
for (int i = 0; i < length; i++) {
if (zbor[i] == 'a' || zbor[i] == 'e' || zbor[i] == 'i' || zbor[i] == 'o' || zbor[i] == 'u') {
continue;
} else {
non_vowels++;
for (int j = i + 1; j < length; j++) {
if (zbor[j] == 'a' || zbor[j] == 'e' || zbor[j] == 'i' || zbor[j] == 'o' || zbor[j] == 'u') {
break;
} else {
non_vowels++;
if (non_vowels % 2 != 0) {
check_pairs = non_vowels / 2 + 1;
} else {
check_pairs = non_vowels / 2;
}
if (pairs < check_pairs) {
pairs++;
}
j_value = j;
}
}
i = j_value + 1;
}
}
cout << pairs;
return 0;
}
Edit:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char zbor[200];
cin.get(zbor, 200);
int length = strlen(zbor);
int pairs = 0;
int non_vowels = 0;
for (int i = 0; i < length; i++) {
if (zbor[i] == 'a' || zbor[i] == 'e' || zbor[i] == 'i' || zbor[i] == 'o' || zbor[i] == 'u') {
non_vowels = 0;
continue;
} else {
non_vowels++;
if (non_vowels >= 2) {
if (non_vowels % 2 != 0) {
pairs = non_vowels / 2 + 1;
} else if (non_vowels % 2 == 0) {
pairs = non_vowels / 2;
}
}
}
}
cout << pairs;
return 0;
}
Edited the code, using pieces of code of the answers below, (bruno's and Ozzy's) here's the final version which works:
#include <iostream>
#include <string.h>
using namespace std;
bool vowel(char c) {
switch(c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
default:
return false;
}
}
int main()
{
char zbor[200];
cin.get(zbor, 200);
int N = strlen(zbor);
int non_vowels = 0;
int pairs = 0;
for (int i = 0; i < N; i++) {
if (!vowel(zbor[i])) {
non_vowels = 0;
} else {
non_vowels++;
if (!vowel(zbor[i])) {
non_vowels = 0;
} else {
non_vowels++;
if (non_vowels > 1) {
pairs++;
}
}
}
}
cout << pairs;
return 0;
}