【问题标题】:Get all subsequences of a sequence获取序列的所有子序列
【发布时间】:2019-05-08 18:28:53
【问题描述】:

我有一个数组,我需要所有可能的子数组(段或子序列),但空数组除外。这不是幂集,因为每个子数组只有在输入数组中连续的元素。

例如,对于输入new int[]{1,2,3},输出将是:

 new int[]{
   new int[]{1},
   new int[]{1,2},
   new int[]{1,2,3},
   new int[]{2},
   new int[]{2,3},
   new int[]{3}
 }

请注意,{1,3} 不存在,因为我不想要所有子集(幂集),只想要所有子序列。

我更喜欢使用单个 LINQ 语句的解决方案。

【问题讨论】:

  • stackoverflow.com/questions/19890781/… - 意识到这可能是一个骗局
  • 投反对票的人能否解释一下原因?
  • 我想这是因为您的问题是“我有一个要求,我希望有人为我编写代码”
  • @jdphenix 这个问题是要获得一个电源组(所有组合)。我想要的是所有子序列。
  • 在问题中提出正确的 C# 类型总是有用的。 {1,2,3} 不是有效的 C# 对象。

标签: c# linq


【解决方案1】:

假设您的来源是List(如果不是,请转换为List),那么您可以这样做:

var srcl = src.ToList();
var ans = Enumerable.Range(0, srcl.Count).SelectMany(start => Enumerable.Range(1, srcl.Count-start).Select(count => srcl.GetRange(start, count)));

使用自然的ArraySegment 扩展名:

public static class ArrayExt {
    public static IEnumerable<T> Segment<T>(this T[] src, int start, int count) => new ArraySegment<T>(src, start, count);
}

你可以让它返回一个数组数组:

var ans = Enumerable.Range(0, src.Length).SelectMany(start => Enumerable.Range(1, src.Length-start).Select(count => src.Segment(start, count).ToArray()));

List 通常是首选。

【讨论】:

    【解决方案2】:

    虽然 NetMage 的解决方案是正确的,但我最终还是编写了自己的扩展方法,使用 Array.Copy 来提高性能:

    /// <summary>
    /// Get all subsequences of the given sequence.
    /// {1,2,3}=>{{1,2},{1,2,3},{2,3}}
    /// </summary>
    public static T[][] GetAllSubsequences<T>(this IEnumerable<T> collection)
    {
        var list = (collection as T[]) ?? collection.ToArray();
        return list.SelectMany((x, i) => list.Skip(i).Select((z, j) =>
              {
                  var arr = new T[j + 1];
                  Array.Copy(list, i, arr, 0, j + 1);
                  return arr;
              })).ToArray();
    }
    

    【讨论】:

    • GetRange 真的存在性能问题吗?除了错误检查,List.GetRange 在内部实际上使用了Array.Copy
    猜你喜欢
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多