I am trying to apply a cipher method. I have tried doing a histogram, and I did not do argc argv in the main because I directly test it from there and I just call./a.out:
#include <stdio.h>
#include <string.h>
void cipher(const char text[], const char table[])
{
int length = strlen(text);
int hist[26]; //histogram for each letter of the alphabet
for (int i = 0; i < 26; i++)
{
hist[i] = 0;
}
char startletter;
for (const char *temp = text; *temp != '\0'; temp++)
{
startletter = *letter;
for (const char *letter = temp; *letter != '\0'; letter++)
{
if (*letter == startletter)
{
hist[*letter - 65] += 1;
}
}
}
for (int i = 0; i < 26; i++)
{
printf("%d ", hist[i]);
}
}
output:
0 0 0 0 0 15 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 3 1 0 0
(supposed to print out the letter occurences in string1
for now)
Here is the code:
#include <stdio.h>
#include <string.h>
void cipher(const char text[], const char table[]){
int hist[26]; //histogram for each letter of the alphabet
for (int i = 0; i < 26; i++)
hist[i] = 0;
for (const char *temp = text; *temp != '\0'; temp++)
hist[*temp-65] += 1;
for (int i = 0; i < 26; i++){
if (hist[i])
printf("%c=%d\n", 'A'+i, hist[i]);
}
}
int main(void){
const char a[] = "FXOWFFOWOFF";
const char b[] = "ABCD";
cipher(a, b);
return 0;
}
All you had to do was remove the nested loop.
you need to sort the histogram and then print letters from table according to the sorted histogram
here is the code:
#include <stdio.h>
#include <string.h>
void cipher(const char text[], const char table[])
{
int length = strlen(text);
int hist[26]; //histogram for each letter of the alphabet
for (int i = 0 ; i < 26; i ++)
{
hist[i] = 0;
}
for (const char *temp = text; *temp != '\0'; temp++)
{
hist[(int)*temp - 65]++;
}
for (int i = 0; i < 26; i++)
{
printf("%d ", hist[i]);
}
printf("\n");
// sort
int sort[26];
for (int i = 0; i < 26; ++i)
{
sort[i] = i;
}
int tempint;
for (int i = 0; i < 25; ++i)
{
for (int j = i; j < 26; ++j)
{
if (hist[sort[j]] > hist[sort[i]]) {
tempint = sort[j];
sort[j] = sort[i];
sort[i] = tempint;
}
}
}
for (int i = 0; i < strlen(table); ++i)
{
printf("%c %c\n", (char)(65 + sort[i]), table[i]);
}
return;
}
int main(void)
{
const char a[] = "FXOWFFOWOFF";
const char b[] = "ABCD";
cipher(a, b);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.