문제(출처: 프로그래머스)

2차원 좌표 평면에 변이 축과 평행한 직사각형이 있습니다. 직사각형 네 꼭짓점의 좌표 [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]가 담겨있는 배열 dots가 매개변수로 주어질 때, 직사각형의 넓이를 return 하도록 solution 함수를 완성해보세요.

 

▶ 내가 푼 방식

function solution(dots) {
    const xArray = dots.map(v=> v[0])
    const yArray = dots.map(v=> v[1])
    const xLength = Math.max(...xArray) - Math.min(...xArray)
    const yLength = Math.max(...yArray) - Math.min(...yArray)

    return xLength * yLength
}

 

 다른 유저가 푼 방식

... 이번에는 다들 비슷하게 풀이함

 

 배운 것들

     -  최대 최소 값을 구하는 방법

const temp = [1,23,4,10]
const maxValue1 = Math.max.apply(null, temp)
const maxValue2 = Math.max(...temp)

const maxValue3 = array.reduce( function (previous, current) { 
	return previous > current ? previous:current;
});

const minValue3 = array.reduce( function (previous, current) { 
	return previous > current ? current:previous;
});

     - 

문제(출처: 프로그래머스)

문자열 my_str과 n이 매개변수로 주어질 때, my_str을 길이 n씩 잘라서 저장한 배열을 return하도록 solution 함수를 완성해주세요.

 

▶ 내가 푼 방식

function solution(my_str, n) {
    var answer =[]
    const arrayLength = Math.ceil(my_str.length/n)
    let startIndex = 0
    for (let i = 0; i < arrayLength; i ++){
        startIndex = n*i 
        answer.push(my_str.slice(startIndex, startIndex+n));
    }
    return answer;
}

 

 다른 유저가 푼 방식

// 유저 1
function solution(my_str, n) {
  return my_str.match(new RegExp(`.{1,${n}}`, "g"));
}
// RegExp(`.{1,${n}}`, "g") 
// -> "g" : 모든 문자열 탐색
// `.{1,${n}}`  : 1개 이상 n개 이하씩
// 탐색


// 유저 2
function solution(my_str, n) {
    let res = [];
    for (let i = 0; i < my_str.length; i+=n) res.push(my_str.slice(i, i+n));
    return res;
}

 

 배운 것들

     -  정규표현식의 다양한 활용방법

           -  my_str.match(new RegExp(`.{1,${n}}`, "g"));

     -  for 구문에서 증가량을 조절하는 방법도 생각해야 한다.

문제(출처: 프로그래머스)

머쓱이는 행운의 숫자 7을 가장 좋아합니다. 정수 배열 array 가 매개변수로 주어질 때, 7이 총 몇 개 있는지 return 하도록 solution 함수를 완성해보세요.

 

▶ 내가 푼 방식

function solution(array) {
    var answer = array.join('');
    const match = answer.match(/7/g)
    return match? match.length : 0
}

 

 다른 유저가 푼 방식

// 유저 1
function solution(array) {
    return(array.join().split("").filter((el)=>{return el=="7"}).length)
}

// 유저 2


// 유저 3

 

 배운 것들

     - 문장에 특정 문자가 몇개가 있는 가를 알고 싶을 때 사용 하는 방식이 text.match(/7/g)

     - 

문제(출처: 프로그래머스)

N 개의 포켓몬 중에서 N/2 개의 유니크한 포켓몬만 선택가능하다.

 

▶ 내가 푼 방식

function solution(nums) {
    const selectNum = Math.floor(nums.length/2)
    const unique = [... new Set(nums)].length
    return unique < selectNum ? unique : selectNum;
}

 

 다른 유저가 푼 방식

// 유저 1
function solution(nums) {
    const noDuplicatePokemon = new Set(nums);
    const pokemonVarietyCount = noDuplicatePokemon.size;
    const pokemonCounts = nums.length;
    return pokemonVarietyCount > pokemonCounts/2 ? pokemonCounts/2 : pokemonVarietyCount;

}

// 유저 2


// 유저 3

 

 배운 것들

     -  new Set() 을 한후  .size 를 이용해서 크기 확인가능

     

문제(출처: 프로그래머스)

덧셈, 뺄셈 수식들이 'X [연산자] Y = Z' 형태로 들어있는 문자열 배열 quiz가 매개변수로 주어집니다. 수식이 옳다면 "O"를 틀리다면 "X"를 순서대로 담은 배열을 return하도록 solution 함수를 완성해주세요.

 

제한사항

  • 연산 기호와 숫자 사이는 항상 하나의 공백이 존재합니다. 단 음수를 표시하는 마이너스 기호와 숫자 사이에는 공백이 존재하지 않습니다.
  • 1 ≤ quiz의 길이 ≤ 10
  • X, Y, Z는 각각 0부터 9까지 숫자로 이루어진 정수를 의미하며, 각 숫자의 맨 앞에 마이너스 기호가 하나 있을 수 있고 이는 음수를 의미합니다.
  • X, Y, Z는 0을 제외하고는 0으로 시작하지 않습니다.
  • -10,000 ≤ X, Y ≤ 10,000
  • -20,000 ≤ Z ≤ 20,000
  • [연산자]는 + 와 - 중 하나입니다.

 

▶ 내가 푼 방식

function solution(quiz) {
    var answer = [];
    quiz.forEach((v) =>{
        let equation = v.split(' ');
        if(equation[1] === "-"){
            let result = Number(equation[0]) - Number(equation[2]);
            if (result === Number(equation[4])){
                answer.push("O")
            }
            else answer.push("X")
        }
        if(equation[1] === "+"){
            let result = Number(equation[0]) + Number(equation[2]);
            if (result === Number(equation[4])){
                answer.push("O")
            }
            else answer.push("X")     
        }
    })
    return answer;
}

 

 다른 유저가 푼 방식

// 유저 1
function solution(quiz) {
    var answer = [];
    return quiz.map(t => {
        const [calc, result] = t.split(' = ');
        const sign = calc.includes('+') ? 1 : -1
        const [a, b] = calc.split(sign === 1 ? ' + ' : ' - ');

        return +a + (+b * sign) === +result ? 'O' : 'X'
    });
}

// 유저 2
function solution(quiz) {
    let answer = [];
    quiz.forEach((val) => {
        const [x, sign, y, , z] = val.split(" ");
        let sum = 0;
        if (sign === "+") {
            sum = Number(x) + Number(y);
        } else {
            sum = Number(x) - Number(y);
        }
        sum === Number(z) ? answer.push("O") : answer.push("X");
    });
    return answer;
}

// 유저 3

 

 배운 것들

     -  split 을 한 후 구조분해를 하면 코드가 좀더 간결해진다.

     - 

+ Recent posts