Approximations
Approximations

Reputation: 11

Changing map string keys and values to int keys and values

I have two lists teachers and students and I have a map teachers_to_students. The keys and the values of the map are both strings. I want to transform it in the following manner: each key is replaced with the index of the teacher in the teachers list; each element of the value (it's a list) is replaced with the index of the student in the students list.

My attempt:

fun main() {
    val teachers_l = listOf("teacher1","teacher2","teacher3")
    val students_l = listOf("student1", "student2", "student3", "student4")

    val teachers_to_students = mapOf("teacher2" to listOf("student3"), "teacher1" to listOf("student1","student2"),  "teacher3" to listOf("student4"))

    val teachers_to_students_by_indices = mutableMapOf<Int,List<Int>>()

    for ((teacher,students) in teachers_to_students){
        val teacher_index = teachers_l.indexOf(teacher)

        val students_indices = mutableListOf<Int>()
        for (student in students){
            students_indices.add(students_l.indexOf(student))
        }
        teachers_to_students_by_indices[teacher_index] = students_indices 
    }
    print(teachers_to_students_by_indices)
}

Is there a more concise way to do it.

Thanks.

Upvotes: 0

Views: 501

Answers (2)

indexOf operation has O(N) compexity. It's inside a loop, so that's already O(N^2).

It's better to build indexes in advance, so that each look-up will cost only O(1):

val teachers_index = teachers_l.withIndex().associate { it.value to it.index }
val students_index = students_l.withIndex().associate { it.value to it.index }

Now, all transformation could be done with:

val teachers_to_students_by_indices = teachers_to_students.asIterable().associate { (teacher, students) ->
    teachers_index[teacher] to students.map { students_index[it] }
}

Upvotes: 1

IR42
IR42

Reputation: 9682

val teachers_to_students_by_indices = teachers_to_students.entries.associate { (key, value) ->
    val keyIndex = teachers_l.indexOf(key)
    val valueIndices =  value.map { students_l.indexOf(it) }
    keyIndex to valueIndices
}

Upvotes: 0

Related Questions