Skip to main content

How to check if an array is symmetric in Kotlin

How to check if an array is symmetric in Kotlin.

Here's a step-by-step tutorial on how to check if an array is symmetric in Kotlin:

Step 1: Understand the Problem

To check if an array is symmetric, we need to compare the elements of the array from both ends towards the middle. If the corresponding elements are equal, the array is symmetric; otherwise, it is not.

Step 2: Create a Function

Create a function called isSymmetric that takes an array as input and returns a Boolean value indicating whether the array is symmetric or not.

fun isSymmetric(array: Array<Int>): Boolean {
// implementation goes here
}

Step 3: Implement the Function

In the isSymmetric function, we need to iterate through the array and compare the corresponding elements from both ends. If any pair of corresponding elements is not equal, we can immediately return false as the array is not symmetric. If we reach the middle of the array without finding any non-equal pairs, we can return true as the array is symmetric.

fun isSymmetric(array: Array<Int>): Boolean {
for (i in 0 until array.size / 2) {
if (array[i] != array[array.size - i - 1]) {
return false
}
}
return true
}

Step 4: Test the Function

Create an array and call the isSymmetric function with different arrays to test its functionality.

fun main() {
val array1 = arrayOf(1, 2, 3, 2, 1)
val array2 = arrayOf(1, 2, 3, 4, 5)

println(isSymmetric(array1)) // Output: true
println(isSymmetric(array2)) // Output: false
}

In the above example, array1 is symmetric as the corresponding elements from both ends are equal (1 = 1, 2 = 2, 3 = 3). Therefore, the output is true. However, array2 is not symmetric as the corresponding elements are not equal (1 != 5). Hence, the output is false.

Step 5: Additional Considerations

  • The isSymmetric function only works for arrays of elements that can be compared using the != operator. If you are working with arrays of custom objects, you may need to override the equals function or implement a custom comparison logic.
  • The isSymmetric function can be used with arrays of any size, as long as the elements are comparable.
  • You can modify the isSymmetric function to work with different types of arrays (e.g., Array<String>, Array<Double>) by changing the function parameter type.

That's it! You now have a step-by-step tutorial on how to check if an array is symmetric in Kotlin.