CodingSpace

[HackerRank/Algorithms] Implementation - Cut the sticks 본문

HackerRank/Algorithm

[HackerRank/Algorithms] Implementation - Cut the sticks

개발자_조이킴 2022. 9. 4. 16:24

Problem. Implementation - Cut the sticks


Link.

https://www.hackerrank.com/challenges/cut-the-sticks/problem?isFullScreen=true 

 

Cut the sticks | HackerRank

Given the lengths of n sticks, print the number of sticks that are left before each cut operation.

www.hackerrank.com


Description.

You are given a number of sticks of varying lengths. You will iteratively cut the sticks into smaller sticks, discarding the shortest pieces until there are none left. At each iteration you will determine the length of the shortest stick remaining, cut that length from each of the longer sticks and then discard all the pieces of that shortest length. When all the remaining sticks are the same length, they cannot be shortened so discard them.

Given the lengths of n sticks, print the number of sticks that are left before each iteration until there are none left.

 


Key Point. 


My Answer. 

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}

/*
 * Complete the 'cutTheSticks' function below.
 *
 * The function is expected to return an INTEGER_ARRAY.
 * The function accepts INTEGER_ARRAY arr as parameter.
 */

function cutTheSticks(arr) {    
    let result = [];
    
    // #1. 배열내 요소의 총합 
    // (total sum of array)
    let totalSum = arr.reduce((acc, cur) => acc + cur);
    
    // #2. 만약 요소의 총합이 0인 경우, [0]을 반환 
    // (return [0], if totalSum is zero)
    if(totalSum === 0)
        return [0];
    
    // #3. 원본 배열을 수정하지 않게하기 위해, 배열 복사 
    // (copy original array and use it in subsequent calculations to keep original array as original)
    let updatedArr = arr.slice();
    
    // #4. 배열내 요소의 총합이 0이 될때까지, while문 반복
    while(totalSum !== 0) {
        // #5. 배열내 요소중 0을 제거
        // removing zero elements in array
        let filteredArr = updatedArr.filter((el) => {
            if(el !== 0) return el;
        });
        
        // #6. 0을 제외한 배열내 최솟값
        // find the minimum value in the array excepting zero elements
        let min = Math.min(...filteredArr);
        let cnt = 0;
        
        // #7. 배열내 요소를 하나씩 조회하면서, 0이 아닌 경우 최소값(min)으로 빼준다
        // subtracting elements with minimum value if it is not zero
        updatedArr = updatedArr.map((el) => {
            if(el !== 0) {
                cnt++;
                return el - min;
            }
            else 
                return el;
        });
        
        // #8. 배열내 총합 업데이트
        // updating the value of totalSum
        totalSum = updatedArr.reduce((acc, cur) => acc + cur);
        
        // #9. 현재 iteration에서 빼기한 수를 result 배열에 저장
        // saving the value of cnt, number of executing substraction in current step
        result.push(cnt);
    };
    
    return result;
}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const n = parseInt(readLine().trim(), 10);

    const arr = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));

    const result = cutTheSticks(arr);

    ws.write(result.join('\n') + '\n');

    ws.end();
}

References. 

 

Comments