TDD练习:保龄球计分
前言
培训遗留作业,计划放在国庆空闲时间做,所以这算是走计划节奏。另外,真的是不喜欢做这些题,虽然实现以后发现很简单。但是没实现之前,多少还是觉得有些困难,可能是自己做题太少(不知道别人做题时候啥感觉)。。另外,做这些题我是感觉完全搭不上算法的边,可能是我自己没专门学过的原因吧,基本上纯粹是按照题的说明需求,然后自己思考,整理思路,然后实现...过程就是这样。
保龄球计分(题目摘自网络,反正都一个规则) 打保龄球是用一个滚球去撞击10个站立的瓶,将瓶击倒。一局分10轮,每轮可滚球1 次或多次,以击到的瓶数为依据计分,一局得分为10轮得分之和,而每轮的得分不仅与本轮的滚球情况有关,还可能与后一轮或两轮的滚球情况有关,即:某轮某次滚球击倒的瓶数不仅要计入本轮得分,还可能会计入前一轮或两轮得分。 Output:
实现思路
<span style="font-size:18px;">/* test.cpp */ #include <assert.h> extern int CalcScore(const char *s); void main() { assert(CalcScore("10 10 10 10 10 10 10 10 10 10 10 10") == 300); assert(CalcScore("10 10 10 7 2 9 1 8 1 8 2 10 9 1 10 8 2") == 192); assert(CalcScore("1 4 4 5 6 4 5 5 10 0 1 7 3 6 4 10 2 8 6") == 133); }</span> <span style="font-size:18px;">/* bowling.cpp */ #include <stdio.h> #include <stdlib.h> typedef struct _context { const char *s; int pos; }Context; int Record[10]; bool Is_STRIKE(int score) { return score == 10; } int ParseScore(Context &ctx,int offset) { int temp_score = 0; if (ctx.s[ctx.pos] == ' ') { ctx.pos++; } return atoi(ctx.s + ctx.pos + offset); } int CalcScorePerRound(Context &ctx) { int offset = 0; int curr_score = 0; int next_score = 0; int round_score = 0; curr_score = ParseScore(ctx,0); // 0表示解析分数的起始偏移 if (Is_STRIKE(curr_score)) { offset = 2; next_score = ParseScore(ctx,offset); ctx.pos += 2; // 本轮STRIKE,下一轮击球开始解析的位置 } else { offset = 0; ctx.pos++; next_score = ParseScore(ctx,offset); ctx.pos++; // 本轮SPARE,下一轮击球开始解析的位置 } // 本轮计分 if (10 > (curr_score + next_score)) // 本轮两次击球未全中 { round_score = curr_score + next_score; } else // 本轮STRIKE或两次补中 { int third_score = ParseScore(ctx,offset); round_score = curr_score + next_score + third_score; } return round_score; } int CalcScore(const char *s) { Context ctx = {s,0}; int total_score = 0; printf("每轮得分:n"); for (int i = 0; i < 10; i++) { Record[i] = CalcScorePerRound(ctx); printf("%-2d ",Record[i]); total_score += Record[i]; } printf("n累计总分:%d",total_score); printf("n+++++++++++++++++++++++++++++++++n"); return total_score; }</span> 总结
领域规则抽象,思考了N久,真心就是(臣妾做不到啊...)。如果仅仅就为实现功能而写的代码,再进行重构抽象,现在感觉好难。只能是多看高质量代码,多积累,多练习了! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |