Jun 개발노트

프로그래머스 - 쇠막대기

January 30, 2020

쇠막대기

const getIndexOfRazer = ags => {
    const agsArr = [...ags];
    let razer = [];
    for (let i = 0; i < agsArr.length; i++) {
        if (agsArr[i] === "(" && agsArr[i + 1] === ")") {
            razer.push(i);
        }
    }
    return razer;
};

const changeStick = ags => {
    const agsArr = [...ags];
    let tempIndex = 0;
    let start = 0;
    let end = 0;
    for (let i in agsArr) {
        if (agsArr[i] === "(") {
            tempIndex = i;
        } else if (agsArr[i] === ")") {
            end = i;
            start = tempIndex;
            agsArr[start] = 0;
            agsArr[end] = 0;
            break;
        }
    }
    return [Number(start), Number(end)];
};
const getStick = ags => {
    let result = [];
    let agsArr = [...ags];
    let count = 0;
    for (let i of agsArr) {
        if (i === ")") {
            count++;
        }
    }
    for (let i = 0; i < count; i++) {
        let stick = changeStick(agsArr);
        result.push(stick);
        agsArr[stick[0]] = "0";
        agsArr[stick[1]] = "0";
    }

    return result;
};

const replaceRazer = ags => {
    return ags.replace(/(\(\))/g, "00");
};

const getNumberOfIron = (a, b) => {
    let args = [...a];
    let args2 = [...b];
    let numberOfStick = 0;
    args.map(v => {
        for (let razer of args2) {
            if (v[0] < razer && razer < v[v.length - 1]) {
                numberOfStick++;
            }
        }
    });
    return numberOfStick + args2.length - 1;
};
const lastFn = first => {
    let IndexOfRazer = getIndexOfRazer(first);
    let subRazer = replaceRazer(first);
    let stick = getStick(subRazer);
    return getNumberOfIron(stick, IndexOfRazer);
};

// test('잘린 막대기', () => {
//     expect(getNumberOfIron('()(((()())(())()))(())')).toBe(17)
// })

test("레이저 구하기", () => {
    expect(getIndexOfRazer("()(((()())(())()))(())")).toEqual([0, 5, 7, 11, 14, 19]);
});

test("레이저 교체하기", () => {
    expect(replaceRazer("()(((()())(())()))(())")).toBe("0(((00)(0)0))(0)");
});

test("막대구하기", () => {
    expect(getStick("0(((00)(0)0))(0)")).toEqual([
        [4, 9],
        [10, 13],
        [3, 16],
        [2, 17],
        [18, 21]
    ]);
});
// test('잘린 막대기 구하기', ()=> {
//     expect(getNumberOfIron([[2,17],[3,16],[4,9],[10,13],[18,21]], [0, 5, 7 ,11, 14, 19])).toBe(17)
// })
test("잘린 막대기 구하기", () => {
    expect(
        getNumberOfIron(
            [
                [2, 17],
                [3, 16],
                [4, 9],
                [10, 13],
                [18, 21]
            ],
            [0, 5, 7, 11, 14, 19]
        )
    ).toBe(17);
});
test("최종", () => {
    expect(lastFn("()(((()())(())()))(())")).toBe(17);
});

Written by Junho You 배운것을 기록하자