2017-04-12 1 views
0

자바 스크립트의 배열을 기반으로 요소가 속한 간격을 확인하는 방법을 찾을 수 없습니다. 파이썬에서 bisect.bisect_left의 동작을 원합니다. 다음은 몇 가지 샘플 코드입니다.JavaScript가 R의 findInterval() 또는 Python의 bisect.bisect_left와 같습니다.

import bisect 
a = [10,20,30,40] 
print(bisect.bisect_left(a,0)) #0 because 0 <= 10 
print(bisect.bisect_left(a,10)) #0 because 10 <= 10 
print(bisect.bisect_left(a,15)) #1 because 10 < 15 < 20 
print(bisect.bisect_left(a,25)) #2 ... 
print(bisect.bisect_left(a,35)) #3 ... 
print(bisect.bisect_left(a,45)) #4 

나는 구현하기가 쉽지만 바퀴를 다시 발명 한 이유는 무엇입니까?

+2

여기에 휠의 내 개인 재발입니다 _ "왜 바퀴를 다시 발명합니까?"- 아마도 "바퀴"는 아직 존재하지 않습니다;) –

답변

2

JavaScript에 내장 된 이분법 함수가 없으므로 직접 롤백해야합니다.

var array = [10, 20, 30, 40] 
 

 
function bisectLeft (array, x) { 
 
    for (var i = 0; i < array.length; i++) { 
 
    if (array[i] >= x) return i 
 
    } 
 
    return array.length 
 
} 
 

 
console.log(bisectLeft(array, 5)) 
 
console.log(bisectLeft(array, 15)) 
 
console.log(bisectLeft(array, 25)) 
 
console.log(bisectLeft(array, 35)) 
 
console.log(bisectLeft(array, 45)) 
 

 
function bisectRight (array, x) { 
 
    for (var i = 0; i < array.length; i++) { 
 
    if (array[i] > x) return i 
 
    } 
 
    return array.length 
 
}

0

동일한 크기의 간격으로 작동 이전에 허용 대답보다 더 빠른 방법은 다음과 같습니다 :

var array = [5, 20, 35, 50] 
 

 
//Intervals: 
 
//  <5: 0 
 
// [5-20): 1 
 
// [20-35): 2 
 
// [35-50): 3 
 
// >=50: 4 
 

 
var getPosition = function(array, x) { 
 
    if (array.length == 0) return; 
 
    if (array.length == 1) return (x < array[0]) ? 0 : 1; 
 
    return Math.floor((x - array[0])/(array[1] - array[0])) + 1 
 
} 
 

 
console.log(getPosition(array, 2)); //0 
 
console.log(getPosition(array, 5)); //1 
 
console.log(getPosition(array, 15));//1 
 
console.log(getPosition(array, 20));//2 
 
console.log(getPosition(array, 48));//3 
 
console.log(getPosition(array, 50));//4 
 
console.log(getPosition(array, 53));//4 
 

 
console.log("WHEN SIZE: 1") 
 
array = [5]; 
 
//Intervals: 
 
// <5: 0 
 
// >=5: 1 
 
console.log(getPosition(array, 3)); 
 
console.log(getPosition(array, 5)); 
 
console.log(getPosition(array, 6));

관련 문제