Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Collection Group Related Elements
    text
    copied!<p>I have a collection of points, I am attempting to write a function which groups all related points. </p> <p>For example, related in this case means that an item contains the other:</p> <pre><code>int[] points = {2, 3, 4, 5, 6, 7, 2, 13, 14, 15, 32, 10, 237, 22, 46, 97} getDirectRelatives(2) = {2, 2, 32, 237, 22} </code></pre> <p>This works for returning all directly related elements. But I would like to group the indirectly related elements. Since 3 and 7 have indirect relations to 2, I want all of their direct relations too:</p> <pre><code>getAllRelatives(2) = {2, 2, 32, 237, 22, 3, 13, 32, 7, 97} </code></pre> <p>Any suggestions?</p> <p><strong>Update:</strong> Here's my implementation to make it more clear. This works but I'd like to know if it's the correct approach</p> <pre><code>public void getAllRelatives() { int groupIndex = 1; List&lt;int&gt; groupCollection = new List&lt;int&gt;(); bool flag = false; int[] marked = null; string currentOuter = null; string currentInner = null; List&lt;int&gt; current = new List&lt;int&gt;(); int[] points = {2, 4, 5, 6, 7, 2, 13, 14, 15, 32, 10, 237, 22, 46, 97}; //marked contains integers which identify which group an element belongs to for (x = 0; x &lt;= marked.Count - 1; x++) { marked(x) = 0; } //Two loops. The first iterates over the target point, the second iterates over each sub point //Once both loops are complete, groupCollection should contain the indexes for //all related integers //outerloop for (i = 0; i &lt;= points.Count - 1; i++) { current.Clear(); currentOuter = points(i).ToString; current.Add(i); //used to hold matches for current loop //inner loop, targetpoint + 1 to end for (x = i + 1; x &lt;= points.Count - 1; x++) { currentInner = points(x).ToString; if (currentInner.Contains(currentOuter)) { current.Add(x); } } //if this is the first iteration, flag as true, forces current items to marked if (marked(0) == 0) { flag = true; } //check if any current points are marked and flag if any of the elements are already in a group, add each found group to group collection for (x = 0; x &lt;= current.Count - 1; x++) { if (!(marked(current(x)) == 0)) { flag = true; groupCollection.Add(marked(current(x))); } } if (flag == true) { groupCollection.Add(groupIndex); //all relatives end up here } for (x = 0; x &lt;= current.Count - 1; x++) { marked(current(x)) = groupIndex; } groupIndex += 1; flag = false; } </code></pre> <p>}</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload