How to find repeated rows of a matrix in Kotlin

1 Answer

0 votes
fun rowToString(row: List<Int>): String {
    return row.joinToString(",")
}

fun findRepeatedRows(matrix: List<List<Int>>) {
    val rowCount = mutableMapOf<String, Int>()

    for (row in matrix) {
        val pattern = rowToString(row)
        rowCount[pattern] = rowCount.getOrDefault(pattern, 0) + 1
    }

    println("Repeated Rows:")
    rowCount.filter { it.value > 1 }.forEach { (pattern, count) ->
        println("Row: [$pattern] - Repeated $count times")
    }
}

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

    findRepeatedRows(matrix)
}


 
/*
run:
 
Repeated Rows:
Row: [1,2,3] - Repeated 2 times
Row: [4,5,6] - Repeated 3 times
 
*/

 



answered May 24 by avibootz
...