C# 中的循环法
我在尝试用 C# 解决数学问题时遇到了问题(可能是由于睡眠不足!)。
假设我有一台饮料机,并且有三排空的可以装可乐。我手里有 17 罐可乐,我必须一次填满每一排。
例如...
传递 1:
将可乐添加到第 1 行。饮料 = 1
将可乐添加到第 2 行。饮料 = 1
将可乐添加到第 3 行。饮料 = 1
通过 2:
将可乐添加到第 1 行。饮料 = 2
将可乐添加到第 2 行。饮料 = 2
将可乐添加到第 3 行。饮料 = 2
...
通过 6
将可乐添加到第 1 行。饮料 = 6
将可乐添加到第 2 行。饮料 = 6
将可乐添加到第 3 行。饮料 = 5(此时没有更多饮料了)
出于某种原因,我完全迷失了。有人可以帮忙吗?
I'm having a problem (possibly due to lack of sleep!) where I'm trying to solve a maths problem in C#.
Let's say I have a drinks machine, and I have three empty rows that can be filled with Cola. I have 17 cans of Cola in my hand and I have to fill each row one at a time.
For example...
Pass 1:
Add Cola to Row 1. Drinks = 1
Add Cola to Row 2. Drinks = 1
Add Cola to Row 3. Drinks = 1
Pass 2:
Add Cola to Row 1. Drinks = 2
Add Cola to Row 2. Drinks = 2
Add Cola to Row 3. Drinks = 2
...
Pass 6
Add Cola to Row 1. Drinks = 6
Add Cola to Row 2. Drinks = 6
Add Cola to Row 3. Drinks = 5 (no more drinks left at this point)
For some reason, I'm completely lost. Can anyone help?!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
非常快速且无痛,并且只需要一个循环,而不是两个嵌套循环。您所需要的只是一点数学知识来获取数组的正确索引:
这将产生以下输出:
Pretty quick and painless, and only requires one loop, not two nested loops. All you need is a little bit of math to get the correct index of the array:
This produces this as output:
您可以计算每行将获得多少个罐头,而不是循环一次添加一个罐头:
Instead of looping to add a can at a time, you can calculate how many cans each row will get:
从臀部开始:
每行的饮料数量在
drinksInRow
中,按从 0 开始的行号索引。这比重复传递要快;基本上是 O(NUM_ROWS) [如果使用 Big-O 玩真正松散的话]。
Shooting from the hip:
number of drinks in each row is in
drinksInRow
, indexed by row number starting from 0.This is faster than doing repeated passes; basicallys its O(NUM_ROWS) [if playing really loose with Big-O].