计算连续天数的最佳方法

发布于 2024-10-27 12:29:36 字数 476 浏览 2 评论 0原文

在我的应用程序中,用户有很多手势。计算用户随后做了多少天手势的好方法是什么?

现在我正在这样做,如下所示,它按照我想要的方式工作。但显然它无法扩展。

class User < ActiveRecord::Base

  # ...

  def calculate_current_streak
    return 0 unless yesterday = gestures.done_on_day(Date.today-1)
    i = 0
    while gesture = self.gestures.done_on_day(Date.today - (i+1).days).first
      i += 1
    end
    i += 1 if gestures.done_on_day(Date.today).first
    i
  end

end 

谢谢!对于那些也可以只跟踪工作日的人来说,这是特别的一点:)

In my app a User has_many Gestures. What is a good way to calculate how many subsequent days the User has done Gestures?

Right now I'm doing it like below, and it works as I want it to. But clearly it doesn't scale.

class User < ActiveRecord::Base

  # ...

  def calculate_current_streak
    return 0 unless yesterday = gestures.done_on_day(Date.today-1)
    i = 0
    while gesture = self.gestures.done_on_day(Date.today - (i+1).days).first
      i += 1
    end
    i += 1 if gestures.done_on_day(Date.today).first
    i
  end

end 

Thanks! Special points to the one who can work in a way to only track business days too :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟─花易冷 2024-11-03 12:29:36

这样想:

条纹的长度等于自用户根本没有使用手势的最后一个(工作日)以来经过的(工作日)天数,对吗?

因此,解决方案归结为计算用户最近没有做出手势的一天。

为了最轻松地做到这一点,许多数据库管理员使用了一个技巧:他们创建包含所有日期的数据库表(例如,从 2000 年到 2100 年的所有日期)。该表只需包含日期字段,但您可以添加布尔字段来标记非工作日,例如周末和节假日。这样的表在很多查询中非常方便,而且您只需创建并填充它一次。 (这里有一篇关于此类表的更详细的文章,是为 MS SQL 编写的,但无论如何都很有洞察力。)

有了这个表(我们称之为日期),您可以使用类似(伪 SQL)的东西来计算你的预记录日期:

SELECT d.date
FROM dates d
LEFT JOIN gestures g ON d.date = g.date AND g.user_id = <put_user_id_here>
WHERE d.date < TODAY() AND g.date IS NULL AND d.work_day = TRUE
ORDER BY d.date DESC
LIMIT 1

Think about it this way:

The length of the streak is equivalent to the number of (business) days passed since the last (business) day the user didn't use gestures at all, right?

So the solution boils down to calculating most recent day that the user didn't make a gesture.

In order to do this most easily, there's a trick that lots of DB admins use: they create DB table with all dates (say, all the dates from year 2000 to year 2100). The table needs to have only date field, but you can throw in a Boolean field to mark non-working days, such as weekends and holidays. Such table can be handy in lots of queries, and you only have to create and fill it once. (Here's a more detailed article on such tables, written for MS SQL, but insightful anyway.)

Having this table (let's call it dates), you can calculate your pre-streak date using something like (pseudo-SQL):

SELECT d.date
FROM dates d
LEFT JOIN gestures g ON d.date = g.date AND g.user_id = <put_user_id_here>
WHERE d.date < TODAY() AND g.date IS NULL AND d.work_day = TRUE
ORDER BY d.date DESC
LIMIT 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文