gpt4 book ai didi

在一周中找到连续几天的算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:18:59 24 4
gpt4 key购买 nike

用户可以从列表中选择任意数量的工作日。算法应找到最长的连续选定日期组。如果小组跨越两周,则开始日可以在结束日之后。如果再简单点,只需要检测至少3天的一组即可。越过周边界,这使得最多一组。 (一周内不能有两组3天不相连。)

例如,如果用户从列表中选择星期一、星期二、星期三和星期六,则显示应该类似于“星期一-星期三和星期六”。

另一个例子是:Wed, Fri, Sat, Sun, Mon -> "Wed, Fri-Mon"。

是否有一个有效的算法,最好是用 C# 或类似的语言?我的 C# hackwork 现在已经超过一页(包括一些评论),但仍未完成。

最佳答案

使用this answer , 略有变化:

使用 dtb 的修改版本的 GroupAdjacentBy 接受一个 minCount 作为参数:

public static IEnumerable<IEnumerable<T>> GroupAdjacentBy<T>(
this IEnumerable<T> source, Func<T, T, bool> predicate, int minCount)
{
using (var e = source.GetEnumerator())
{
if (e.MoveNext())
{
var list = new List<T> { e.Current };
var pred = e.Current;
while (e.MoveNext())
{
// if adjacent, add to list
if (predicate(pred, e.Current))
{
list.Add(e.Current);
}
else
{
// otherwise return previous elements:
// if less than minCount elements,
// return each element separately
if (list.Count < minCount)
{
foreach (var i in list)
yield return new List<T> { i };
}
else
{
// otherwise return entire group
yield return list;
}

// create next group
list = new List<T> { e.Current };
}
pred = e.Current;
}
yield return list;
}
}
}

并更改 GroupAdjacentBy 的条件以在周转换时分组:

// week starts with Monday, so this should
// represent: Wed, Fri, Sat, Sun, Mon
int[] array = new int[] { 1, 2, 4, 5, 6, 0 };

Func<int, int, bool> adjacentCriteria = (x, y) => (x+1==y) || (x==6 && y==0);

string result = string.Join(", ", array
.GroupAdjacentBy(adjacentCriteria, 3)
.Select(g => new int[] { g.First(), g.Last() }.Distinct())
.Select(g => string.Join("-", g)));

Console.WriteLine(result); // output: 1, 2, 4-0

关于在一周中找到连续几天的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8853102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com