Day 2: Fixed point

apomalyn

Xavier Chretien

Posted on January 7, 2020

Day 2: Fixed point
  • Difficulty: Easy
  • Programming language: Kotlin

Problem

A fixed point in an array is an element whose value is equal to its index.
Given a sorted array of distinct elements, return a fixed point, if one exists. Otherwise, return false.

For example:

  • Given [-6, 0, 2, 40], you should return 2
  • Given [1, 5, 7, 8], you should return false

My solution

This is an easy one and I don't want to go to a very complex solution. Let's just iterate the array and find the fixed point 😄

/**
 * Find each fixed point in a sorted array.
 *
 * @param array, sorted array
 * @return an list with each fixed points, the list is empty if there is no fixed points.
 */
fun findFixedPoint(array: IntArray): List<Int>{
    if(array[1] < array[0]) throw IllegalArgumentException("Array not sorted")

    val pointFixedFound = mutableListOf<Int>()
    for ((index, value) in array.withIndex()) {
        if(index == value){
            pointFixedFound.add(index)
        }
    }

    return pointFixedFound.toList()
}
Enter fullscreen mode Exit fullscreen mode

UPDATED VERSION

As

nickholmesde image

suggests in the comments, I didn't really follow the question asked. The question is to return A fixed point not all fixed points, so there is the updated version (thanks again to Nick Holmes).

fun findFixedPoint(array: IntArray): Int? {
    val pointFixedFound = mutableListOf<Int>()

    for ((index, value) in array.withIndex()) {
        if(index == value){
            return index
        } else if (value > index) {
            break
        }
    }
    return null
}
Enter fullscreen mode Exit fullscreen mode

The function returns null if there is no fixed point because I didn't find if this is possible to return an int or false in Kotlin, so I return null instead.

💖 💪 🙅 🚩
apomalyn
Xavier Chretien

Posted on January 7, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Day 3: From string to math
challenge Day 3: From string to math

January 8, 2020

Day 2: Fixed point
challenge Day 2: Fixed point

January 7, 2020

31 days of problems
challenge 31 days of problems

January 6, 2020