graph algorithm - Javascript Union Pairs Union Find -
i working on union finding. want group pairs of numbers based on whether 1 of indices shares number index of pair. so:
i have array of pairs such these:
pairs: [[1,3], [6,8], [3,8], [2,7]]
whats best way group them in unions such this:
[ [ 1, 3, 8, 6 ], [ 2, 7 ] ]
([1,3] , [3,8] go because share 3. group unites [6,8] because share 8. whats best way in javascript?
here other examples:
pairs: [[8,5], [10,8], [4,18], [20,12], [5,2], [17,2], [13,25],[29,12], [22,2], [17,11]] [ [ 8, 5, 10, 2, 17, 22, 11 ],[ 4, 18 ],[ 20, 12, 29 ],[ 13, 25 ] ]
edit here's method i'm using:
findunions = function(pairs, unions){ if (!unions){ unions = [pairs[0]]; pairs.shift(); }else{ if(pairs.length){ unions.push(pairs[0]) pairs.shift() } } if (!pairs.length){ return unions } unite = true while (unite && pairs.length){ unite = false loop1: (i in unions){ loop2: var length = pairs.length; (j=0;j<length;j++){ if (unions[i].includes(pairs[j][0])){ if (!unions[i].includes(pairs[j][1])){ unions[i].push(pairs[j][1]) pairs.splice(j, 1) j-=1; length-=1 unite = true }else{ pairs.splice(j, 1) j-=1 length-=1 } }else if (unions[i].includes(pairs[j][1])){ unions[i].push(pairs[j][0]) pairs.splice(j, 1) unite = true j-=1 length-=1 } } } } return findunions(pairs, unions) }
method:
finalarray = [], positions = {}; array.length j=i+1 array.length find match between arr[i] , arr[j] if match found pos = postion mapped either or j in positions add elements of arr[i] or arr[j] or both depending on pos. return finalarray
in method keep storing positions of arrays adding finalarray in positions object , later can use object find suitable position add elements of matched arrays in finalarray.
function mergearrays(finalarray, pos, subarray) { (var k = 0; k < subarray.length; k++) { if (finalarray[pos].indexof(subarray[k]) < 0) finalarray[pos].push(subarray[k]); } } function unionarrays(arr) { var finalarray = [arr[0]], positions = { 0: 0 }; (var = 0; < arr.length; i++) { (var j = + 1; j < arr.length; j++) { (var k = 0; k < arr[i].length; k++) { if (arr[j].indexof(arr[i][k]) >= 0) { if (i in positions) { mergearrays(finalarray, positions[i], arr[j]); positions[j] = positions[i]; } else if (j in positions) { mergearrays(finalarray, positions[j], arr[i]); positions[i] = positions[j]; } else { var pos = finalarray.length; finalarray.push([]); mergearrays(finalarray, pos, arr[i]); mergearrays(finalarray, pos, arr[j]); positions[i] = positions[j] = pos; } break; } } } if (!(i in positions)) { finalarray.push(arr[i]); positions[i] = finalarray.length - 1; } } return finalarray; } console.log(unionarrays([[1,3], [6,8], [3,8], [2,7]])); console.log(unionarrays([[8,5], [10,8], [4,18], [20,12], [5,2], [17,2], [13,25],[29,12], [22,2], [17,11]]));
Comments
Post a Comment