Count Alphabet Characters from an array? [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So, in this program we have to
A. Count the number of each letter of the alphabet found in a character array and store these counts in an integer array
I understand that part but then it says we have to use the ASCII values which confuses me.
This is the file for reference:
" A frog walks into a bank and asks the teller, Miss Pattywack
for a loan. Miss Pattywack tells the frog,
"you must have collateral for the loan".
The frog pulls out of his pouch his porcelain people collection
and offers them as collateral.
Miss Pattywack looks at the figurines and tells the frog that
the collection is not acceptable.
The bank manager overhears the conversation and yells to the
teller - "It's a nick nack Pattywack, give the frog a loan!"
Use a for loop to examine each character in the character array
i. Use toupper to case the letter, so you are only dealing with capital letters
ii. If the character is a letter of the alphabet, increment the integer array in the position of the ASCII value of the character minus 65
1) 65 is the ASCII value of letter, 'A'
(1) If the character is A, 65-65 = 0 the position you want to increment for the character A
(2) If the character is C, 67-65 = 2 the position you want to increment for the character C
I have this so far:
void CountAlphabetCharacters(char chArray[MAX_CHARACTERS], int lengthOfArray)
{
int index;
for(index = 0; index <= lengthOfArray; index++)
{
chArray[index] = toupper(chArray[index]);
static_cast<int>(index);
}
}
That's all I have because that's all I understand. I mean, I understand how you get the ASCII value but I am so lost on how to actually make the for loop for this. Like I'm assuming you look at the characters from the file but I don't understand how you get that value you and keep going. I don't know if I make sense but I'm hoping I do and someone can help!! Thanks in advance.

Things you need:
An array to hold the characters that you read. I think chArray is that array.
An array to hold the count of the letters of the alphabet. I don't see that array.
Update the code in CountAlphabetCharacters to go through the characters in chArray and update the count of letters in chArray.
Before calling CountAlphabetCharacters, create the array for holding the count of characters.
int charCountArray[26] = {0};
Change the function CountAlphabetCharacters to accept it as an argument.
void CountAlphabetCharacters(char chArray[MAX_CHARACTERS],
int charCountArray[],
int lengthOfArray)
Use it as an argument in the call to CountAlphabetCharacters.
Update the implementation of CountAlphabetCharacters.
void CountAlphabetCharacters(char chArray[MAX_CHARACTERS],
int charCountArray[],
int lengthOfArray)
{
int index;
int ch;
for(index = 0; index <= lengthOfArray; index++)
{
// The character at the index.
ch = chArray[index];
// Check whether it is an alphabetical character.
if ( isalpha(ch) )
{
// If so, make it the uppercase letter.
ch = toupper(ch);
// Increment the charCountArray for the letter.
charCountArray[ch-'A']++;
}
}
}

