[프로그래머스]카펫(javascript/자바스크립트)

스카치·2023년 4월 13일
0

문제

풀이 1

function solution(brown, yellow) {
    var divisor = [];
    let sum = brown + yellow
    for (let i=3; i<sum; i++){
        if (sum % i === 0 ) divisor.push(i)
        if (i*i === sum) divisor.push(i)
    }
    
    let combi = getCombinations(divisor, 2)
    
    let answer = combi.filter( v => {
        if (v[0] * v[1] === sum) {
            let qyellow = (v[0]-2) * (v[1]-2)
            if (qyellow === yellow) return v
        }
    })[0]
     
    return answer[0] < answer[1] ? [answer[1], answer[0]] : answer
     
}


function getCombinations(arr, selectNumber) {
    const result = []
    if (selectNumber === 1) return arr.map(v => [v])
    arr.forEach( (fixed, index, origin) => {
        const rest = arr.slice(index+1)
        const combinations = getCombinations(rest, selectNumber-1)
        const attatch = combinations.map(v => [fixed, ...v])
        result.push(...attatch)
    })
    return result
}

풀이 2

function solution(brown, red) {
    var answer = [];
    for (var i = 3; i <= (brown+red)/i; i++) {
        var x = Math.floor((brown+red)/i);
        if( (x-2)*(i-2)=== red) {
            break;
        }
    }

    return [x,i];
}

풀이 3

function solution(brown, yellow) {
    const x = (brown - 12) * 0.5;
    const y = yellow - brown + 8;
    const i = ( 8 + x + Math.sqrt( Math.pow(x, 2) - (4 * y) ) ) * 0.5;
    const j = ( 8 + x - Math.sqrt( Math.pow(x, 2) - (4 * y) ) ) * 0.5;
    console.log(i)


    var answer = [i, j];
    return answer;
}

풀이 4

function solution(brown, yellow) {
    var xpy=brown/2+2;
    for(var a=1;a<xpy;a++) if(a*(xpy-a)==brown+yellow)  return [Math.max(a,xpy-a),Math.min(a,xpy-a)];
}

풀이 5

function solution(brown, red) {
    let sumOfHorizonAndVertical = (brown - 4)/2;
    for (let i=1; i < sumOfHorizonAndVertical; i++) {
        if ((sumOfHorizonAndVertical - i)*i === red) {
            return [sumOfHorizonAndVertical - i + 2, i + 2];
        }
    }
}

0개의 댓글