This is for homework! But I need help anyway. The assignment is to input a sentence then output the number of words, and the number of occurrences of each letter. The output must have the letters in alphabetical order. So far, I've been able to count the number of words and get all the letters to lower case so that I'll be able to keep count of them. My question is how to actually keep count of the letters.
Example of output:
I say Hi.
3 words
1 a
1 h
2 i
1 s
1 y
Here's the code that I have so far:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
int letters[26];
char letter;
int word = 0;
cout << "Please enter a sentence: "<< endl;
do
{
cin.get(letter);
if(isspace(letter))
word++;
letter = tolower(letter);
cout << letter;
}
while (letter != '\n');
cout << "The number of words = " << word << endl;
return 0;
}
Should I input directly into a C-string? or will that mess up the word count?
If you're allowed to use STL, use std::map for mapping letters to counters. It will additionally sort the letters.
Otherwise, treat chars as indexes in an array of counters and increment them.
My question is how to actually keep
count of the letters
It's fairly straight forward. Simply create an array of 26 integers, (one for each letter), and initialize it to zero.
int letters[26] = { 0 }; // Initialize array to zero
Each value in the array corresponds to a count of a particular letter. Array index 0 refers to 'a', array index 1 refers to 'b', and so on. Then, everytime you encounter a letter, increment the appropriate value in the array. You can use the character 'a' (ASCII value 97) as a starting offset. So, given the variable char letter; you would do:
++letters[tolower(letter) - 'a'];
But always make sure that before you increment the appropriate value in the array, you check that isalpha(letter) && islower(letter) to make sure that your letter is in the range of lowercase a-z; otherwise you will access an index beyond the bounds of the array. You can also test for this condition by saying if (letter >= 'a' && letter <= 'z').
Hint: tolower(letter)-'a' is:
0 if letter is a
1 if letter is b
...
Hm, just few points to make your home task more useful to you (and your code more correct):
Think what happens if you have file with several spaces in a row (word counting).
Think how to be more correct with 'letters' (check for isalpha() at least). Also isalpha() could be key for simpler counting with fixed array [256] (this might be even the best solution as for performance vs std::map usage, check std::map documentation anyway).
Think about more effective file input. At least line at once.
Related
This question already has an answer here:
C++ string and string literal comparison
(1 answer)
Closed 1 year ago.
Question - The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word s from Berlandish into Birlandish as t. Help him: find out if he translated the word correctly.
Input -
The first line contains word s, the second line contains word t. The words consist of lowercase Latin letters. The input data do not consist unnecessary spaces. The words are not empty and their lengths do not exceed 100 symbols.
Output -
If the word t is a word s, written reversely, print YES, otherwise print NO.
When I write this code, the output is wrong -
int main(){
char s[100000],a[100000];
cin >> s >> a;
strrev(s);
if(s==a){
cout << "YES";
}else{cout << "NO";}
}
But when I write this code, the output is correct -
int main(){
char s[100000];
string a;
cin >> s >> a;
strrev(s);
if(s==a){
cout << "YES";
}else{cout << "NO";}
}
Why is it like this, is there a rule that a character array cannot be compared to another character array and if so, how can it be compared to a string?
Remember that arrays naturally decay to pointers to their first elements, and it's such pointers that you are comparing.
In short, what you're really doing is:
if(&s[0] == &a[0])
And those two pointers will never be equal.
To compare the contents of character arrays, you need to use strcmp() or similar function instead, eg:
if(strcmp(s, a) == 0)
Since you're programming in C++, please use std::string for all your strings. There are overloads for the == operator that do the right thing if you have std::string values.
hello i am a beginner in programming and am in the array lessons ,i just know very basics like if conditions and loops and data types , and when i try to solve this problem.
Problem Description
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.
Input Specification
The first line contains a single integer n (1⩽n⩽105) — the length of the string. The second line contains a string consisting of English lowercase letters: 'z', 'e', 'r', 'o' and 'n'.
It is guaranteed that it is possible to rearrange the letters in such a way that they form a sequence of words, each being either "zero" which corresponds to the digit 00 or "one" which corresponds to the digit 11.
Output Specification
Print the maximum possible number in binary notation. Print binary digits separated by a space. The leading zeroes are allowed.
Sample input:
4
ezor
Output:
0
Sample Input:
10
nznooeeoer
Output:
1 1 0
i got Time limit exceeded on test 10 code forces and that is my code
#include <iostream>
using namespace std;
int main()
{
int n;
char arr[10000];
cin >> n;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
for (int i = 0; i < n; i++) {
if (arr[i] == 'n') {
cout << "1"
<< " ";
}
}
for (int i = 0; i < n; i++) {
if (arr[i] == 'z') {
cout << "0"
<< " ";
}
}
}
Your problem is a buffer overrun. You put an awful 10K array on the stack, but the problem description says you can have up to 100K characters.
After your array fills up, you start overwriting the stack, including the variable n. This makes you try to read too many characters. When your program gets to the end of the input, it waits forever for more.
Instead of putting an even more awful 100K array on the stack, just count the number of z's and n's as you're reading the input, and don't bother storing the string at all.
According to the compromise (applicable to homework and challenge questions) described here
How do I ask and answer homework questions?
I will hint, without giving a code solution.
In order to fix TLEs you need to be more efficient.
In this case I'd start by getting rid of one of the three loops and of all of the array accesses.
You only need to count two things during input and one output loop.
I'm a newbie programmer who has been working on a ROT13 implementation as part of a tutorial and came across the following code. It outputs the correct characters however I'm not quite sure how it works and there is no explanation attached.
char rot13[] = { 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z','A','B','C','D','E','F','G','H','I','J','K','L','M' };
std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < alphabet.length(); i++) {
std::cout << rot13[alphabet[i] - 'A'];
}
Specifically, I dont quite understand how minusing the 'A' from a character within the string alphabet provides us with our ROT13 number. I initially thought that 'A' corresponded to an index within rot13[] and minusing that would provide us with a new index, however wouldn't that indicate that any numbers beneath A's index (Z,Y,X...) would become negative indexes as a result and throw errors.
Is anyone able to explain the logic behind this code to me?
Granted that alphabet[i] is an uppercase letter (which is the case in your example), alphabet[i] - 'A' will compute the distance to the letter 'A' in the ASCII table. So 'A'-'A' will be 0, 'B'-'A' will be 1 and so on, up to 'Z'-'A' which is 25.
Your character array rot13 is written so that the index 0 has the letter 'N', the index 1 is the letter 'O' and so on up to index 12 with the letter 'Z' and then index 13 is 'A', index 14 is 'B' and so on up to index 25 which is 'M'
To make things clearer, let’s rewrite this line:
std::cout << rot13[alphabet[i] - 'A'];
As:
char letterBeforeRot13 = alphabet[i];
int index = letterBeforeRot13 - 'A';
char letterAfterRot13 = rot13[index];
std::cout << letterAfterRot13;
This is pretty much what your compiler does, but with more details.
If we pick an example where alphabet[i] equals to the letter 'A', letterBeforeRot13 is assigned to the letter 'A', index is assigned to 'A'-'A' which is 0, letterAfterRot13 is assigned to the element of the array rot13 at index 0, which is 'N'. So the letter 'A' is transformed into 'N'.
You can do the same for any letter and you will see that everything is fine, including the edge cases when you thought that things would be out of bounds. You cannot have negative indexes with this technique.
I am a beginner in c++,I need to be able to find longest series of chars (that are next to each other) in a string that will be inputted by user,how can I do that, I have been trying for hours to type the code and nothing worked for me.
Sorry for my Bad English
example:
"**....*****......"(string input)
I need to find the longest series of '*'
so the input will be 5
problem(need to count just the chars between 'S' and finish at 'F')
int cnt=0,cnt1=0,cnt2=0;
string s;
cin>>s;
for(int j=0;j<s.length();j++){
if(s[j]=='S')
cnt1++;
if(s[j]=='F')
break;
while(true) {
if(s[j]=='*'&&cnt1==1)
cnt++;
if(cnt>cnt2)
cnt2=cnt;
if(s[j]=='F')
break;
}
cnt=0;
}
cout<<cnt2<<endl;
So I assume you are trying to find a series of equal chars (like "aaa").
A simple method, probably not the most efficient, is to count those chars in a loop and hold the index of the longest set of chars.
Get your string from stdin
Create an index counter and a variable to count current number of chars
Count same chars in a loop in one int and mark their beginning index (only if sum is greater than the last one you encountered in loop)
After the loop return the char (and same following chars) in string[index]
Basically what I'm looking for is a way to set the contents of an array -ex: a phrase- into individual words to be compared.
so when the user enters the data, I can tell how many words of the same length they are.
void main(){
char array[30];
int length, cont, array_tokens;
printf("enter a phrase: ");
scanf("%[^\n]s", array); //or gets(array); which ever one you like
/*-------------------------
*******magic happens*******
---------------------------*/
for(int i=0; i<wordcount;i++)
printf("%d word(s) with %d letters was entered", array_tokens, cont);//some sort of
system("pause"); //counter which came
} //with the magic that
//happened before
so the result should be:
enter a phrase: user entered a phrase with similar lentgh words
1 word(s) with 1 letter was entered
2 word(s) with 4 letters was entered
1 word(s) with 5 letters was entered
3 word(s) with 6 letters was entered
1 word(s) with 7 letters was entered
Well, strtok() is one way to solve this problem. If you're aiming for efficiency (you should), you should write a loop which iterates over the letters in the sentence. Count the number of non-space characters encountered since the last white-space, and update the n-letter-word-frequency array whenever you get a white-space. I could've written the code to do this, but I don't want to deprive you of the sense of gratification when you write the working piece of code yourself. :P
You can have an array count where count[i] is the number of words of length i.
Set count to 0
Set t to 0
for(int i=0;i<given_phrase.length();i++)
{
if(given_phrase[i]==' ')
{
count[t]++;
t=0;
}
else
{
t++;
}
}
For C, simply check for '\0' for end of phrase.
Then you can display results based on count.
You'll want to split up the sentence into tokens (in this case individual words) by a delimiter (in this case a space char ' '). There are various ways to do that. A good old-school C method is to use strtok as Robert Harvey suggested, which is provided by the C Standard Library. It works by passing in the string you want to split up, followed by the delimiter at which to split the string.
Then, to count the similar length words, try having integer variables for the different word lengths (or more simply in a sort of frequency array, each index representing a word of that length and its value being a count of their occurrences), looping over all the word tokens, incrementing the corresponding variable when a word of a length is encountered. To obtain the length of a C-Style string, try strlen.