본문 바로가기

Java Script/알고리즘 풀이

[알고리즘] 0826

문제 - Codewars_A needle in the Haystack (8kyu)

Write a function findNeedle() that takes an array full of junk but containing one "needle"
After your function finds the needle it should return a message (as a string) that says:"found the needle at position " plus the index it found the needle, so:

Example(Input --> Output)
["hay", "junk", "hay", "hay", "moreJunk", "needle", "randomJunk"]
--> "found the needle at position 5"
Note: In COBOL, it should return "found the needle at position 6"

문제 풀이

function findNeedle(haystack) {
    let needlePosition = haystack.indexOf("needle");
    return `found the needle at position ${needlePosition}`
}
  1. 배열 내에서 일치하는 문자열의 위치를 반환하는 indexOf 메소드를 이용해서 needle의 위치를 변수로 선언
  2. 이후 백틱 문자를 사용해서 문자열을 작성하고 needle 문자열의 위치는 needlePosition 변수를 불러오는 것으로 코드 작성

코드 비교

function findNeedle(array) {
for (var i=0; i<array.length; i++){
  if (array[i] === 'needle')
    return 'found the needle at position ' + i;
}
  1. for 구문의 조건 부분에 만약 array의 배열이 needle과 같으면 'found the needle at position ' + i;이라는 문자열을 반환하는 코드로 작성했다.

'Java Script > 알고리즘 풀이' 카테고리의 다른 글

[알고리즘] 0828  (0) 2023.08.28
[알고리즘] 0827  (0) 2023.08.27
[알고리즘] 0825  (0) 2023.08.25
[알고리즘] 0824  (0) 2023.08.24
[알고리즘] 0823  (0) 2023.08.23