본문 바로가기
알고리즘/Codewars

[Codewars] A Needle in the Haystack (8 kyu) / JavaScript

by fluss 2023. 1. 4.

https://www.codewars.com/kata/56676e8fabd2d1ff3000000c

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Can you find the needle in the haystack?

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 index = -1;
  for(let i = 0; i < haystack.length; i++){
    if(haystack[i] === 'needle') index = i;
  }
  return "found the needle at position " + index;
}

댓글