Kotlin - How to check if a char is present in a matrix?

Viewed 98

Only for context: I am trying to implement Playfair Cipher. It would be really helpful if you take a look at Playfair Cipher to understand my problem.

This program is just for some background:

fun main(){
    println("Enter the message:")
    var message:String = readLine()!!.toUpperCase()
    println("Enter the key:")
    var key:String = readLine()!!.toUpperCase()

    var cipTable = Array(5){ Array(5){'X'}}

    var j=0; //to iterate througm my key

    for(innerArray in cipTable){
        for(i in innerArray.indices){
            if(key[j++] !in cipTable)
                innerArray[i]+=key[j]
            
            if(j==key.length) break
        }
    }
}

My main issue is with this part:

for(innerArray in cipTable){
        for(i in innerArray.indices){
            if(key[j++] !in cipTable)

I wanted to check if the key that I am going to insert in the matrix is already present in it or not. I also cannot use innerArray instead of cipTable as it would only check for char in the same row. Is there any way I can check if a char is present or not in the entire matrix?

For eg.:

fun main(){
    var result = arrayOf(
            intArrayOf(3, 2, 4),
            intArrayOf(6, 7, 9),
            intArrayOf(12, 11, 23)
    )
    
    //To check if 2 is present in the entire matrix/table
    if(result.any { 2 !in it}) println("not present") else print("present")
}

Can you tell me what is wrong in this code because the output is not expected. Also is there any way I can use forEach for the same.

2 Answers

If I understand correctly, you want this for loop to result in a true or false based on whether any inner array has the same sequence and number of chars as the key String.

First of all, the inner array should be a CharArray instead of an Array<Char>, to avoid boxing.

val cipTable = Array(5) { CharArray(5) { 'X' } }

Then you can use all and contentEquals to check if any of the inner CharArrays are a match for the key.

val charArrayKey = key.toCharArray()
val isKeyInTable = cipTable.any { it.contentEquals(charArrayKey) }

If you want to skip the step of converting the key to a CharArray, you can manually check it like this:

val isKeyInTable = 
    cipTable.any { it.size == key.length && it.withIndex().all { (i, c) -> c == key[i] } }

I guess one way is to use extensions.

fun Array<IntArray>.has(x:Int):Boolean{
    for(innerArray in this){
        if(x in innerArray)
            return true
    }
    return false
}

fun main(){
    var result = arrayOf(
            intArrayOf(3, 2, 4),
            intArrayOf(6, 7, 9),
            intArrayOf(12, 11, 23)
    )

    //To check if 43 or 4 is present in the entire matrix/table
    if(result.has(43)) println("present") else println("not present")
    if(result.has(4)) println("present") else println("not present")
}
Related