► JS Algorithm/Programmers

[Programmers] JavaScript 알고리즘 | Lv.0 가까운 수

다람트리 2024. 1. 18. 20:07
반응형

🔒 문제 설명

정수 배열 array 정수 n 매개변수로 주어질 , array 들어있는 정수  n 가장 가까운 수를 return 하도록 solution 함수를 완성해주세요.


🔒 제한사항  

  • 1 ≤ array의 길이 ≤ 100
  • 1 ≤ array의 원소 ≤ 100
  • 1 ≤ n ≤ 100
  • 가장 가까운 수가 여러 개일 경우 작은 수를 return 합니다.

🔒 입출력 예

array n result
[3, 10, 28] 20 28
[10, 11, 12] 13 12

🔒 입출력 예 설명

입출력 예 #1

  • 3, 10, 28 중 20과 가장 가까운 수는 28입니다.

입출력 예 #2

  • 10, 11, 12 중 13과 가장 가까운 수는 12입니다.

 

공지 - 2023 3 29 테스트 케이스가 추가되었습니다. 기존에 제출한 코드가 통과하지 못할 수도 있습니다.


 

🔐 solution of mine

Array.sort()

Array.indexOf()

Math.abs()

  const solution = (array, n) => {
    let sorted = [...array, n].sort((a, b) => a - b);
    let myIdx = sorted.indexOf(n);

    if (sorted[0] === n) return console.log(sorted[1]);
    if (sorted[array.length] === n)
      return console.log(sorted[array.length - 1]);

    return console.log(
      Math.abs(sorted[myIdx] - sorted[myIdx - 1]) <=
        Math.abs(sorted[myIdx] - sorted[myIdx + 1])
        ? sorted[myIdx - 1]
        : sorted[myIdx + 1]
    );
  };

  //---

  solution([3, 10, 28], 20); // expected output: 28
  solution([10, 11, 12], 13); // expected output: 12

  solution([10, 11, 12], 9); // expected output: 10
  solution([9, 11, 12], 10); // expected output: 9
  solution([6, 7, 9], 8); // expected output: 7
  solution([2, 3, 4], 1); // expected output: 2
  solution([3, 1], 2); // expected output: 1

워우.. 생각치 못한 다양한 케이스들이 나와가지고

꽤나 난항이여따 ㅜㅜ

'질문하기' 댓글들보면서 하나씩 풀어나갔다 (아날로그하게... 하나하나 조건식으로 하핳)

 

이번문제는 풀이들도 너무 어려워땁 ;;;

 


 

🔐 solution of others 

Array.reduce()

Math.abs()

Math.min()

 

  const solution = (array, n) =>
    console.log(
      array.reduce((a, c) =>
        Math.abs(n - a) === Math.abs(n - c)
          ? Math.min(a, c)
          : Math.abs(n - a) < Math.abs(n - c)
          ? a
          : c
      )
    );

  solution([3, 10, 28], 20); // expected output: 28
  solution([10, 11, 12], 13); // expected output: 12

  solution([10, 11, 12], 9); // expected output: 10
  solution([9, 11, 12], 10); // expected output: 9
  solution([6, 7, 9], 8); // expected output: 7
  solution([2, 3, 4], 1); // expected output: 2
  solution([3, 1], 2); // expected output: 1
 

 


 

반응형