Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
843 B
2
Indexable
Never
IEnumerable<Post> MergePosts(IReadOnlyList<List<Post>> list)
{
    var res = new List<Post>();
    var ptr = new int[list.Count];

    for (var i = 0; i < list.Count; i++)
    {
        ptr[i] = list[i].Count - 1;
    }

    while (true)
    {
        var index = 0;
        Post? adding = null;
        for (var i = 0; i < ptr.Length; i++)
        {
            if (ptr[i] < 0) continue;

            var post = list[i][ptr[i]];

            if (adding is null ||
                DateTime.Compare(post.CreatedAt, adding.CreatedAt) is var c && c == 1 ||
                (c == 0 && post.Id > adding.Id))
            {
                adding = post;
                index = i;
            }
        }

        if (adding is null) break;

        ptr[index]--;
        res.Add(adding);
    }

    return res;
}