-
HackerRank 문제 해석, 풀이 Apple and Orange-Java scriptAlgorithm 2023. 4. 12. 18:24728x90
이 문제는 한국어로해도 알아먹기 어려운 문제였다
샘의집에는 열매가 많이 맺힌 사과나무와 오렌지나무가있습니다.
아래의 정보를 이용하여 사과와 오렌지가 각각 몇 개인지 도출하세요.
붉은색영역은 집을 의미한다. s는 시작점, t는 끝나는지점이다. 사과나무는 집의 왼쪽에위치, 오렌지나무는 오른쪽에.
과일이 나무에서 떨어질 때, 과일은 나무의 원점에서 x축을 따라 나무로부터 d 거리 단위로 떨어집니다.음수값은 왼쪽, 양수값은 오른쪽으로 과일이 떨어진 것을 의미함.
m개의 사과와 n개의 오렌지의 값이 주어진다. 몇개의 사과와 오렌지가 샘의 집(즉, [s,t]포함 범위)에 떨어질 것인지 구하시오.
예를 들어, 샘의 집이 s=7 t=10에 위치했을 때, 사과나무의 위치는 4이고 오렌지나무의 위치는 12임.
3개의 사과, 3개의 오렌지가 있음. 사과는 [2,3,-4]거리에, 오렌지는 [3 , -2, -4]단위에 떨어짐.
그러므로 사과의 나무로부터의 거리는 각각 [4+2, 4+3, 4+-4]=[6,7,0]
오렌지는 [12+3, 12+-2, 12+-4]= [15, 10, 8]
사과 하나와 오렌지 두개가 7-10사이(집영역) 포함되는 위치이기 때문에 1,2를 프린트하면 정답.일직선에 놓여있는 사과나무a, 집 s-t, 오렌지나무에서 사과나무에서 떨어진 사과배열 apples와 오렌지나무에서 떨어진 오렌지배열 oranges가 집의 영역(s~t)에 포함되면 그 개수를 각각 구하는 문제이다.
한국말로 해도 이해하기 어렵다.
파라미터가 너무 많아서 이해하기 좀 어려워서 콘솔로 정리하며 문제를 풀었다.
하드코딩장인의 코드 갑니다
function countApplesAndOranges(s, t, a, b, apples, oranges) { let appleTree = a; let orangeTree = b; let house = [s, t]; //이 변수는 사실 쓰이지 않는데 헷갈리지 않기 위해 만듦 let appleLocation = [...apples]; //빈배열로 둬도 좋음. [...apples].map((apple, i) => { appleLocation[i] = apples[i] + appleTree; }); //주어진 apples 매개변수가 사과나무와의 상대적인 위치이기 때문에 실제 사과의 위치를 구하기 위해 //apples배열을 map을 돌려 새로운 appleLocation배열을 만들었다. console.log(appleLocation); let orangeLocation = [...oranges]; [...oranges].map((orange, i) => { orangeLocation[i] = oranges[i] + orangeTree; }); console.log(orangeLocation); let answerApple = 0; let answerOrange = 0; appleLocation.map((e, i) => { if (s <= e && e <= t) { //집의 영역 s~t사이에 위치한 경우 answerApple += 1; //한개 추가 } }); orangeLocation.map((e, i) => { if (s <= e && e <= t) { answerOrange += 1; } }); console.log( "집:", house, "사과나무위치:", a, ",오렌지나무위치:", b, "사과떨어진어레이:", apples, ",오렌지떨어진어레이:", oranges ); console.log([answerApple, answerOrange]); return [answerApple, answerOrange]; } countApplesAndOranges(7, 11, 5, 15, [-2, 2, 1], [5, -6]);
chatGPT가 해준 코드 정리
function countApplesAndOranges(s, t, a, b, apples, oranges) { const fallenApples = apples.filter(apple => s <= a + apple && a + apple <= t); const fallenOranges = oranges.filter(orange => s <= b + orange && b + orange <= t); return [fallenApples.length, fallenOranges.length]; }
1. filter 함수를 사용하여 떨어진 사과와 오렌지를 찾고, 집의 범위 내에 있는지 검사하여 해당 사과와 오렌지의 개수를 세는 방법을 사용했습니다. 따라서 filter 함수는 배열에서 주어진 함수의 조건을 만족하는 요소들만 걸러내어 새로운 배열을 만드는 함수입니다. 간단히 말해서, 배열의 요소 중에서 조건에 맞는 요소들만 남겨두는 것입니다.
2. filter 함수를 사용하여 사과와 오렌지를 걸러낸 후, 해당 요소들의 개수를 length 속성을 사용하여 쉽게 계산할 수 있습니다. 이를 활용하여 최종 결과값인 [fallenApples.length, fallenOranges.length]를 반환합니다.형님으로 모셔야겠다ㅠ.ㅠ
근데 문제는 자꾸 오답처리가 되는 것이다....
해커랭크는 어떤 문제는 return값만 도출하면 정답처리가 되는데 어떤 문제는 return이 아니고 콘솔로 찍어야 정답이 된다.
이번 문제는 return으로 결론을 내면 아웃풋이 없다고 오류생기고 console.log(answerApple,answerOrange) 이렇게 찍었더니 또 정답으로 인정이 안됨
이것저것 해보다가 이렇게 각자 콘솔로 찍었더니 정답처리가 됐다.
console.log( answerApple)console.log( answerOrange)츠암나~~~~~
정답
'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', function(inputStdin) { inputString += inputStdin; }); process.stdin.on('end', function() { inputString = inputString.split('\n'); main(); }); function readLine() { return inputString[currentLine++]; } /* * Complete the 'countApplesAndOranges' function below. * * The function accepts following parameters: * 1. INTEGER s * 2. INTEGER t * 3. INTEGER a * 4. INTEGER b * 5. INTEGER_ARRAY apples * 6. INTEGER_ARRAY oranges */ function countApplesAndOranges(s, t, a, b, apples, oranges) { let appleTree = a; let orangeTree = b; let house = [s, t]; let appleLocation = [...apples]; [...apples].map((apple, i) => { appleLocation[i] = apples[i] + appleTree; }); let orangeLocation = [...oranges]; [...oranges].map((orange, i) => { orangeLocation[i] = oranges[i] + orangeTree; }); let answerApple = 0; let answerOrange = 0; appleLocation.map((e, i) => { if (s <= e && e <= t) { answerApple += 1; } }); orangeLocation.map((e, i) => { if (s <= e && e <= t) { answerOrange += 1; } }); console.log( answerApple) console.log( answerOrange) } function main() { const firstMultipleInput = readLine().replace(/\s+$/g, '').split(' '); const s = parseInt(firstMultipleInput[0], 10); const t = parseInt(firstMultipleInput[1], 10); const secondMultipleInput = readLine().replace(/\s+$/g, '').split(' '); const a = parseInt(secondMultipleInput[0], 10); const b = parseInt(secondMultipleInput[1], 10); const thirdMultipleInput = readLine().replace(/\s+$/g, '').split(' '); const m = parseInt(thirdMultipleInput[0], 10); const n = parseInt(thirdMultipleInput[1], 10); const apples = readLine().replace(/\s+$/g, '').split(' ').map(applesTemp => parseInt(applesTemp, 10)); const oranges = readLine().replace(/\s+$/g, '').split(' ').map(orangesTemp => parseInt(orangesTemp, 10)); countApplesAndOranges(s, t, a, b, apples, oranges); }
728x90'Algorithm' 카테고리의 다른 글
코딩테스트에 많이 쓰이는 자바스크립트 메서드 reduce(), 누적값, 중복요소 찾기 (0) 2023.04.19 HackerRank 문제 해석, 풀이 Grading Student - Java script (0) 2023.04.12 알고리즘 하드코딩 장인 [프로그래머스] 약수의 개수와 덧셈 (코드 간결화) (0) 2023.04.11 HackerRank 문제 해석, 풀이 Plus Minus- Java script (0) 2023.04.06 [알고리즘풀기] 프로그래머스 로그인성공? (0) 2023.03.30