【问题标题】:Distinct subsets from a set集合中的不同子集
【发布时间】:2011-06-01 17:53:27
【问题描述】:

我编写了一个扩展方法,它从位图中返回 YUV 值的二维数组,即:

public static YUV[,] ToYuvLattice(this System.Drawing.Bitmap bm)
{
    var lattice = new YUV[bm.Width, bm.Height];
    for(var ix = 0; ix < bm.Width; ix++)
    {
        for(var iy = 0; iy < bm.Height; iy++)
        {
            lattice[ix, iy] = bm.GetPixel(ix, iy).ToYUV();
        }
    }
    return lattice;
}

然后我需要提取具有相同 U 和 V 分量的集合。 IE。 Set1 包含所有 [item1;item2] 对,Set2 包含 [_item1;_item2] 对。所以我想获取列表列表。

public IEnumerable<List<Cell<YUV>>> ExtractClusters()
{            
    foreach(var cell in this.lattice)
    {
        if(cell.Feature.U != 0 || cell.Feature.V != 0)
        {
            // other condition to be defined
        }
        // null yet
        yield return null;
    }
} 

我从上面的代码开始,但我坚持使用不同值的条件。

【问题讨论】:

    标签: c# algorithm collections distinct


    【解决方案1】:

    听起来你有一个等价关系,你想对数据进行分区。通过等价关系,我的意思是:

    1. A r A
    2. A r B => B r A
    3. A r B 和 B r C => A r C

    如果这是你所拥有的,那么这应该可以工作。

    public static class PartitionExtension
    {
        static IEnumerable<List<T>> Partition<T>(this IEnumerable<T> source, Func<T, T, bool> equivalenceRelation)
        {
            var result = new List<List<T>>();
            foreach (var x in source)
            {
                List<T> partition = result.FirstOrDefault(p => equivalenceRelation(p[0], x));
                if (partition == null)
                {
                    partition = new List<T>();
                    result.Add(partition);
                }
    
                partition.Add(x);
            }
            return result;
        }
    }
    

    用法:

    return this.lattice
    .Where( c=> c.Feature.U != 0 && c.Feature.V != 0 )
    .Partition((x,y)=>
         x.Feature.U == y.Feature.U &&
         x.Feature.V == y.Feature.V);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多