/*
At each index of the row, check if there's a corresponding key ("column") in the map.
If there is, push this value into that "column".
If there's not, create the "column" for this row index and set its first value to this value.
Finally, convert the Map back to the original nested-Array structure
with some clever shorthand: brackets around the spread operator.
*/
function pivot(table) {
console.log('pivoting table!')
const rotated = new Map()
for (row of table) {
row.forEach((v, i) => rotated.get(i) ? rotated.get(i).push(v) : rotated.set(i, [v]))
}
return [...rotated.values()]
}
/*
For each element in the array, check to see if we've "seen" the value yet.
If yes, increase the count in the map for this value
If no, create a new key in the map for this value, and start counting.
After collecting counts, make a Set of the counts, which will keep only unique values.
If all the element counts are equal, this Set's size will be 1.
If all the element counts weren't equal, the Set will be larger than 1.
*/
function areElementCountsUnequal(arr) {
const counts = new Map()
arr.forEach(v => counts.get(v) ? counts.set(v, counts.get(v) + 1) : counts.set(v, 1))
const uniqueElementCounts = new Set([...counts.values()])
return uniqueElementCounts.size !== 1
}
function game(table) {
for (row of table) {
if (areElementCountsUnequal(row)) {
console.log(`row unequal: ${row}`)
return 'false'
}
}
const tablePivoted = pivot(table)
for (col of tablePivoted) {
if (areElementCountsUnequal(col)) {
console.log(`col unequal: ${col}`)
return 'false'
}
}
// we must not have found any unequal ones!
return 'true'
}
const inputTable1 = [
["1","2","1","2"],
["2","1","1","2"],
["2","2","1","1"],
["1","1","2","2"]
]
const result1 = game(inputTable1)
console.log(result1)
console.log('---- next game ----')
const inputTable2 = [
["1","3","1","2","3","2"],
["2","1","1","2","3","2"],
["2","2","1","1","1","2"],
["1","1","2","2","1","2"]
]
const result2 = game(inputTable2)
console.log(result2)