코드로 우주평화

Find the middle element 본문

나는 이렇게 학습한다/Algorithm & SQL

Find the middle element

daco2020 2022. 3. 9. 11:45
반응형

Description:

As a part of this Kata, you need to create a function that when provided with a triplet, returns the index of the numerical element that lies between the other two elements.

The input to the function will be an array of three distinct numbers (Haskell: a tuple).

For example:

gimme([2, 3, 1]) => 0

2 is the number that fits between 1 and 3 and the index of 2 in the input array is 0.

Another example (just to make sure it is clear):

gimme([5, 10, 14]) => 1

10 is the number that fits between 5 and 14 and the index of 10 in the input array is 1.

 

 

 

Solution:

1. Copy the 'triplet' array and sort it.
2. Find the middle element of the sorted array.
3. Find the index of the original array with the found element and return it.

 

function gimme (triplet) {
  return triplet.indexOf(triplet.slice().sort((a, b)=>{return a - b})[1])
}

 

 

 

반응형

'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

Maximum Length Difference  (0) 2022.03.11
Testing 1-2-3  (0) 2022.03.10
Highest and Lowest  (0) 2022.03.08
Who likes it?  (0) 2022.03.07
Abbreviate a Two Word Name  (0) 2022.03.06