如何重构涉及连续集的棘手逻辑?
这里的规则是,用户可以连续获得 10、20 和 30 次徽章。但用户不能连续获得多个徽章。我正在跟踪用户模型中的 consec 胜利。
例如,如果用户达到 10 连胜,则该用户将被授予 10 连胜徽章。如果用户连续 20 次,他/她会收到 20 次连续徽章。如果用户取得了 30 场连胜,则该用户将被授予 30 场连胜徽章。用户不应被授予三枚 10 连胜徽章 - 只能获得一枚 10 连胜徽章、一枚 20 连胜徽章和一枚 30 连胜徽章。
此外,如果用户达到 40 连胜,那么该用户应该被授予 10 连胜徽章。如果用户达到 50 分,那么他/她应该被授予 20 连胜徽章。如果用户达到 60 分,则应授予用户 30 连胜徽章。如果用户达到 70,则应奖励用户 10 连胜。我想你已经明白了这里的模式。 30 连胜奖杯是用户可以获得的最高奖杯。但用户可以无限连胜。
def check_win_streak(streak)
badge = 10
while badge < BADGE::MAX_STREAK_BADGE_SIZE do # MAX_STREAK_BADGE_SIZE = 30
if streak < badge then
break
end
if (streak % badge == 0) then
award_streak_badge(badge)
end
badge += 10
end
end
The rule at work here is that users can be awarded badges for a streak of 10, 20, and 30. But the user can't be awarded multiple badges for the same streak. I'm tracking consec wins in the user model.
For example, if the user hits a 10-streak, the user is awarded a 10-streak badge. If the user is on a 20-streak, he/she receives a 20-streak badge. If the user is on a 30-game win streak, the user is awarded a 30-streak badge. The user shouldn't be awarded three 10-streak badges -- only one 10-streak, one 20-streak, and one 30-streak.
Further, if the user reaches a 40-win streak, then the user should be awarded a 10-streak badge. If the user hits 50, then he/she should be awarded a 20-streak badge. If the user hits 60, the user should be award a 30-streak badge. If the user hits 70, the user should be awarded a 10-streak. I think you get the pattern here. A 30-streak trophy is the max a user can get. But the user can be on an infinite winning streak.
def check_win_streak(streak)
badge = 10
while badge < BADGE::MAX_STREAK_BADGE_SIZE do # MAX_STREAK_BADGE_SIZE = 30
if streak < badge then
break
end
if (streak % badge == 0) then
award_streak_badge(badge)
end
badge += 10
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
唐和兰迪给出了总体想法。这是完整的代码:
Don and Randy gave the general idea. Here is the complete code:
尝试MOD算术。
将条纹修改为 30 - 您将得到在每个 30 条带中重复的结果...
try MOD arithmatic.
mod the streak by 30 - and you will get results that repeat in each band of 30...
去除其余部分的模数,即
62 % 30 = 2
。然后进行除法得到30连胜的数量。Modulus to get rid of the rests i.e.
62 % 30 = 2
. Then there is division to get the number of 30 streaks.