array = [[1, 2], [13, 14], [4, 5], [80, 30], [12, 14], [10, 90], [3, 2], [6, 9], [1, 5], [4, 5], [5, 9], [4, 3], [13, 12]]
//expected
output = [[1, 2], [13, 14], [4, 5], [80, 30], [10, 90], [3, 2], [6, 9], [4, 5], [5, 9], [4, 3], [13, 12]]
Think of the subarray,for example [1,2] will be a line connected from point 1 to point 2. Therefore, refering to above, since [1,2],[3,2],[4,3],[4,5],[4,3] means that it will connect to Point 1 to Point 5 because there is a line connected to Point 1 to 2,2 to 3,3 to 4, 4 to 5 and if the array contains its overall line combination that is Point 1 to Point 5, it will be filtered out from the array. This is done to filter out all short lines present with its node position in a long line. May I know the logic and the algorithm to solve this? Thank you for reading and have a nice day :)
I have tried the code below at https://codepen.io/Maximusssssu/pen/jOYXrNd?editors=0012:
The first part is to output all subarrays in ascending order for better view whereas for the second part,I have tried the include() method to check whether a node is present in the subarray and get its position.
array_ascending_arr = [];
for (let i = 0; i < array.length; i ) {
let subarrayy = array[i].sort(function(a, b) {
return a - b
});
array_ascending_arr.push(subarrayy);
}
console.log(array_ascending_arr) // output all subarrays in ascending order back into array
for (let k = 1; k < 5; k ) {
for (let m = 0; m < array.length; m ) {
for (let i = 1; i < 2; i ) {
if (array_ascending_arr[m].includes(k) == true) {
console.log(m)
}
}
}
console.log(".......")
}
CodePudding user response:
You could try for an adjacency list. My understanding of the algorithm is if two pairs share an edge they will combine to form a new edge until all sets are unique.
CodePudding user response:
I did this...
const array = [[1,2],[13,14],[4,5],[80,30],[12,14],[10,90],[3,2],[6,9],[1,5],[4,5],[5,9],[4,3],[13,12]];
console.log('output:\n', JSON.stringify( combination( array )))
function combination(arr)
{
let arrFilter = arr
.map(([a1,a2]) => [Math.min(a1,a2),Math.max(a1,a2)] )
.sort(([a1,a2],[b1,b2]) => ((a2-a1)-(b2-b1)) || (a1-b1) || (a2-b2) )
.reduce((r,[a1,a2]) =>
{
let group = r.grpN.find(g=>g.includes(a1) | g.includes(a2))
if (!group)
{
r.grpN.push([a1,a2])
r.res.push([a1,a2])
}
else if (group.includes(a1) ^ group.includes(a2))
{
if (group.includes(a1)) group.push(a2)
if (group.includes(a2)) group.push(a1)
r.res.push([a1,a2])
}
return r
},{grpN:[],res:[]})
.res;
return arr.filter(([p1,p2])=>arrFilter.some(([f1,f2])=>f1===Math.min(p1,p2) && f2===Math.max(p1,p2)))
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
.as-console-row::after { display: none !important; }