void CountAlphabetCharacters(char chArray[MAX_CHARACTERS], int lengthOfArray)
{
int index;
int counter[26]={0}; // holds occurrence of each character
for(index = 0; index < lengthOfArray; index++)
{
if(isalpha(chArray[index]){
int val = (int)toupper(chArray[index]);
counter[val-65]++; //increment occurrence count for this character
}
}
for(char c ='A',index = 0; index <26; index++,c++)
{
printf("%c : %d", c, counter[index]); //print character and corresponding occurrence
}
}

Related

Finding matching letters in a string at same spots [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I need a code to compare two strings: word and ptw. Both strings only have one word, and are of equal length and same case. The code needs to check the first character of both words and see if they are same and it will do this untill the end of the word. Then it will output the amount of matching letters (I don't need to know the matching letters).
Example: If word is windows and ptw is winowes it should output 4 as w, i, n, and s match.
I have tried the following however it does not check the positions:
string matchingletters(string word, string ptw) {
string result = "";
sort(begin(word), end(word));
sort(begin(ptw), end(ptw));
std::string intersection;
std::set_intersection(begin(word), end(word), begin(ptw), end(ptw),
back_inserter(intersection));
string mlr = to_string(intersection.length());
result = mlr + result;
cout << result << endl;
return result;
}
The result this gives when word is kanton and ptw is balkon is 4.
It counts k even though k is at 0 position in word and 3 position at ptw and thus they are not in the same postion and should not be counted.
Assuming the two words have the same length and since you don't care which letters match you can simply iterate and count matching characters
unsigned matchingletters(const std::string& word, const std::string& ptw) {
assert(word.size() == ptw.size());
unsigned count{0};
for (size_t i = 0; i < word.size(); ++i) {
if(word[i] == ptw[i])
count++;
}
return count;
}

Can somebody explain to me that how does this C program reverse an characters array? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
there is a program written below. I am not understanding that how does it reverse an char array. I mean it works fine, it does reverse the string which is stored in char array by user, but I want to know how does it work and how does it reverse the order? Basically I am not understanding the first for loop, it does not have any statements in the body plus the first part of the for loop is missing. Please explain in simple and easy words, not in typical or difficult words. I am not a native English speaker. Thanks a lot.
#include <iostream>
using namespace std;
int main()
{
char name[99];
int counter=0;
cin >> name;
for(;name[counter]!='\0'; counter++)
{}
cout << "\nName: ";
for (;counter > 0; counter--)
{
cout << name[counter-1];
}
}
C strings are null ('\0') terminated. The first loop increments counter until the end of the string contained in name is found. That is indicated by the null character. The important part is that counter is declared outside of the first for loop and it stays in scope, and with the same value, when the second loop is executed. The second loop then starts at the end of the string in name printing the characters until the it prints the first character.
In Your Program, First For loop is to know number of characters in name variable.
Let me explain you how it works.
For loop have basic structure like
for(i=10;i>0;i--)
{
//Body part of for
}
First part i=0 is initialization, second part is condition and third part is Increment/Decrements. In your program, We have already initialize value of counter as 0. This loop is just for counting number of characters so after every loop count variable will increment. We do not need to write anything in body part.
after completing first for loop count variable have same value as name variable's characters.
Again in second loop we don't need to initialize count values because count already have some value stored in it.
Hope You understand now..!!
you start your counter at 0.
for(;name[counter]!='\0'; counter++){}
the for loop above increments the counter until it reaches '\0' .At this point your counter has incremented to the number of characters of what you typed as name. eg: if you typed hello counter is now at 5.
for (;counter > 0; counter--){cout << name[counter-1];
}
In the above for loop,you start by having the counter value at 5 then printing out each character of your array in reverse because first iteration your counter is 5, you print name[4] which is o then counter decrements so you print name[3]=l,then name[2]=l,
then name[1]=e , then name[0] =h. Note: if your counter is at value n you are printing n-1. so when your counter decrements to 1 you print name[0]. then the counter finally decrements to 0 where the loop becomes false. Also you are not reversing the array elements themselves but are just printing them in reverse.
#include <iostream>
using namespace std;
int main()
{
char name[99];
int counter=0; // variable to store the number of characters in name.
cin >> name;
// the for loop is counting each letter until the end of the string, storing the result in counter.
for(;name[counter]!='\0'; counter++)
{}
cout << "\nName: ";
// if the name you entered was "Billy" counter would = 5
for (;counter > 0; counter--)
{
// since counter = 5 counter subtracts 1 to get to the "5th" spot in the array which is when counter = 4
// name[0] = B
// name[1] = i
// name[2] = l
// name[3] = l
// name[4] = y
// now starting from position 4 in the array counter-- subtracts 1
// from counter each time it runs through the loop to get to each previous letter.
cout << name[counter-1];
}
}

decoding a character array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Given a character array in a URL format like
char *s="www.google.com\tsp finite.aspx"
While decoding it space should be replaced by %20 and thus the string becomes:
char *s="www.google.com\tsp%20finite.aspx"
We are not allowed to use a new character array but allowed to use some character variables for temporary use. Should not use any containers also. The array contains enough space to contain the decoded data so no need to worry about the more space to be taken.
I followed the Brute-Force mechanism where all the characters from the point of finding a space to the end of the array are to be swapped. But this is not the most efficient way to solve the problem.
Can any body tell me which is the best way (algorithm) to decrease the no. of swappings in order to acquire the solution.
I am assuming the string has been allocated using malloc
First calculate the number of spaces and the length of the string
Then the new length = old length + number of spaces * 2. Use realloc to expand the string.
The work backwards from the end and copy to the new length. When encountering space copy in %20 instead.
The main problem could be that swapping space with %20 will require moving the whole string 2 characters more .
Here's an idea :
Parse the whole string once, and count the number of spaces in the string
The new length of the array would be strlen(original) + 2*(nOfSpaces) (let's call it from now on NewLen)
Parse the whole string once again but starting backwards.
You will copy the previous string contents inside itself but at an offset until you hit a space
you will have a pointer starting at strlen(original) and one starting at NewLen
parse from strlen(original) backwards until you find a space (the substrLen will be subLen)
memcpy from [strlen(original)-curParsingindex] to [NewLen - curParsingIndex-2*(enteredSpaces)] sublen amount
Instead of copying the space, put %20 instead
This way you will avoid moving the string forward each time you hit a space.
Regarding step 4 , you might think about using a temporary variable for the sublen, since you might end up writing in the same memory zone by mistake (take an example where all the spaces are at the beginning).
This is a classic interview coding question; a good solution for this starts with a good interface for your solution. Something that works is:
char* replaceChar(char* in, char c)
char *in - string you want to decode
c - the char you want to replace with it's hexa value ASCII code ( HEX val ascii for ' ' is 0x20)
Pseudocode:
allocate a buffer the same size as the input buffer
get the index of the first occurrence of the char you want to replace (strcspn can help with that)
copy the content of the of the input up to the found index to the new buffer.
reallocate the new buffer size to newSize=oldSize+2
add % to the new string
repeat until you reach the end of the string.
return a pointer to the new string
You can also do it in place on the original string but that solution is a bit more complicated because you have to shift everything.
You can do it in two passes. The key idea is to first count the number of spaces and then move each character directly to its final position. In your approach you shift the remainder of the string at each occurrence of a space.
#include <stdio.h>
int main ()
{
char str[1000] = "www.example.com/hello world !";
int length;
int spaces;
int i;
char *ptr;
printf ("\"%s\"\n", str);
// pass 1:
// calculate length and count spaces
length = 0;
spaces = 0;
for (ptr = str; *ptr; ptr++) {
if (*ptr == ' ') {
spaces++;
}
length++;
}
// pass 2:
// transform string
// preserve terminating null character
ptr = str + length + 2 * spaces;
for (i = length; i >= 0; i--) {
char c = str[i];
if (c == ' ') {
*ptr-- = '0';
*ptr-- = '2';
*ptr-- = '%';
}
else {
*ptr-- = c;
}
}
printf ("\"%s\"\n", str);
return 0;
}

Separating number input into units [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I need to separate users input into units and store them in an array.
e.g if user enters 6547. Array will store {6,5,4,7} Using C++ on Linux
I would appreciate if you can help me with pseudocode or explain an algorithm.
I'm a beginner so please restrain from advising advanced function (and explain its use if you do) as we have studied basics so far
N.B| If such question has already been answered and I skipped it in search, please do point me to it.
The math for isolating right most digit:
digit = digit % 10;
The math for shifting a number right by one digit:
new_number = old_number / 10;
Every letter and number can be represented as a text character. For example, '5' is a character representing the single decimal digit 5.
The math for converting a textual digit (character) to numeric:
digit = char_digit - '0';
Example:
digit = '9' - '0';
The math for converting a numeric digit to a textual digit (character):
char_digit = digit + '0';
Example:
char_digit = 5 + '0';
Your problem basically breaks into few parts, which you need to figure out:
how to read one character from input
how to convert one character to the digit it represents
how to store it in the array
Please, try to explain if you have problem with some particular point from the list above or there is a problem somewhere else.
Suppose Variable input_string holds the number entered by the user & you want to store it in an array named 'a'...Here's a C snippet.. you can easily convert it into C++ code..
I would recommend taking the input as string rather than int so that you can directly insert the digits extracted from the end...(else you can start storing the integer from beginning and then reverse the array)
scanf("%s",&input_string)
size = strlen(input_string)-1
input = atoi(input_string)
while (input/10>0)
{
i=input%10;
input=input/10;
a[size]=i;
size--;
}
Hope that helps!
Here's a C++11 solution:
std::string input;
std::cin >> input;
int num = std::stoi(input);
std::vector<int> v_int;
for (unsigned int i = 0; i < input.size(); i++)
{
v_int.push_back(num % 10);
num /= 10;
}
// To get the numbers in the original order
std::sort(v_int.rbegin(), v_int.rend());
for (unsigned int i = 0; i < v_int.size(); i++) {
std::cout << v_int[i] << std::endl;
}
If you want it in a c-style array, do this:
int* dynamic_array = new int[v_int.size()];
std::copy(v_int.begin(), v_int.end(), dynamic_array);
delete dynamic_array;

Given a word and a text, return the count of the occurrences of anagrams of the word in the text [duplicate]

This question already has answers here:
Given a word and a text, we need to return the occurrences of anagrams
(6 answers)
Closed 9 years ago.
For eg. word is for and the text is forxxorfxdofr, anagrams of for will be ofr, orf, fro, etc. So the answer would be 3 for this particular example.
Here is what I came up with.
#include<iostream>
#include<cstring>
using namespace std;
int countAnagram (char *pattern, char *text)
{
int patternLength = strlen(pattern);
int textLength = strlen(text);
int dp1[256] = {0}, dp2[256] = {0}, i, j;
for (i = 0; i < patternLength; i++)
{
dp1[pattern[i]]++;
dp2[text[i]]++;
}
int found = 0, temp = 0;
for (i = 0; i < 256; i++)
{
if (dp1[i]!=dp2[i])
{
temp = 1;
break;
}
}
if (temp == 0)
found++;
for (i = 0; i < textLength - patternLength; i++)
{
temp = 0;
dp2[text[i]]--;
dp2[text[i+patternLength]]++;
for (j = 0; j < 256; j++)
{
if (dp1[j]!=dp2[j])
{
temp = 1;
break;
}
}
if (temp == 0)
found++;
}
return found;
}
int main()
{
char pattern[] = "for";
char text[] = "ofrghofrof";
cout << countAnagram(pattern, text);
}
Does there exist a faster algorithm for the said problem?
Most of the time will be spent searching, so to make the algorithm more time efficient, the objective is to reduce the quantities of searches or optimize the search.
Method 1: A table of search starting positions.
Create a vector of lists, one vector slot for each letter of the alphabet. This can be space-optimized later.
Each slot will contain a list of indices into the text.
Example text: forxxorfxdofr
Slot List
'f' 0 --> 7 --> 11
'o' 1 --> 5 --> 10
'r' 2 --> 6 --> 12
For each word, look up the letter in the vector to get a list of indexes into the text. For each index in the list, compare the text string position from the list item to the word.
So with the above table and the word "ofr", the first compare occurs at index 1, second compare at index 5 and last compare at index 10.
You could eliminate near-end of text indices where (index + word length > text length).
You can use the commutativity of multiplication, along with uniqueness of primal decomposition. This relies on my previous answer here
Create a mapping from each character into a list of prime numbers (as small as possible). For e.g. a-->2, b-->3, c-->5, etc.. This can be kept in a simple array.
Now, convert the given word into the multiplication of the primes matching each of its characters. This results will be equal to a similar multiplication of any anagram of that word.
Now sweep over the array, and at any given step, maintain the multiplication of the primes matching the last L characters (where L is the length of your word). So every time you advance you do
mul = mul * char2prime(text[i]) / char2prime(text[i-L])
Whenever this multiplication equals that of your word - increment the overall counter, and you're done
Note that this method would work well on short words, but the primes multiplication can overflow a 64b var pretty fast (by ~9-10 letters), so you'll have to use a large number math library to support longer words.
This algorithm is reasonably efficient if the pattern to be anagrammed is so short that the best way to search it is to simply scan it. To allow longer patterns, the scans represented here by the 'for jj' and 'for mm' loops could be replaced by more sophisticated search techniques.
// sLine -- string to be searched
// sWord -- pattern to be anagrammed
// (in this pseudo-language, the index of the first character in a string is 0)
// iAnagrams -- count of anagrams found
iLineLim = length(sLine)-1
iWordLim = length(sWord)-1
// we need a 'deleted' marker char that will never appear in the input strings
chNil = chr(0)
iAnagrams = 0 // well we haven't found any yet have we
// examine every posn in sLine where an anagram could possibly start
for ii from 0 to iLineLim-iWordLim do {
chK = sLine[ii]
// does the char at this position in sLine also appear in sWord
for jj from 0 to iWordLim do {
if sWord[jj]=chK then {
// yes -- we have a candidate starting posn in sLine
// is there an anagram of sWord at this position in sLine
sCopy = sWord // make a temp copy that we will delete one char at a time
sCopy[jj] = chNil // delete the char we already found in sLine
// the rest of the anagram would have to be in the next iWordLim positions
for kk from ii+1 to ii+iWordLim do {
chK = sLine[kk]
cc = false
for mm from 0 to iWordLim do { // look for anagram char
if sCopy[mm]=chK then { // found one
cc = true
sCopy[mm] = chNil // delete it from copy
break // out of 'for mm'
}
}
if not cc then break // out of 'for kk' -- no anagram char here
}
if cc then { iAnagrams = iAnagrams+1 }
break // out of 'for jj'
}
}
}
-Al.