Groups | Blog | Home
all groups > flash actionscript > may 2005 >

flash actionscript : Intersect arrays


Balancin
5/15/2005 12:00:00 AM
Im making a game and necessary of a function to intersect two arrays,
however, in the flash (as2) does not exist in the manual nothing speaking on
this and I did not obtain to make a generic function, whats can I make?

Jeckyl
5/16/2005 12:00:00 AM
what exactly do you mean by "intersect"
--
Jeckyl

kglad
5/16/2005 12:00:00 AM
function intersectA(a1,a2){
iA=new Array();
for(var ivar=0;ivar<a1.length;ivar++){
for(var jvar=0;jvar<a2.length;jvar++){
if(a1[ivar]==a2[jvar]){
iA.push(a2[ivar]);
}
}
}
return iA;
Balancin
5/16/2005 12:00:00 AM
sorry =/

my arrays:

cardsArray =
[11,11,9,9,12,12,19,19,10,10,17,17,3,3,6,6,18,18,16,16,8,8,5,5,7,7,20,20,15,15,14,14]
arraycartas = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

with your function:

function intersectA(a1,a2){
iA=new Array();
for(var ivar=0;ivar<a1.length;ivar++){
for(var jvar=0;jvar<a2.length;jvar++){
if(a1[ivar]==a2[jvar]){
iA.push(a2[ivar]);
}
}
}
return iA;
}

trace(intersectA(arraycartas,cardsArray));
//result
9,9,12,12,12,12,19,19,19,19,10,10,10,10,17,17,17,17,3,3,6,6,6,6,18,18,18,18,16,16,16,16

I wanted that I returned for example from these examples of mine arrays:
iA = [1, 3, 9, 16, 17]

"kglad" <webforumsuser@macromedia.com> escreveu na mensagem
news:d69ajp$bbo$1@forums.macromedia.com...
[quoted text, click to view]

Balancin
5/16/2005 12:00:00 AM
example:
arrays:
a[2,3,5,1];
b[1,2,3,5, 4, 0]
i need this result[0, 4]


"Jeckyl" <Jeckyl@Hyde.com> escreveu na mensagem
news:d697th$8c3$1@forums.macromedia.com...
[quoted text, click to view]

Jeckyl
5/16/2005 12:00:00 AM
That's not an intersection .. intersection is the set (array) or things that
is common.

You are after a difference (what is in one that is not in the other)

function isElementOf(e,a) {
for ( var j in a ) {
if (a[j] == e) {
return true;
}
}
}
function difference(a,b) {
var c = new Array;
for ( var j in a ) {
if (! isElementOf(a[j],b)) {
c.push(a[j]);
}
}
for ( var j in b ) {
if (! isElementOf(b[j],a)) {
c.push(b[j]);
}
}
return c;
}
var a = [2,3,5,1];
trace(a);
var b = [1,2,3,5, 4, 0]
trace(b);
var result = difference(a,b);
trace(result);

You may be better using objects instead. more efficient for sets than arrays
as you don't need to search them to see if something is an element eg

function differenceSet(a,b) {
var c = new Object;
for ( var e in a ) {
if (! b[e]) c[e] = true;
}
for (var e in b) {
if (! a[e]) c[e] = true;
}
return c;
}
function traceSet(a) {
var s = "";
for ( var e in a ) {
if (s != "") s = s + ",";
s = s + e;
}
trace(s);
}
var a = new Object;
a[2] = a[3] = a[5] = a[1] = true;
traceSet(a);
var b = new Object;
b[1] = b[2] = b[3] = b[5] = b[4] = b[0] = true;
traceSet(b);
var result = differenceSet(a,b);
traceSet(result);

--
All the best
Jeckyl

AddThis Social Bookmark Button