Last active
June 28, 2021 03:05
-
-
Save CarlaTeo/08f1291ddf1905559a59b012db40ea92 to your computer and use it in GitHub Desktop.
[JS] Count distinct triagles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Given a list of N triangles with integer side lengths, determine how many different triangles there are. | |
// Two triangles are considered to be the same if they can both be placed on the plane such that their vertices | |
// occupy exactly the same three points. | |
// https://leetcode.com/discuss/interview-question/922155/facebook-recruiting-portal-counting-triangles | |
function sortTriangle([a, b, c]) { | |
if(b > a) { | |
if(c > b) return [c, b, a]; | |
else if(c > a) return [b, c, a]; | |
else return [b, a, c]; | |
} | |
else { | |
if(c > a) return [c, a, b]; | |
else if(c > b) return [a, c, b]; | |
else return [a, b, c]; | |
} | |
} | |
function countDistinctTriangles(triangles) { | |
const triangleGraph = {}; | |
let distinctTrianglesCount = 0; | |
triangles.forEach(triangle => { | |
const [a, b, c] = sortTriangle(triangle); | |
let countIncrease = 0; | |
if(triangleGraph[a]){ | |
if(triangleGraph[a][b]){ | |
if(!triangleGraph[a][b][c]){ | |
countIncrease = 1; | |
triangleGraph[a][b][c] = true; | |
} | |
} | |
else { | |
countIncrease = 1; | |
triangleGraph[a][b] = {}; | |
triangleGraph[a][b][c] = true; | |
} | |
} | |
else { | |
countIncrease = 1; | |
triangleGraph[a] = {}; | |
triangleGraph[a][b] = {}; | |
triangleGraph[a][b][c] = true; | |
} | |
distinctTrianglesCount += countIncrease; | |
}); | |
return distinctTrianglesCount; | |
} | |
function countDistinctTriangles(arr) { | |
const ans = {}; | |
arr.forEach((tri) => { | |
const key = tri.sort((a,b) => a > b ? 1 : -1).join(""); | |
if(!ans[key]) ans[key] = true; | |
}); | |
return Object.keys(ans).length; | |
} | |
// --------------------------------------------------- Test --------------------------------------------------------// | |
console.log(countDistinctTriangles([[7, 6, 5], [5, 7, 6], [8, 2, 9], [2, 3, 4], [2, 4, 3]])); // 3 | |
console.log(countDistinctTriangles([[3, 4, 5], [8, 8, 9], [7, 7, 7]])); // 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment