6/29 codewars문제

samuel Jo·2023년 6월 29일
0

codewars

목록 보기
27/46

1. A Needle in the Haystack (8Kyu)

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"

function findNeedle(haystack) {
  // your code here
  for (i = 0 ; i < haystack.length ; i++){
    if(haystack[i]==="needle"){
      return "found the needle at position " + i
    }
  }
}

for문을 돌면서 매개변수에 들어온 배열이 needle이면 반환.


2.Two to One(7kyu)

DESCRIPTION:
Take 2 strings s1 and s2 including only letters from a to z. Return a new sorted string, the longest possible, containing distinct letters - each taken only once - coming from s1 or s2.

Examples:
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"

같은 매개변수의 String이 들어올 경우.
a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"


function longest(s1, s2) {
  return [...new Set(s1+s2)].sort().join("")
}

일단 중복되지않는 배열을 만들어주기 위해 Set을 사용.
근데 Set은 순서를 갖지않기에 [...new Set()] 사용. 그리고 난 후 정렬후 join()메서드로 배열의 모든 요소를 문자열로 변환.


3. Remove String Spaces(8kyu)

너무 간단해서 문제설명은 생략. 문자열의 모든 띄어쓰기를 제거하는 문제. 진짜 쉬어가는 문제였다.

function noSpace(x){
 return x.replaceAll(" ","");
}

4.Equal Sides Of An Array(6kyu)

장황하게 쓰여있는데 줄여말하자면
왼쪽의 합과 오른쪽의 합이 같을때를 나누는 기준점 N을 찾는 문제다.

요구사항으로는 0< arr < 1000,
여러개의 N이 나온다면 가장 낮은 index를 반환
만약 N이 될 조건이 안되면 return -1;을 반환.

이번문제는 조금 흥미롭게 접근했다.


function findEvenIndex(arr) {
  let left = 0; // 왼쪽 부분 배열의 합을 저장할 변수
  let right = arr.reduce((s, n) => s + n, 0); // 전체 배열의 합을 저장할 변수
  for (let i = 0; i < arr.length; i++) {
    right -= arr[i]; // 현재 인덱스의 값을 전체 합에서 제외
    if (left === right){ return i;} // 왼쪽 합과 오른쪽 합이 동일하면 인덱스 i를 반환
    left += arr[i]; // 현재 인덱스의 값을 왼쪽 합에 추가
  }
  return -1; // 조건을 만족하는 인덱스가 없는 경우 -1을 반환
}

주석을 통해 설명을 적어놨다. 꽤나 흥미롭게 푼것같다.

profile
step by step

0개의 댓글