Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created May 4, 2025 17:34
Show Gist options
  • Save tatsuyax25/f845499e31b52b4faed6f1d664a95b56 to your computer and use it in GitHub Desktop.
Save tatsuyax25/f845499e31b52b4faed6f1d664a95b56 to your computer and use it in GitHub Desktop.
Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino can be rotated to be equal to another domino. Return the number of pairs (i,
/**
* Counts the number of equivalent domino pairs.
* Two dominoes are equivalent if they have the same numbers, regardless of order.
*
* @param {number[][]} dominoes - A list of domino pairs represented as 2-element arrays.
* @return {number} - The total number of equivalent domino pairs.
*/
var numEquivDominoPairs = function(dominoes) {
// If there are no dominoes, return 0
if (!dominoes || dominoes.length === 0) {
return 0;
}
let numPairs = 0; // Counter for equivalent pairs
let pairCountMap = new Map(); // Stores occurrences of normalized domino pairs
for (let [a, b] of dominoes) {
// Ensure the smaller number comes first to standardize the representation
const key = a < b ? `${a},${b}` : `${b},${a}`;
// Retrieve the current count of this pair (default to 0 if not found)
const currentCount = pairCountMap.get(key) || 0;
// Each new occurrence of the pair can form `currentCount` additional pairs
numPairs += currentCount;
// Update the pair count in the map
pairCountMap.set(key, currentCount + 1);
}
return numPairs;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment