继续 codewars 6级题。
大项目也在绝赞制作中~
行数破千完成小半。
公号里添加高清视频,需要做腾讯视频V认证,而个人申请比较麻烦。。。
所以这里只写题目和解题代码,不再添加讲解视频,点下面的链接看吧。
b站讲解视频链接:https://www.bilibili.com/video/av26025184/
腾讯讲解视频链接:https://v.qq.com/x/page/l0709r9zcza.html
今天的题目有点长。。。。。。。
而solution很短。
Introduction
Fish are an integral part of any ecosystem. Unfortunately, fish are often seen as high maintenance. Contrary to popular belief, fish actually reduce pond maintenance as they graze on string algae and bottom feed from the pond floor. They also make very enjoyable pets, providing hours of natual entertainment.
Task
In this Kata you are fish in a pond that needs to survive by eating other fish. You can only eat fish that are the same size or smaller than yourself. You must create a function called fish that takes a shoal of fish as an input string. From this you must work out how many fish you can eat and ultimately the size you will grow to.
Rules
-
Your size starts at 1
-
The shoal string will contain fish integers between 0-9
-
0 = algae and wont help you feed.
-
The fish integer represents the size of the fish (1-9).
-
You can only eat fish the same size or less than yourself.
-
You can eat the fish in any order you choose to maximize your size.
-
The bigger fish you eat, the faster you grow. A size 2 fish equals two size 1 fish, size 3 fish equals three size 1 fish, and so on.
-
Your size increments by one each time you reach the amounts below.
Increase your size Your size will increase depending how many fish you eat and on the size of the fish. This chart shows the amount of size 1 fish you have to eat in order to increase your size.
etc...
RETURNS
Return an integer of the maximum size you could be.
Example1
shoal = "11112222" = > 4 fish of size 1 = > 4 fish of size 2 You eat the 4 fish of size 1 ( 4* 1 = 4 ) which increases your size to 2
Now that you are size 2 you can eat the fish that are sized 1 or 2.
You then eat the 4 fish of size 2 ( 4*2 =8) which increases your size to 3
Example 2
shoal = " 111111111111 " = > 12 fish of size 1
You eat the 4 fish of size 1 ( 4*1 =4 ) which increases your size to 2
You then eat the remainding 8 fish of size 1 ( 8*1 =8 ) which increases your size to 3 Good luck and enjoy!
solution
#include <array>
int fish(std::string shoal) {
std::array<int, 10> Fishs;
Fishs.fill(0);
for (auto i : shoal) {
Fishs.at(i - '0')++;
}
Fishs.at(0) = 0;
int numFishToNext = 4, CurrentSize;
for (CurrentSize = 1; CurrentSize < 10;CurrentSize ++) { Fishs.at(CurrentSize) *= CurrentSize;
Fishs.at(CurrentSize) += Fishs.at(CurrentSize - 1);
if (Fishs.at(CurrentSize) >= numFishToNext) {
Fishs.at(CurrentSize)-=numFishToNext;
numFishToNext += 4;
continue;
}
break;
}
if (CurrentSize == 10) {
for (; Fishs.at(9) >= numFishToNext;
Fishs.at(9) -= numFishToNext, numFishToNext += 4, CurrentSize++);
}
return CurrentSize;
}
欢迎关注微信公众号:小霍编程