简体   繁体   中英

Grouping neighbouring entries with the same value in a 2d array

EDIT: I now realized the question was not appropriate for stack but I've gotten a lot of helpful advice anyway. Thanks everyone!

I have a 2d array and I want to group together neighbors of the same value. Using C# (working with unity).

Let's say I have this:

int[,] array {   
    0,0,0,0,0,0,1,0,0,0,  
    0,1,1,0,0,0,1,0,0,0,  
    0,1,0,0,0,0,0,0,0,0,  
    0,0,0,0,0,0,1,1,1,0,  
    0,0,0,0,0,0,1,1,1,0  
}

There are three "clusters" of 1:s. I want to add them to a dictionary with some variable for identification. So maybe first add the neighboring values to a list, add that list to a dictionary, clear the list and move onto the next cluster.

The columns and rows would be of equal length in the real thing.

I would also want the sorting method to accept arrays of various sizes so no hardcoded values. I parse the array from an XML document.

I've tried looking into Array.Sort but the resources I have found have been exclusively about sorting values in as/descending order. Just pointing me in the right direction, some some relevant web resources would be greatly appreciated!

I'm not going to give you the answer in full code since 1. you shouldn't be asking for it here and 2. you can definitely work it out yourself.

This is a good opportunity for you to whip out your pen and paper and figure out the algorithm. Lets say we want something similar to your task: just grouping the clusters of ones. The pseudocode might look like this.

  1. Create a list of clusters
  2. For each element in the grid, check if its a one.
  3. If it is a one, check if it has a neighbor that is part of a cluster. If so, add it to that cluster, else create a new cluster an add it.

If would then run through this on paper with a small example.

Once you have your desired algorithm, putting it into a dictionary and sorting it should be trivial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM