티스토리 뷰

Algorithms

smallest distance

seoca 2021. 1. 16. 21:27

 

find the smallest distance in a given array. 

 

const arr = [1, 4, 2, 2, 1, 5];

function smallestDistance(arr) {
    const distanceArray = [];
    for (let i = 0; i < arr.length; i++) {
        if (arr.lastIndexOf(arr[i]) !== arr.indexOf(arr[i])) {
            let distance = arr.lastIndexOf(arr[i]) - arr.indexOf(arr[i]) //get the distance
            distanceArray.push(distance); //push to new array
        }
    }

    distanceArray.sort() //sort
    console.log(distanceArray[0]) //return first index
}

smallestDistance(arr); //1

 

'Algorithms' 카테고리의 다른 글

How many typos in a string  (0) 2021.02.12
CamelCase  (0) 2021.02.12
Cut the sticks  (0) 2020.12.18
Equalize the Array  (0) 2020.12.11
Invert Binary Tree  (0) 2020.11.30