How to check if a matrix columns contain numbers without repetition in Kotlin

1 Answer

0 votes
fun columnsHaveUniqueNumbers(matrix: List<List<Int>>): Boolean {
    if (matrix.isEmpty() || matrix[0].isEmpty()) return true

    val numCols = matrix[0].size
    for (j in 0 until numCols) {
        val columnSet = mutableSetOf<Int>()

        for (row in matrix) {
            if (!columnSet.add(row[j])) return false // Duplicate found
        }
    }
    return true
}

fun main() {
    val matrix1 = listOf(
        listOf(1, 4, 7),
        listOf(2, 5, 8),
        listOf(3, 6, 9)
    )

    val matrix2 = listOf(
        listOf(1, 4, 7),
        listOf(2, 4, 8),
        listOf(3, 6, 9)
    )

    println("Matrix 1 columns have unique numbers: ${columnsHaveUniqueNumbers(matrix1)}")
    println("Matrix 2 columns have unique numbers: ${columnsHaveUniqueNumbers(matrix2)}")
}
 
 
  
/*
run:
  
Matrix 1 columns have unique numbers: true
Matrix 2 columns have unique numbers: false
  
*/

 



answered May 28, 2025 by avibootz
...