2009-10-29 18 views

Répondre

2

// éditer: testé et fonctionne

function product(set) { 
    if(set.length < 2) 
     return set[0]; 
    var head = set.shift(), p = product(set), r = []; 
    for(var j = 0; j < head.length; j++) 
     for(var i = 0; i < p.length; i++) 
      r.push([head[j]].concat(p[i])); 
    return r; 
} 

var set = [ 
    [ "a", "b", "c"], 
    [ "D", "E" ], 
    [ "x" ] 
]; 

var p = product(set); 
for(var i = 0; i < p.length; i++) 
    document.write(p[i] + "<br>"); 
+0

je vous remercie beaucoup! J'ai su que je devais recurse quelque part mais juste ne pourrais pas trouver le modèle. –

+0

Ce code ne sera pas exécuté: il manque) à deux endroits. –

0

méthode Essayez concat:

var newArr=[]; 

for(var i=0; i< arr.length; i++) 
{ 
    newArr = newArr.concat(arr[i]); 
} 
+0

qui vient de produire [ "a", "b", "c", "d", "e"] –

+0

Désolé ma faute, je ne vois pas la sortie que vous vouliez :) symptôme du programmeur. – TheVillageIdiot

1

Cela fonctionne:

<html><body><script> 
var to_join = [ ["a", "b"], ["c", "d"], ["e"] ]; 
var joined = to_join[0]; 
for (var i = 1; i < to_join.length; i++) { 
    var next = new Array(); 
    var ends = to_join[i]; 
    for (var j = 0; j < ends.length; j++) { 
     for (var k = 0; k < joined.length; k++) { 
      next.push (joined[k]+ " " + (ends[j])); 
     } 
    } 
    joined = next; 
} 
alert (joined); 
</script></body></html> 
+0

Cela fonctionnerait encore mieux si vous fermiez l'étiquette du corps;] –

+0

Merci pour votre correction. –