JavaScript - LeetCode Random Algorithm Test(14)

먹보·2023년 3월 29일
0

1. Nim Game (No.0292)

문제 설명

You are playing the following Nim Game with your friend:

  • Initially, there is a heap of stones on the table.
  • You and your friend will alternate taking turns, and you go first.
  • On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.
  • The one who removes the last stone is the winner.

Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false.

해석

베스킨라빈스 31게임을 생각해보면 된다.

차이는 31이 아닌 랜덤 숫자 n이 주어진다는 것이고, 2명이서 플레이하며 항상 내가 먼저 시작하는 것이다.

이 때 숫자 n이 주어졌을 때 내가 해당 게임을 이길 수 있으면 true를 아니라면 false를 반환하는 함수를 구현해주세요.

예제

코드

function canWinNim(n: number): boolean {
  return n % 4 != 0;
};

🗒️코멘트

5부터 10까지 해보면 4와 8에서 false가 나와 혹시나 하는 마음에 돌렸는데 맞았다.

내가 이길 수 없는 케이스는 4의 배수였던 것, 그래서 간단하게 주어진 수를 n으로 나눈 나머지에 따라 true/false를 가렸다.


2. Number of Segments in a String (No.0434)

문제 설명

Given a string s, return the number of segments in the string.
A segment is defined to be a contiguous sequence of non-space characters.

해석

s라는 문자열이 주어졌을 때, s에 있는 단어의 갯수를 반환하는 함수를 구현해주세요.

예제

코드

function countSegments(s: string): number {
   return s.split(" ").filter(x => x !== "").length;
};

🗒️코멘트

방심헀다라기 보단 오만해졌다. 예전에는 이런 쉬운 문제도 손코딩을 해서 여러가지 테스트 케이스를 고려한 후 코드를 짰는데 이번에는 단순하게 짰다가 "" 빈 문자열이라던가 " " 공백만 가득한 문자열에 대한 케이스를 고려하지 않고 성의 없이 문제를풀다..쓸데없는 시간을 낭비했다.

반성하자.


3. Statistics from a Large Sample (No.1093)

문제 설명

You are given a large sample of integers in the range [0, 255]. Since the sample is so large, it is represented by an array count where count[k] is the number of times that k appears in the sample.
Calculate the following statistics:

  • minimum: The minimum element in the sample.
  • maximum: The maximum element in the sample.
  • mean: The average of the sample, calculated as the total sum of all elements divided by the total number of elements.
  • median:
    - If the sample has an odd number of elements, then the median is the middle element once the sample is sorted.
    - If the sample has an even number of elements, then the median is the average of the two middle elements once the sample is sorted.
  • mode: The number that appears the most in the sample. It is guaranteed to be unique.
    Return the statistics of the sample as an array of floating-point numbers [minimum, maximum, mean, median, mode]. Answers within 10-5 of the actual answer will be accepted.

해석

0 ~ 255사이의 정수가 담긴 배열이 주어졌을 때, 최소값, 최대값, 평균값, 중간값, 그리고 최대 빈도 수 값을 배열에 담아 반환하는 함수를 구현해주세요.

예제

코드

var sampleStats = function(count) {
    let max = -Infinity,
        min = Infinity,
        mean,
        totalSum = 0,
        freq = 0,
        mode,
        median,
        maxCount = 0;
    
    for(let l = 0, r = 255; l <256; l++, r--){
        if(count[l]){
            totalSum += count[l]*l;
            freq += count[l];
            if(min === Infinity) min = l;
            if(count[l] > maxCount){
                maxCount = count[l];
                mode = l;
            }
        }
        if(count[r]){
            if(max === -Infinity) max = r;
        }
    }
    mean = totalSum / freq;
    
    let runningSum = 0;
    let i = 0
    // Calculate median     
    while(runningSum < freq/2){
        runningSum += count[i];
        i++;
    }
    if(freq%2 || runningSum > freq/2) median = i-1;
    else{
        let prev = i-1;
        while(!count[i]) i++;
        median = (prev + i)/2;
    }
    
    return [min, max, mean, median, mode]
};

🗒️코멘트

수학에서 자주 통용되어 사용되는 mean, median, mode를 한 번씩 구할 수 있는 좋은 연습문제였다.

profile
🍖먹은 만큼 성장하는 개발자👩‍💻

0개의 댓글