c - 二维字符数组中的排序列

标签 c arrays matrix c99

<分区>

我有一个二维数组,其中顶行是一行字母(字母表),底行是它上面的字母在字符串中出现的频率。这个想法是将字母按频率顺序排列在顶行。

目前:

输入:

quickbrownfoxjumpsoverthelazydog

输出:

abcdefghijklmnopqrstuvwxyz

11112111111111411211211111

期望的输出:

oeruabcdfghijklmnpqstvwxyz

42221111111111111111111111

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>

main()
{
    char string[100];
    char s[26][2];
    int c = 0, count[26] = {0};

    printf("Enter a string\n");
    gets(string);

    while ( string[c] != '\0' )
    {
        if ( string[c] >= 'a' && string[c] <= 'z' ) 
        count[string[c]-'a']++;

        c++;
    }


    for ( c = 0 ; c < 26 ; c++ )
    {
        if( count[c] != 0 )
        {
            s[c][1]=c+'a';
            s[c][2]= (char)(((int)'0')+count[c]);
            gotoxy(c,1);
            printf("%c",s[c][1]);
            gotoxy(c,2);
            printf("%c",s[c][2]);
        }
    }

    return 0;
}

最佳答案

这是一种方法:取每个计数,将其左移五位,然后按位或低五位中的字母编号。对生成的数字进行排序,并通过使用 0x1F 并添加 'a' 将其最低有效的五位转换回字母。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int compare (const void * a, const void * b) {
    int ia = *(int*)a;
    int ib = *(int*)b;
    return (ia>>5) == (ib>>5) ? ia-ib : ib-ia;
}

int main(int argc, char* argv[]) {
    char string[100] = "quickbrownfoxjumpsoverthelazydog";
    int c = 0, count[26];
    memset(count, 0, sizeof(count));
    while ( string[c] != '\0' ) {
        if ( string[c] >= 'a' && string[c] <= 'z' ) {
            count[string[c]-'a']++;
        }
        c++;
    }
            // Shift the letter ordinal into the lower five bits of the count*32
    for ( c = 0 ; c < 26 ; c++ ) {
        count[c] = (count[c] << 5) | c;
    }
            // Sort the results using the custom compare function
    qsort(count, 26, sizeof(int), compare);
            // Print the letters by taking the lower five bits
    for ( c = 0 ; c < 26 ; c++ ) {
        printf("%c", 'a'+(count[c]&0x1F));
    }
    printf("\n");
            // Print the counts by ignoring the lower five bits
    for ( c = 0 ; c < 26 ; c++ ) {
        printf("%d", count[c] >> 5);
    }
    return 0;
}

关于c - 二维字符数组中的排序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9082430/

相关文章:

c - 使用 eclipse CDT 进行 gdb 调试 : not able to show correctly varibles values

c - 在c语言windows中通过函数重置二维数组

c# - 如何用垃圾填充字节数组?

php - 多对象数组中的 json_decode

arrays - 如何获取给定范围内大于x的元素?

matlab - 如何创建随机矩阵,其中除了一个随机行外,每一列都是零?

c++ - 在分块矩阵中查找一个值

c# - 将结构内的整数指针编码为回调

c - 结构体可以包含的成员数量或变量类型是否有大小限制?

java - java中无法编译的源代码错误