C
C#3y ago
Bread

Get longest consecutive date 'streak' [Answered]

I'm trying to figure out a nice way of getting a date-streak from a list of objects which will have activities on them. The premise to the problem is, each user records their 'excercise' which can be multiples per day. I don't care about anything other than some acceptence criteria (namely, duration of the exercise) but I can group these effectively into some structure I assume of:
[date] : [true/false]
[date] : [true/false]
This would indicate if the user has completed an activity on that date. Where I'm struggling is to then calculate the streak of dates (the largest streak) in that full list, ie:
1st : true
2nd : false
3rd : true
4th : true
5th : false
6th : true
7th : false
1st : true
2nd : false
3rd : true
4th : true
5th : false
6th : true
7th : false
Here the users top 'streak' is going to be 2, as completed on the 3rd and 4th
14 Replies
Becquerel
Becquerel3y ago
this sounds very similar to the classic 'gaps and islands' problem often seen in SQL
Bread
BreadOP3y ago
I may be structuring the data wrong initially and is not gospel
Becquerel
Becquerel3y ago
a manual way to do it would be to loop through the entire collection with a 'currentStreak' and 'largestStreak' counters
Xymanek
Xymanek3y ago
int maxStreak = 0;
int currentStreak = 0;

foreach (bool status in days)
{
if (status)
{
currentStreak++;
if (currentStreak > maxStreak) maxStreak = currentStreak;
}
else
{
currentStreak = 0;
}
}
int maxStreak = 0;
int currentStreak = 0;

foreach (bool status in days)
{
if (status)
{
currentStreak++;
if (currentStreak > maxStreak) maxStreak = currentStreak;
}
else
{
currentStreak = 0;
}
}
Becquerel
Becquerel3y ago
increment current streak if current item is true, increment largestStreak if it's larger yeah, like that
Bread
BreadOP3y ago
I won't have access to SQL unfortunately, so that looks like a good idea
Xymanek
Xymanek3y ago
this would be definitely more complicated in SQL
Becquerel
Becquerel3y ago
yeah, i'm not suggesting to use SQL, just giving you a name you can google to look around for other ideas if necessary
Bread
BreadOP3y ago
yeah appreciate that, never heard it before so some nice reading Thanks folks!
Becquerel
Becquerel3y ago
you can use '/close' to end the thread now
Bread
BreadOP3y ago
let me steal the code first then I will
Accord
Accord3y ago
✅ This post has been marked as answered!
Bread
BreadOP3y ago
Oh it doesn't delete? awesome
Accord
Accord3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server