0%

codewar-找到中間值的index

題目:找到中間值的index

Example:

1
2
3
4
5
6
7
8
Test.describe("Basic Tests") do
Test.assert_equals(gimme([2, 3, 1]), 0, 'Finds the index of middle element')
Test.assert_equals(gimme([5, 10, 14]), 1, 'Finds the index of middle element')
Test.assert_equals(gimme([1, 3, 4]), 1, 'Finds the index of middle element')
Test.assert_equals(gimme([15, 10, 14]), 2, 'Finds the index of middle element')
Test.assert_equals(gimme([-0.410, -23, 4]), 0, 'Finds the index of middle element(Negative numbers)')
Test.assert_equals(gimme([-15, -10, 14]), 1, 'Finds the index of middle element (Negative numbers)')
end

解題方向:

  1. 我們必須先找到哪個數字是中間值,所以把這個陣列按照順序排列,因為題目都是只有三個元素,所以我就取第二個,然後給他一個變數以便後面取用。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    def gimme(arr)
    middle_element = (arr.sort)[1]
    end

    =>
    Finds the index of middle element - Expected: 0, instead got: 2
    Finds the index of middle element - Expected: 1, instead got: 10
    Finds the index of middle element - Expected: 1, instead got: 3
    Finds the index of middle element - Expected: 2, instead got: 14
    Finds the index of middle element(Negative numbers) - Expected: 0, instead got: -0.41
    Finds the index of middle element (Negative numbers) - Expected: 1, instead got: -10
  2. 接下來就是要找到這個值在原本的陣列中的位置

    1
    2
    3
    4
    def gimme(arr)
    middle_element = (arr.sort)[1]
    arr.index(middle_element)
    end