코드스테이츠 8주차

GunW·2019년 6월 25일
2

뭘해야할지 몰라서...이것저것 다 공부하고 있다...😂
오늘도 이것저것 본것들을 적어서 머리에 담으려 한다.


1. StopWatch

WEB에 간단한 스톱워치를 띄워보자.
화면에 시간을 표시할 0.00 과 시작버튼, 종료 버튼을 둔다.
addEventListenr로 각각을 구성한다.

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>스톱워치</title>
</head>
<body>
  <h1 id="display-time">0.00</h1>
  <input type="button" id="start-btn" value="시작">
  <input type="button" id="stop-btn" value="종료">
  <script>
    window.addEventListener("load", function() {
      const startBtn = document.querySelector("#start-btn");
      const stopBtn = document.querySelector("#stop-btn");
      const displayTime = document.querySelector("#display-time");
      let startTime, timer;
      init();
      
      // start action
      function start() {
        startBtn.onclick = null;
        stopBtn.onclick = stop;
        startTime = new Date();
        timer = setInterval(() => {
          let now = new Date();
          displayTime.innerText = ((now - startTime) / 1000).toFixed(2);
        }, 10);
      }

      // stop action
      function stop() {
        clearInterval(timer);
        startBtn.onclick = start;
      }

      // init
      function init() {
        startBtn.onclick = start;
      }
    })
  </script>
</body>
</html>

image.png


2. linear Search(선형 검색)

딱 들어만 봐도 효율이 나쁜 검색 방법이다.
처음부터 차례로 검사한다.
1억개를 검사할 때 최악의 경우 1억번째에 결과가 나온다...😅
쉬워보이지만 막상 만들면 어려우니 직접 만들어보아야 한다.
고차함수를 사용하면 끝까지 돌기때문에 고차함수는 사용하지않는다.

const linearSearch = (x, arr) => {
  let i = 0;
  let n = arr.length;
  while(i < n && arr[i] < x) {
    console.log(`arr[${i}] : ${arr[i]}`);
    i++;
  }
  return x === arr[i] ? i : null;
}

const array = [1,2,3,5,8,10,12,15,20,50,77,99];
console.log('RESULT : ' + linearSearch(20, array)); // 8
// arr[0] : 1
// arr[1] : 2
// ...
// arr[6] : 12
// arr[7] : 15
// RESULT : 8

3. binary search(이진 검색)

선형 검색을 공부해놓고 이진 검색을 안 할 수 없다.
1. 중앙값과 대상을 비교한다.
2. 같거나 작다면 최대를 중앙값으로 두고 다시 검색한다.
3. 보다 크다면 최소를 중앙값으로 두고 다시 검색한다.
4. 같아지면 해당 인덱스를, 아니면 null을 반환한다.

const binarySearch = (x, arr) => {
  let [lhs, rhs] = [0, arr.length - 1];
  while(lhs < rhs) {
    let center = Math.floor((lhs + rhs) / 2);
    x <= arr[center] ? (rhs = center) : (lhs = center + 1)
  }
  return x === arr[rhs] ? rhs : null;
}

const array = [1,2,3,5,8,10,12,15,20,50,77,99];
console.log(binarySearch(8, array));  // 4
console.log(binarySearch(50, array)); // 9
profile
ggit

0개의 댓글