BoOk/멀티패러다임프로그래밍
[1장] 예제풀이
돈워리비햅삐
2025. 5. 26. 00:27
[문제 1] start, end 사이의 소수를 찾는 함수를 만들어보자.
조건 isPrime 함수는 소수를 판별합니다.
const isPrime = (n: number) => {
}
const findPrimeInRange = (start: number, end: number) => {
}
//결과값 예시
console.log(...findPrimeInRange(1, 100));
// [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
문제풀이
/*
소수찾는 함수 출처(수정쪽)
https://velog.io/@hyorimm/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EC%86%8C%EC%88%98-%EC%B0%BE%EA%B8%B0-in-JavaScript
*/
// 소수인지 판별하는 함수
const isPrime = (x: number) => {
for (let i = 2; i <= Math.sqrt(x); i++) {
if (x % i === 0) return false;
}
return true;
};
//소수일 때 이터레이터를 리턴
// 책에 있는 자연수 이터레이터로 생성하는 코드 복붙해서 시작함
const findPrimeInRange = (start: number, end: number) => {
let n = start; //순회를 시작할 숫자
return {
next(): IteratorResult<number> {
while (n <= end) {
const current = n++;
if (isPrime(current)) return { value: current, done: false }; //소수일 때 반환
}
return { value: undefined, done: false }; //end넘으면 종료
},
[Symbol.iterator]() {
return this;
},
};
};
[문제2] price 가 전 price 보다 높은 로그만 찍어야 합니다. 해당되는 id 를 모아서 뱉어냅니다.
로그로 찍으면 아래와 같이 결과가 나와야합니다.
const logs = [
{ id: 1000, price: 100 },
{ id: 2000, price: 101 },
{ id: 3000, price: 100 },
{ id: 4000, price: 102 },
{ id: 5000, price: 103 },
{ id: 6000, price: 105 },
]
function getUpPriceLogs(
iter: IteratorObject<{ id: number, price: number }>,
count: number
): number[] {
}
//결과값 예시
console.log(getUpPriceLogs(logs[Symbol.iterator](), 3))
// [1000, 2000, 4000]
문제풀이
//책에 있는 filter함수 구현 복붙해서 변형함
function getUpPriceLogs(
iter: IteratorObject<{ id: number; price: number }>,
count: number
): number[] {
let prev = -Infinity; //이전값 state
let result: number[] = []; //반환할 id를 모을곳
while (result.length < count) {
//count다 채우면 루프종료
const { value, done } = iter.next(); //현재값
if (done) break; //iter길이만큼만 루프
if (value.price > prev) {
//전값과 현재값 비교
result.push(value.id);
}
prev = value.price; //이전 가격 갱신
}
return result;
}