Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Here is my program.I am trying to find the frequency of each character of a string and display it. While answering please see to it that I don't want to try the ASCII concept and I want to know whats wrong with this concept.
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
int l=0,j,k,m,count[10000];
char string[10000];
printf("Enter the string : \n");
scanf("%s",string);
l=strlen(string);
printf("%d",l);
for(j=0;j<l;j++)
{
for(k=j+1;k<l;k++)
{
if(string[j]==string[k])
{
count[j]++;
}
}
}
for(m=0;m<l;m++)
{
printf("%d",count[m]);
}
return 0;
}
So you wish to find the frequency of characters in your string.
About the mistakes in your code:
Consider the string lalal Here you would be counting the last l twice, once corresponding to first l and second time corresponding to third l. Hence your logic is faulty.
Similar is the case of count[]. You haven't initialized the array hence it holds garbage values.
So another approach to your problem could be declaring a 26-element array(English alphabet), iterate through the entire list and increment count corresponding to each element when that element is found.
int frequencyChar[26] = {0};//stores frequency of characters [a-z], initialized to zero
for( i=0; i<strlen(str); i++) //iterate through the entire string
{
frequencyChar[str[i] - 'a']++; //increment count corresponding to each element
}
for( i=0; i<26; i++)
{
printf("%d\n",frequencyChar[i]);
}
P.S.Above code assumes only lowercase characters in string. Minor changes would allow inclusion of uppercase letters!
Here are the problems:
You have written: I am trying to find the frequency of each character, but you code is attempting to calculate histogram of correlations between pairs of characters.
as an index for count you are using j, which iterates over constitutive characters in string. This means that your table count have lots of 0 and only some 1 and nothing else.
So currently this is NOT histogram of pairs of characters nor histogram of characters.
Character histogram can be created like this:
void makeStrHistogram(char *str, int histogram[256])
{
memset(histogram, 0, sizeof(histogram));
while (*str) histogram[*str++]++;
}
void printHistogram(int histogram[256])
{
for (int i=0; i<256; ++i) {
if (histogram[i]) {
printf("%c - %d\n", (char)i, histogram[i]);
}
}
}
To generate character correlation matrix:
void correlationMatrixForStr(char *str, int matrix[256][256])
{
memset(matrix, 0, sizeof(matrix));
int len = strlen(str);
for (int i=0; i<len; ++i) {
for (int j=i+1; j<len; ++j) {
matrix[i][j]++;
}
}
}
Related
I am making a program which requires the user to input an argument (argv[1]) where the argument is every letter of the alphabet rearranged however the user likes it. Examples of valid input is "YTNSHKVEFXRBAUQZCLWDMIPGJO" and "JTREKYAVOGDXPSNCUIZLFBMWHQ". Examples of invalid input would then be "VCHPRZGJVTLSKFBDQWAXEUYMOI" and "ABCDEFGHIJKLMNOPQRSTUYYYYY" since there are duplicates of 'V' and 'Y' in the respective examples.
What I know so far is, that you can loop through the whole argument like the following
for (int j = 0, n = strlen(argv[1]); j < n; j++)
{
//Place something in here...
}
However, I do not quite know if this would be the right way to go when looking for duplicates? Furthermore, I want the answer to be as simple as possible, right know time and cpu usage is not a priority, so "the best" algorithm is not necessarily the one I am looking for.
Try it.
#include <stdio.h>
#include <stddef.h>
int main()
{
char * input = "ABCC";
/*
*For any character, its value must be locate in 0 ~ 255, so we just
*need to check counter of corresponding index whether greater than zero.
*/
size_t ascii[256] = {0, };
char * cursor = input;
char c = '\0';
while((c=*cursor++))
{
if(ascii[c] == 0)
++ascii[c];
else
{
printf("Find %c has existed.\n", c);
break;
}
}
return 0;
}
assuming that all your letters are capital letters you can use a hash table to make this algorithm work in O(n) time complexity.
#include<stdio.h>
#include<string.h>
int main(int argc, char** argv){
int arr[50]={};
for (int j = 0, n = strlen(argv[1]); j < n; j++)
{
arr[argv[1][j]-'A']++;
}
printf("duplicate letters: ");
for(int i=0;i<'Z'-'A'+1;i++){
if(arr[i]>=2)printf("%c ",i+'A');
}
}
here we make an array arr initialized to zeros. this array will keep count of the occurrences of every letter.
and then we look for letters that appeared 2 or more times those are the duplicated letters.
Also using that same array you can check if all the letters occured at least once to check if it is a permutation
I don't know if this is the type of code that you are looking for, but here's what I did. It looks for the duplicates in the given set of strings.
#include <stdio.h>
#include <stdlib.h>
#define max 50
int main() {
char stringArg[max];
int dupliCount = 0;
printf("Enter A string: ");
scanf("%s",stringArg);
system("cls");
int length = strlen(stringArg);
for(int i=0; i<length; i++){
for(int j=i+1; j<length; j++){
if(stringArg[i] == stringArg[j]){
dupliCount +=1;
}
}
}
if(dupliCount > 0)
printf("Invalid Input");
printf("Valid Input");
}
This code snippet is used to count the duplicate letters in the array.
If you want to remove the letters, Also this code snippet is helpful .Set null when the same characters are in the same letter.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count=0;
int array[]={'e','d','w','f','b','e'};
for(int i=0;i<array.Lenth;i++)
{
for(int j=1;j<array.Length;j++)
{
if(array[i]==array[j])
{
count++;
}
}
}
printf("The dublicate letter count is : %d",count);
}
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int h[26]={0};
int i, j, count, tmp=0;
scanf("%s", str);
count=strlen(str);
for(i=0; i<count; i++) {
h[str[i]-97]++;
}
for(j=0; j<25; j++) {
if(h[j]<h[j+1]) {
tmp=j+1;
}
}
printf("%c", (char)tmp+97);
}
I want to output the most frequently entered lowercase letters, but how can I change it by output the strange values?
Try input this code "aaaabbbbsefa", then the "s" will be output.
Your code has a lot of problems. And a good bit of traps.
scanf("%s", str);
What if the input is longer than str can hold?
count=strlen(str);
This is a waste of cpu cycles. You don't need the length of a string to loop through it, you can simply check if the current element of the string is a \0
for(i=0; i<count; i++) {
h[str[i]-97]++;
}
This is problematic, what if the input contained some other character than lower case characters, this could easily cause out of bounds reading.
for(j=0; j<25; j++) {
if(h[j]<h[j+1]) {
tmp=j+1;
}
}
Firstly, this loop stops before 25, but it should stop before 26
Secondly, this definitely does not do what you think it does.
If you want to print the most frequent lower case character from in your input, this is how the flow should look like-
Take the string input and store it into a char array, make sure it can actually hold it
Declare a variable to keep track of the number of occurrences for each lowercase alphabet
Loop through the input string
Check if the current element is lowercase - if it is, add to the counter - if it isn't, do nothing
Loop through the occurrences record, check if the current occurrence is higher than the highest record (which is set to 0 before the loop) - if it higher, change the highest record to it and store the character - if it isn't, move on
Print the resulting character
This is how that'd look like in C-
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define ALPHABET_COUNT 26
#define MAX_LEN 100
int main()
{
char str[MAX_LEN];
int occurrences[ALPHABET_COUNT] = { 0 };
if (!fgets(str, MAX_LEN, stdin))
{
// Something went wrong, error handling here
return 1;
}
for (int i = 0; str[i] != '\0'; i++)
{
if (islower(str[i]))
{
occurrences[str[i] - 'a']++;
}
}
int highest_occurrence = 0;
char highest_occurring_char;
for (int i = 0; i < ALPHABET_COUNT; i++)
{
if (occurrences [i] > highest_occurrence)
{
highest_occurrence = occurrences[i];
// Convert the current index to its corresponding lowercase alphabet
highest_occurring_char = (char) (i + 'a');
}
}
printf("Highest occurring character: %c\n", highest_occurring_char);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am solving a question on Codechef BUY1GET1.Here is the question.
One day Alice visited Byteland to purchase jewels for her upcoming wedding anniversary.
In Byteland, every Jewelry shop has their own discount methods to attract the customers. One discount method called Buy1-Get1 caught Alice's attention. That is, Alice buys one jewel, then she can get one additional jewel with the same color without charge by Buy1-Get1.
Alice lists the needed jewels as a string S, each letter denotes one jewel, and the same letters denote the same colors of jewels, and the different letters denote the different colors of jewels. The cost of each jewel is 1. Your task is to calculate the minimum cost for getting all the jewels Alice listed.
Input
The first line of input contains a single line T, which represents the number of test cases. Then T lines will follow, and each contains a string S, which represents the jewels Alice needed.
Output
Output the minimum cost for each test case.
Constraints
1 ≤ T ≤ 100
1 ≤ |S| ≤ 200, where |S| represents the length of the string S.
The string S is case sensitive, and will contain only English characters in the range [a-z], [A-Z].
Sample
Input:
4
ssss
ssas
sa
s
Output:
2
3
2
1
I am always getting wrong answer on Codechef but on my PC it give the same output as the sample cases. I can't figure out why?
Here is my code.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
int t;
scanf("%d\n",&t);
while(t--)
{
int i,j,n,m=0,k=0;
char a[201];
scanf("%s",a);
n=strlen(a);
int count=0;
for(i=0;i<n;i++)
{
count=0;
if(isalpha(a[i]))
{
count++;
for(j=i+1;j<n;j++)
{
if(a[j]==a[i])
{
count++;
a[j]=++k;
}
}
}
//printf("%dc\n",count );
if(count%2==0)
{
m+=(count/2);
//printf("%dm1\n",m);
}
else if(count%2!=0)
m+=(1+count/2);
}
printf("%d\n",m );
}
return 0;
}
OK
just replace the following line:
a[j]=++k;
with
a[j]= '\0';
and submit again.
Explanation
for certain cases the value of k comes to the range 65-90 and 97-122
then k is treated as a character as it obtains the ascii value of a character.
so assign a null value to the array a[] every time and i think it will work.
int sum = 0;
//search number of occurences for each alphabet in the string
for (i=0; i<26; i++) {
sum += (numchar(str, 'a' + i) +1) / 2; //round up
}
You could write your own numchar function that finds how many characters c exist in a string s:
int numchar(char[] s, char c) {
int i = 0, n = 0;
while ( s[i] != '\0' ) {
if (s[i] == c) n++;
i++;
}
return n;
}
solution:
#include<stdio.h>
int main()
{
int t,h[256],i,cost;
scanf("%d",&t);
char s[201];
while(t--)
{
for(i=0;i<256;i++)
h[i]=0;
scanf("%s",s);
i=0;
while(s[i])
{
h[s[i]]++;
i++;
}
cost = 0;
for(i='A';i<='z';i++)
if(h[i]&1)
cost += h[i]/2 + 1;
else
cost += h[i]/2;
printf("%d\n",cost);
}
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Compare each string and find the number of common lowercase letter in all the strings.
Each string is represented by a lowercase letter from 'a' to 'z'.
Example Input:
4
abcf
aghb
acbl
bamn
Example Output:
2 // a and b
Code:
#include<stdio.h>
#include<string.h>
int main() {
int n;
scanf("%d\n",&n);
char str[n][100];
char var[0][100];
for(int i=0; i<n; i++) { // strings
scanf("%99s/n",str[i]);
}
for(int i=0;i<100;i++) { // comparison of first 2 strings
for(int k=0;k<100;k++)
if(str[0][i]==str[1][k])
for(int j=0;j<strlen(str[0]);j++) {
var[0][j]=str[0][j]; // storing the common letters in a var array
}
}
for(int l=0; l<strlen(str[1]); l++) { // comparing letters in var array with the letters of all other strings
int x;
if(var[0][l]==str[l+2][l]);
x=strlen(var[0]); // counting the common letters
printf("%d\n",x);
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
int n;
scanf("%d",&n);
char str[n][100];
char var[n][26];
memset(&var[0][0], 0, sizeof(var));
for(int i=0; i<n; i++) {
scanf("%99s", str[i]);
char ch;
for(int j=0; ch=str[i][j]; ++j){
if(islower(ch)){
var[i][ch-'a']=1;//depend on the sequence of character codes
}
}
}
int x = 0;
for(int i=0; i<26; ++i){
int num = 0;
for(int j=0;j<n;++j)
if(var[j][i])
++num;
if(num==n)//all string has character of ('a'+i)
++x;
}
printf("%d\n",x);
return 0;
}
Not sure why you would want to special-case the first two strings here? How about an approach like this (in pseudocode):
- create a set of characters, name it letters_in_all_strings
- add every lowercase letter to letters_in_all_strings
- for each input string
- create a set of characters, name it letters_in_this_string
- add every character in the input string to letters_in_this_string
- remove all letters from letters_in_all_strings that are not present in letters_in_this_string
- print out the size of letters_in_all_strings
You could use an array of 0s and 1s, indexed by char, to implement a set of chars in C. Or you could use glib (https://stackoverflow.com/a/2502721/2186890). Or maybe consider using a more modern programming language?
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 8 years ago.
Improve this question
If I had an array that looks like :
'A\t2\nB\t5\nC\t6\nB\t2\n' <- alphabet and numbers are separated by a tab(\t) and a new line(\n) after the number.
I need to collect the same alphabet together also summing the number behind of alphabet. If printing out the output should looks like:
'A\t2\nB\t7\nC\t6'.
I thought of using a strcmp function, but the input array may change so I wont be able to know what alphabet is in it.
edit: sorry, I think my question is not clear. My array is not only a character, but it can be a sequence of character+numbers too. such as: 'THIS\t25\nTHESE\t67\nTHOSE\t2\nTHESE\t102\nTHOSE23\t55\n'
You can read the current line's alphabet into char c and the number into int i and have a int alpha[26] defined with all entries initialised to 0. Then you just have to:
alpha[c - 'A'] += i;
then just print out all non-zero entries in alpha
You can collect each character at a time and use a switch to produce the desire output...
like...
getch(c);
switch(c)
{
//case for alphabets
//case for numbers
}
I think you should first find smallest letter (by ASCII code number ex. A=65), search input strings for this letter (maybe using strchr) and summ (in separate variable) all numbers relative to this letter, at the end, write letter and number in new string and proceed with next letter (B=66).
Then you'll have new string sorted and summarized.
char *input;
char *output;
char *p, *cur;
int nums, num;
char min;
char temp[20];
//search for minimal letter
for(int i = 0; i < strlen(input); i++){
if(input[i] > 65 && input[i] < 90)
if(input[i] < min)
min = input[i];
}
//parsing input string
for(int i = 0; i < strlen(input)/4; i++){
//strlen(input)/4 because each sequense at least 4 letters
p = input;
num = 0;
nums = 0;
while(cur = strchr(p, min)){
sscanf(cur+2, "%d", &num);
nums += num;
p = cur+1;
}
//filling new string
sprintf(temp, "%c\t%d\n", min, nums);
strcat(output, temp);
min++;
}