How to check if an array is palindrome in Kotlin
How to check if an array is palindrome in Kotlin.
Here's a step-by-step tutorial on how to check if an array is a palindrome in Kotlin:
Start by creating a function named
isPalindromethat takes an array as input and returns a Boolean value indicating whether the array is a palindrome or not.Inside the
isPalindromefunction, initialize two variablesstartandendwith the values 0 andarray.size - 1respectively. These variables will be used to iterate through the array from both ends.Create a while loop that runs as long as
startis less than or equal toend. This loop will compare the corresponding elements from both ends of the array.Inside the loop, compare
array[start]witharray[end]. If they are not equal, returnfalseas it means the array is not a palindrome.After comparing the elements, increment
startby 1 and decrementendby 1 to move towards the center of the array.If the loop completes without returning
false, it means all the corresponding elements from both ends of the array were equal. In this case, returntrueto indicate that the array is a palindrome.To test the
isPalindromefunction, create an array with some values and call the function, passing the array as an argument. Print the result to the console.
Here's an example implementation of the isPalindrome function:
fun isPalindrome(array: IntArray): Boolean {
var start = 0
var end = array.size - 1
while (start <= end) {
if (array[start] != array[end]) {
return false
}
start++
end--
}
return true
}
fun main() {
val array1 = intArrayOf(1, 2, 3, 2, 1)
val array2 = intArrayOf(1, 2, 3, 4, 5)
println(isPalindrome(array1)) // Output: true
println(isPalindrome(array2)) // Output: false
}
In this example, array1 is a palindrome because the elements are the same when read from left to right or right to left. On the other hand, array2 is not a palindrome because the elements are different when read in reverse.
Feel free to modify the code and test it with different arrays to check if they are palindromes.