C
C#2y 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
Becquerel2y ago
this sounds very similar to the classic 'gaps and islands' problem often seen in SQL
Bread
Bread2y ago
I may be structuring the data wrong initially and is not gospel
Becquerel
Becquerel2y ago
a manual way to do it would be to loop through the entire collection with a 'currentStreak' and 'largestStreak' counters
Xymanek
Xymanek2y 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
Becquerel2y ago
increment current streak if current item is true, increment largestStreak if it's larger yeah, like that
Bread
Bread2y ago
I won't have access to SQL unfortunately, so that looks like a good idea
Xymanek
Xymanek2y ago
this would be definitely more complicated in SQL
Becquerel
Becquerel2y 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
Bread2y ago
yeah appreciate that, never heard it before so some nice reading Thanks folks!
Becquerel
Becquerel2y ago
you can use '/close' to end the thread now
Bread
Bread2y ago
let me steal the code first then I will
Accord
Accord2y ago
✅ This post has been marked as answered!
Bread
Bread2y ago
Oh it doesn't delete? awesome
Accord
Accord2y ago
✅ This post has been marked as answered!