c语言编程一只蚂蚁,一个有趣的数蚂蚁问题(C语言实现)

问题

An orderly trail of ants is marching across the park picnic area.

It looks something like this:

..ant..ant.ant…ant.ant..ant.ant….ant..ant.ant.ant…ant..

But suddenly there is a rumour that a dropped chicken sandwich has

been spotted on the ground ahead. The ants surge forward! Oh No, it’s

an ant stampede!! Some of the slower ants are trampled, and their

poor little ant bodies are broken up into scattered bits. The

resulting carnage looks like this:

…ant…ant..nat.ant.t..ant…ant..ant..ant.anant..t

Can you find how many ants have died? —— [ codewars ]

提醒:

” ant “代表正常蚂蚁,其他为非正常蚂蚁;

两个头一个身体或者一个身体两个头都只代表两只死掉的蚂蚁。

思考

想要知道多少只死去的蚂蚁,我们就需要弄清有多少散乱的“头”和“身体”。如果“头”的数目多余“身体”,则用“头”数目代表死去蚂蚁数目;反之,则用“身体”代表死去蚂蚁的数目。“ant”代表的一只蚂蚁,那各个字母有代表着蚂蚁的什么部位呢?其实,不管是 ‘a’,‘n’,‘t’中的哪一个,都是蚂蚁的一部分,我们只需要统计不正常蚂蚁的‘a’,‘n’,‘t’的个数即可,最多的就代表总共死去的蚂蚁数目。

代码

接下来用C语言代码来实现:

#include

#include

int deadAntCount(const char* ants)

{

int a_all = 0;

int n_all = 0;

int t_all = 0;

int a_alive = 0;

int n_alive = 0;

int t_alive = 0;

int a_died;

int n_died;

int t_died;

for (ants; *ants != '\0'; ants++)

{

if (*ants == 'a')a_all++;

if (*ants == 'n')n_all++;

if (*ants == 't')t_all++;

if (*ants == 'a'&&*(ants + 1) == 'n'&&*(ants + 2) == 't')

{

a_alive++;

n_alive++;

t_alive++;

}

}

a_died = a_all - a_alive;

n_died = n_all - n_alive;

t_died = t_all - t_alive;

return (int)fmax(a_died,fmax(n_died,t_died));

}

//测试主函数

int main()

{

int a1 = deadAntCount("ant ant ant ant");

int a2 = deadAntCount("");

int a3 = deadAntCount("ant anantt aantnt");

int a4 = deadAntCount("ant ant .... a nt");

printf("%d,%d,%d,%d", a1, a2, a3, a4);

return 0;

}

测试结果

5da1418851f33c41c2342cb34e63a937.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值