我有一个任务是写一个从一个机器人开始的代码,我需要找出需要多少个月才能获得多达200个机器人。
条件:
从一个机器人开始,这个机器人收集材料需要2个月。有了这些材料,它可以建造3个机器人,每个月一个机器人。因此,一个机器人的周期是5个月。当然,新造的机器人也会收集2个月的材料,然后每个机器人制造3个机器人,以此类推……
我唯一的建议是它应该使用3个变量来完成。每个采集月2个,每个建筑月3个。
这是用Java完成的。提前感谢!
发布于 2012-09-11 16:05:21
我会以面向对象的方式解决这个问题。
我将创建一个带有公共方法workForAMonth()的Robot类,该方法可能返回一个新的robot或null。
主循环看起来像这样(伪代码):
create an empty List of robots
add one robot to it
while the list of robots has less than 200 entries
create a new list of the newly build robots
iterate the list of existing robots. for each robot:
call the workForAMonth method. When it returns a robot, append it to the list of newly build robots
append the newly build robots to the main list
add 1 to month
output monthworkForAMonth方法将如下所示:
increment the private month counter of this robot by 1
whe the counter is 5, set it back to 0
when the counter is 2 or larger, return a new Robot, else return null发布于 2012-09-11 17:26:21
一种可能的方法的提示:
因为这里最小的时间单位是1个月,所以让我们有一个时间变量,它一次递增1个月。
机器人将做什么取决于他目前在5个月周期中的哪个月。因此,我们跟踪每种状态下有多少个机器人,
当一个月过去了,处于不同状态的机器人数量将如何变化?机器人将进入下一个状态。可能(取决于他们的状态),他们还会生产出一种新的机器人。这个机器人将处于什么状态?
继续循环,直到拥有所需数量的机器人。
发布于 2012-09-11 16:11:02
既然你一点头绪都没有,我给你三个提示:
https://stackoverflow.com/questions/12365172
复制相似问题