299-e-Bulls and Cows

数字游戏,根据提示猜数字。乍一看就是哈希了,好像不难上手就写,但后来发现自己根本没完全理解要求导致老是错误。难点在于当有重复数字时确定那个cows,也就是b。反正自己写了蛮久cows的逻辑,我只看出了b不能大于secret中该字的出现次数,然后就是改啊改的,就是不完全对。原因在于自己没有搞懂它确定的逻辑到底是什么。提交了n次后怒查答案,发现有个思路是将secret和guess都哈希然后其各位最小值之和就是bulls和cows之和,bulls很好确定,于是相减就得出b了。至于为什么是bulls和cows之和我还得想想,但反正ac了。另外就是由于是c写的,而b可能大于10,所以还得处理字符串貌似我的ide还用不乐itoa,真是不省心。。。

反正写的不好,ac代码如下:

char *int2str(char *result, int num) {
    if (num == 0) {
        return result;
    }
    
    int a = num % 10;
    num /= 10;
    
    int2str(result, num);
    
    result[strlen(result)] = a + 48;
    result[strlen(result)] = '\0';
    
    return result;
}
char* getHint(char* secret, char* guess) {
    int a = 0, b = 0, sp = 0, gp = 0;
    int *hashSecret = (int *)calloc(10, sizeof(int)); //表示原表各个数字个数的表
    int *hashSource = (int *)calloc(10, sizeof(int)); //动态求哈希值时表征原表的表
    int *hashGuess = (int *)calloc(10, sizeof(int));  //动态表征猜表的表
    memset(hashSecret, 0, sizeof(int) * 10);
    memset(hashSource, 0, sizeof(int) * 10);
    memset(hashGuess, 0, sizeof(int) * 10);
    
    for (int i = 0; secret[i] != '\0'; i++) {
        sp = secret[i] - 48;
        hashSecret[sp] += 1;
        gp = guess[i] - 48;
        hashGuess[gp] += 1;
        
        if (secret[i] == guess[i])
            a++;
    }
    
    for (int i = 0; i < 10; i++) {
        printf("%d: sec-->%d, source-->%d, gue-->%d\n", i, hashSecret[i], hashSource[i], hashGuess[i]);
    }
    
    int tmpa = 0, tmpb = 0;
    int secCount = 0, ammu = 0;
    for (int i = 0; i < 10; i++) {
        tmpa = hashSource[i];
        tmpb = hashGuess[i];
        secCount = hashSecret[i];
        
        if (tmpb <= secCount)
            ammu += tmpb;
        else
            ammu += secCount;
    }
    b = ammu - a;
    
    
    char *result = (char *)calloc(10,sizeof(char));
    char *as = NULL, *bs = NULL;
    
    if (a != 0) {
        as = (char *)calloc(32, sizeof(char));
        int2str(as, a);
        for (int i = 0; as[i] != '\0'; i++)
            result[i] = as[i];
    }
    else
        result[0] = '0';
    result[strlen(result)] = 'A';

    if (b != 0) {
        bs = (char *)calloc(32, sizeof(char));
        int2str(bs, b);
        for (int i = strlen(result), j = 0; bs[j] != '\0'; i++, j++)
            result[i] = bs[j];
    }
    else
        result[strlen(result)] = '0';
    result[strlen(result)] = 'B';
    
    free(hashSecret);
    free(hashGuess);
    free(hashSource);
    
    return result;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值