Skip to content

Instantly share code, notes, and snippets.

@arnotes
Created May 7, 2021 02:48
Show Gist options
  • Save arnotes/d3799f00add710b1eab9ec599c1670a2 to your computer and use it in GitHub Desktop.
Save arnotes/d3799f00add710b1eab9ec599c1670a2 to your computer and use it in GitHub Desktop.
component labeling
using System;
using System.Collections.Generic;
using System.Linq;
namespace connected
{
class Program
{
static (int groupNum, char value) nullGroupVal = (-1, '*');
static char[,] data =
{
{ ' ',' ','#','#',' ',' ' },
{ ' ','#','#','#','#',' ' },
{ ' ',' ',' ',' ',' ',' ' },
{ ' ',' ',' ',' ',' ',' ' },
{ 'x',' ','h','h',' ',' ' },
{ 'x',' ','h','h',' ','b' },
};
static void Main(string[] args)
{
int groupNum = -1;
var pixelDC = new Dictionary<(int row, int col), (int groupNum, char value)>();
for (int row = 0; row < data.GetLength(0); row++)
{
for (int col = 0; col < data.GetLength(1); col++)
{
var value = data[row, col];
var leftNbor = pixelDC.ContainsKey((row, col-1))? pixelDC[(row, col-1)] : nullGroupVal;
var topNbor = pixelDC.ContainsKey((row-1, col))? pixelDC[(row-1, col)] : nullGroupVal;
if(value == leftNbor.value)
{
pixelDC[(row, col)] = (leftNbor.groupNum, value);
}else if(value == topNbor.value && value != leftNbor.value)
{
pixelDC[(row, col)] = (topNbor.groupNum, value);
}
if(value == leftNbor.value && value == topNbor.value)
{//if conflict
var duplicateGroup = topNbor.groupNum;
var pixelList = pixelDC.ToList();
pixelList = pixelList
.Where(px => px.Value.groupNum == duplicateGroup)
.ToList();
foreach (var px in pixelList)
{
pixelDC[px.Key] = (leftNbor.groupNum, px.Value.value);
}
}
if(value != leftNbor.value && value != topNbor.value)
{
groupNum++;
pixelDC[(row, col)] = (groupNum, value);
}
}
}
var finalList = pixelDC.ToList();
var groups = finalList
.GroupBy(x => x.Value.groupNum);
foreach (var group in groups)
{
Console.WriteLine(group.Key + "-------------------");
Console.WriteLine(group.ToList().Select(x => x.Value.value).ToArray());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment