숫자만 추출

const str = "aAb1B2cC34oOp";
const numbers = str.match(/\d+/g);
// ["1", "2", "34"]

/\d+/g

  • \d+ : 연속된 하나이상의 숫자에 매칭
  • g : 전체 문장
  • 전체 문장에서 연속된 하나이상의 숫자에 매칭되는 문자를 찾는다. 

참고로 \D+ 는 숫자가 아닌 문자들을 찾는 패턴

 

3x , 7, 2x 추출

const str = "3x + 7 + 2x"
const numberX = str.match(/\b\d+x\b/g); // [ '3x', '2x'] 
const number = str.match(/\b\d+\b/g);   // ['7']
const number2 =str.match(/\d+/g);       //['3', '7', '2']

/\b\d+\b/g

  • \b : 단어의 경계를 의미 --- |on| |the| |board|  에서 | 가 경계
  • \d+x : 연속된 하나이상의 숫자와 x로 이루어진 패턴
  • g : 전체 문장

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

문자열 my_string이 매개변수로 주어집니다. my_string은 소문자, 대문자, 자연수로만 구성되어있습니다. my_string안의 자연수들의 합을 return하도록 solution 함수를 완성해주세요.

 

▶ 내가 푼 방식

function solution(my_string) {
    const reg = /\d+/g
    const numberArray = my_string.match(reg);
    
    return numberArray === null ? 0 :numberArray.reduce((sum,number) => sum + parseInt(number), 0);
}

 

 다른 유저가 푼 방식

// 유저 1
function solution(my_string) {
  return my_string.split(/\D+/).reduce((acc, cur) => acc + Number(cur), 0);
}


// 유저 2
function solution(my_string) {
    return my_string.toLowerCase().replace(/[a-z]/g, " ").split(" ").map((v) => v*1).reduce((a,b) => a+b)
}

 

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

한 개 이상의 항의 합으로 이루어진 식을 다항식이라고 합니다. 다항식을 계산할 때는 동류항끼리 계산해 정리합니다. 덧셈으로 이루어진 다항식 polynomial이 매개변수로 주어질 때, 동류항끼리 더한 결괏값을 문자열로 return 하도록 solution 함수를 완성해보세요. 같은 식이라면 가장 짧은 수식을 return 합니다.

 

▶ 내가 푼 방식

function solution(polynomial) {
    const xVariable = polynomial.match(/\b\d*x\b/g);
    const numbers = polynomial.match(/\b\d+\b/g);
    
    const numberSum = numbers === null? null: numbers.reduce((sum, number) => {
        return sum + parseInt(number) }, 0)
    
    const Coefficient = xVariable === null? null: xVariable.reduce((sum, variable) => {
        const number = variable === 'x'? 1: parseInt(variable);
        return sum + number
    },0)
    
    const xSum = (Coefficient === 1 && Coefficient !==null) ? 'x' : `${Coefficient}x`
    
    if (numberSum && Coefficient){
        return `${xSum} + ${numberSum}`
    }
    if (numberSum && Coefficient === null){
        return `${numberSum}`
    }
    if (numberSum == null && Coefficient){
        return `${xSum}`
    }
}

 

 다른 유저가 푼 방식

// 유저 1
function solution(polynomial) {
    const arr = polynomial.split(" + ");
    const xNum = arr
                .filter(n => n.includes("x"))
                .map(n => n.replace('x', '') || '1')
                .reduce((acc, cur) => acc + parseInt(cur, 10), 0);
    const num = arr
                .filter(n => !isNaN(n))
                .reduce((acc, cur) => acc + parseInt(cur, 10), 0);

    let answer = [];
    if(xNum) answer.push(`${xNum === 1 ? "" : xNum}x`);
    if(num) answer.push(num);

    return answer.join(" + ");
}

 

 배운 것들

     - "숫자x" 형태를 모두 찾아 배열로 반환

const allX = str.match(/\b\d+x\b/g)
/**
\b는 단어 경계 -> 이를 통해 "x" 앞에 오는 숫자들만 선택
\d+는 하나 이상의 숫자를 나타냄
x는 리터럴 문자 'x'를 의미
\b는 닫는 단어 경계를 나타냅니다.
g는 전역 검색을 의미, 문자열 전체에서 해당패턴을 검색
**/

     -  " 숫자" 만 모두 찾아 배열로 반환

const number = str.match(/\b\d+\b/g)
  • 숫자만을 찾아내며, 숫자가 독립적인 단어로 취급 (숫자 앞뒤에 문자가 없어야 찾아냄).

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

머쓱이는 RPG게임을 하고 있습니다. 게임에는 up, down, left, right 방향키가 있으며 각 키를 누르면 위, 아래, 왼쪽, 오른쪽으로 한 칸씩 이동합니다. 예를 들어 [0,0]에서 up을 누른다면 캐릭터의 좌표는 [0, 1], down을 누른다면 [0, -1], left를 누른다면 [-1, 0], right를 누른다면 [1, 0]입니다. 머쓱이가 입력한 방향키의 배열 keyinput와 맵의 크기 board이 매개변수로 주어집니다. 캐릭터는 항상 [0,0]에서 시작할 때 키 입력이 모두 끝난 뒤에 캐릭터의 좌표 [x, y]를 return하도록 solution 함수를 완성해주세요.
- [0, 0]은 board의 정 중앙에 위치합니다. 예를 들어 board의 가로 크기가 9라면 캐릭터는 왼쪽으로 최대 [-4, 0]까지 오른쪽으로 최대 [4, 0]까지 이동할 수 있습니다.

 

▶ 내가 푼 방식

function solution(keyinput, board) {
    var answer = [];
    const controlXY = {"down": ["y", -1] , "up": ["y", 1], "left": ["x", -1], "right": ["x",1] }
    const maxX = (board[0] - 1) / 2;
    const maxY = (board[1] - 1) / 2;
    let x = 0
    let y = 0
    for (let i of keyinput){
        let [coordinate, value] = controlXY[i];
        if (coordinate == "x"){
            x += value
            if (x > maxX) {x = maxX}
            if (x < -maxX) {x = -maxX}
        }
        else{
            y += value
            if (y > maxY) {y = maxY}
            if (y < -maxY) {y = -maxY}
        }
    }
    return [x, y]
}

 

 다른 유저가 푼 방식

// 유저 1
function solution(keyinput, board) {
    let res = [0,0];
    for (let p of keyinput) {
        switch(p){
            case 'left': if (-res[0] < board[0]/2-1) res[0]--; break;
            case 'right': if (res[0] < board[0]/2-1) res[0]++; break;
            case 'up': if (res[1] < board[1]/2-1) res[1]++; break;
            case 'down': if (-res[1] < board[1]/2-1) res[1]--; break;
        }
    }
    return res;
}

// 유저 2
const CONTROL = {
    up: [0, 1],
    down: [0, -1],
    left: [-1, 0],
    right: [1, 0],
}

function solution(key, [n, m]) {
    const [x1, x2] = [-(n-1)/2, (n-1)/2];
    const [y1, y2] = [-(m-1)/2, (m-1)/2];
    return key.reduce(([x, y], k) => {
        const [nx, ny] = [x + CONTROL[k][0], y + CONTROL[k][1]];
        if (x1 <= nx && nx <= x2 && y1 <= ny && ny <= y2) return [nx, ny];
        return [x, y];
    }, [0, 0]);
}


// 유저 3

 

 배운 것들

     -  배운것 : Array.reduce 에서 accumulator 를 배열로도 가능하다. 함수 안에서 더하기만 하는 것이 아니라 원하는 기능을 구현 할 수도 있다.

     -  복습 : Array.reduce

array.recude((accumulator, currentVale) => {
    accumulator + currentValue
  },
  initialValue
);

     - 

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

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 구문에서 증가량을 조절하는 방법도 생각해야 한다.

+ Recent posts