View Full Version : complex grouping from array data

01-20-2009, 06:01 AM
I've been hitting the wall for the last 4 days on this one, and would appreciate any ideas that anyone may have regarding it.

Here's the overview:

Imagine a puzzle, where groups of pieces should theoretically be able to be snapped together outside of the final resting place. To make it simple to understand lets just say that it is a 5 x 5 grid labeled A - Y like this:
a b c d e
f g h i j
k l m n o
p q r s t
u v w x y

a should be able to snap to b and f but no others
b should be able to snap to a,c,and g but no others

OK now I have all the things worked out that I thought would be difficult, when a piece is layed down, it checks to see if that piece is in the correct place relative to the other pieces on the board, and i have it creating an array of all pieces that are in the correct spot, as well as a large multi demensional array containing all of the possible joins for each of the pieces (a connects to b or f, etc)

The problem lies when more than 2 clusters are correct on the board.
For an example, lets say that pieces a,b,c,u,v,w are all in the correct spot relative to each other, and an array is returned with these pieces.

I now need to loop through them all and determine that a,b,c belong together and u,v,w belong together. (and ideally create an array for each letter saying all pieces that should be joined to it.. example :
cluster[a] = b,c
cluster[b] = a,c

Here's he basic code I have been working with:

//clus= all pieces that are candidates to be clustered together
clusters[clus[i]] = [];
thiscluster = new Array();
//cluster = an array containing all of the possible matches for each piece
for(a in cluster[clus[i]]){
//in_array = same as php in_array funtion .. rreturns true if the item is found in the array
thiscluster[thiscluster.length] = cluster[clus[i]][a];
for(m in clus){
if(in_array(clus[i],cluster[clus[m]]) || in_array(clus[m],cluster[clus[i]])){
thiscluster[thiscluster.length] = clus[m];
clusters[clus[i]] = thiscluster;

I have a few 100 different variations on the above, but basically this has been my plan of attack, and it's ok for one or two pieces in a cluster, and only one cluster, but if there are multiple clusters/multiple pieces in each cluster, it gets really buggy...

It's one of those problems that seems so simple, yet once you dig into it, seems like it can not be done.

If anyone has any ideas on a better method to attack this, I would be forever grateful.