[JS] 프로그래머스 1단계 다시 풀기

Hadam Cho·2021년 4월 15일
1

Algorithm

목록 보기
19/32

크레인 인형 뽑기

이전 소스 코드

function solution(board, moves) {
  var answer = 0;

  const row = board.length;
  const column = board[0].length;

  let basket = [];
  moves.forEach((move) => {
    for (let i = 0; i < row; i++) {
      const character = board[i][move - 1];
      if (character !== 0) {
        basket.push(character);
        board[i][move - 1] = 0;
        break;
      }
    }
  });

  console.log(basket);
  for (let i = 0; i < basket.length - 1; i++) {
    if (basket[i] === basket[i + 1]) {
      answer += 2;
      basket.splice(i, 2);
      i -= 2;
    }
  }

  return answer;
}

다시 풀이한 소스 코드

function solution(board, moves) {
    /*
        1. moves[i] - 1을 열로 가진 요소를 탐색한다. (board[j][moves[i] - 1])
        2. 0이 아니라면 0으로 바꾼 뒤 바구니에 넣는다.
        3. 바구니에 들어있는 맨 뒤 요소가 넣으려는 요소와 같다면 
           맨 뒤 요소를 꺼내고 카운트를 두 개 증가시킨다.
        4. moves 탐색이 끝나면 카운트를 반환한다.
    */
    let count = 0;
    const basket = [];
    for (let i = 0; i < moves.length; i++) {
        for (let j = 0; j < board.length; j++) {
            const character = board[j][moves[i] - 1];
            if (character !== 0) {
                board[j][moves[i] - 1] = 0;
                if (basket.length !== 0 && basket[basket.length - 1] === character) {
                    basket.pop();
                    count += 2;
                } else {
                    basket.push(character);
                }
                break;
            }
        }
    }
    return count;
}

신규 아이디 추천

이전 소스 코드

function solution(new_id) {
  let answer = "";
  answer = new_id
    .toLowerCase()
    .replace(/[^\w.-]/g, "")
    .replace(/\.{2,}/g, ".")
    .replace(/^\.|\.$/g, "");

  let len = answer.length;
  if (len === 0) {
    answer = "a";
    len = answer.length;
  }
  if (len > 15) {
    answer = answer.slice(0, 15).replace(/\.$/g, "");
  }
  if (len <= 2) {
    answer += answer.charAt(len - 1).repeat(3 - len);
  }
  return answer;
}

다시 풀이한 소스 코드

function solution(new_id) {
    const answer = new_id
                    .toLowerCase()
                    .replace(/[^\w-.]/g, '')
                    .replace(/\.{2,}/g, '.')
                    .replace(/^\.|\.$/g, '')
                    .padEnd(1, 'a')
                    .slice(0, 15)
                    .replace(/\.$/, '');;
    return answer.padEnd(3, answer.slice(-1))
}

모의고사

이전 소스 코드

function solution(answers) {
  var answer = [];
  const first = [1, 2, 3, 4, 5];
  const second = [2, 1, 2, 3, 2, 4, 2, 5];
  const third = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5];

  let count = new Array(3).fill(0);
  for (let i = 0; i < answers.length; i++) {
    if (answers[i] === first[i % first.length]) {
      count[0] += 1;
    }
    if (answers[i] === second[i % second.length]) {
      count[1] += 1;
    }
    if (answers[i] === third[i % third.length]) {
      count[2] += 1;
    }
  }

  let max = count[0];
  for (let i = 1; i < count.length; i++) {
    if (max < count[i]) {
      max = count[i];
    }
  }

  for (let i = 0; i < 3; i++) {
    if (max === count[i]) {
      answer.push(i + 1);
    }
  }
  return answer;
}

다시 풀이한 소스 코드

function solution(answers) {
    const people = [
        [1, 2, 3, 4, 5],
        [2, 1, 2, 3, 2, 4, 2, 5],
        [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
    ];
    
    const count = new Array(3).fill(0);
    for (let j = 0; j < people.length; j++) {
        count[j] = answers.filter((answer, i) => answer === people[j][i % people[j].length]).length;
    }
    
    const max = Math.max(...count);
    const answer = [];
    for (let i = 0; i < count.length; i++) {
        if (max === count[i]) {
            answer.push(i + 1);
        }
    }
    
    return answer;
}

체육복

이전 소스 코드

function solution(n, lost, reserve) {
    let result = new Array(n).fill(1);
    for (let i = 0; i < lost.length; i++) {
        result[lost[i] - 1] -= 1; 
    }
    for (let i = 0; i < reserve.length; i++) {
        result[reserve[i] - 1] += 1;
    }
    for (let i = 0; i < n - 1; i++) {
        if (result[i] === 0 && result[i+1] === 2 || result[i] === 2 && result[i+1] === 0) {
            result[i] = 1;
            result[i+1] = 1;
        }
    }
    let answer = 0;
    for (let i = 0; i < n; i++) {
        if (result[i] >= 1) {
            answer += 1;
        }
    }
    return answer;
}

다시 풀이한 소스 코드

function solution(n, lost, reserve) {
    /*
        1. 현재 학생들이 가지고 있는 체육복의 현황을 조사한다.
        2. 만약 도난당한 학생과 체육복이 2개인 학생의 인덱스가 붙어있다면
           체육복을 빌려준다.
        3. 체육복 갯수가 1 또는 2인 학생들의 수를 리턴한다.
    */
    
    // 1
    const current = new Array(n).fill(1);
    lost.forEach(l => current[l - 1] -= 1);
    reserve.forEach(r => current[r - 1] += 1);
    
    // 2
    for (let i = 0; i < n - 1; i++) {
        if (current[i] === 0 && current[i + 1] === 2 || 
            current[i] === 2 && current[i + 1] === 0) {
            current[i] = 1;
            current[i + 1] = 1;
        }
    }
    
    // 3
    return current.filter(c => c >= 1).length;
}

소수 만들기

이전 소스 코드

function solution(nums) {
    const sums = [];
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            for (let k = j + 1; k < nums.length; k++) {
                sums.push(nums[i] + nums[j] + nums[k]);
            }
        }
    }
    
    const not = [];
    sums.forEach(sum => {
        for (let i = 2; i < sum; i++) {
            if (sum % i === 0) {
                not.push(sum);
                break;
            }
        }
    });
    
    return sums.length - not.length;
}

다시 풀이한 소스 코드

function isPrime(num) {
    if (num === 2 || num === 3) {
        return true;
    }
    if (num < 2 || num % 2 == 0) {
        return false;
    }
    for (let i = 3; i <= Math.sqrt(num); i += 2) {
        if (num % i === 0) {
            return false;
        }
    }
    return true;
}

function solution(nums) {
    /*
        1. 삼중 for문을 통해 겹치지 않게 3개의 숫자를 더한다.
        2. 그 숫자가 소수인지 판별한다.
        3. 소수라면 count를 증가한다.
        4. count를 리턴한다.
    */
    let count = 0;
    for (let i = 0; i < nums.length - 2; i++) {
        for (let j = i + 1; j < nums.length - 1; j++) {
            for (let k = j + 1; k < nums.length; k++) {
                const sum = nums[i] + nums[j] + nums[k];
                if (isPrime(sum)) {
                    count += 1;
                }
            }
        }
    }
    return count;
}
profile
(。・∀・)ノ゙

0개의 댓글