티스토리 뷰

Algorithms

Cut the sticks

seoca 2020. 12. 18. 17:39

간단하게는 minimum value 로 each index를 subtract할 수 있는 갯수를 구하는 문제.

 

 

Solution 1 in Javascript 

const arr = [5, 3, 2, 2, 2, 8]

function cutTheSticks(arr) {
    //sort the array
    let sorted = arr.sort();

    //set index[0] to a min
    let min = sorted[0];
     console.log(sorted.length); 

    for (let i = 0; i < sorted.length; i++) {
        if (sorted[i] > min) {
            min = sorted[i]; //change min to next shortest min
            console.log(sorted.length - i);
        }
    }
}

cutTheSticks(arr); //6 3 2 1

 

solution 

1. array 를 sort한다.

2. first index를 min 으로 지정

3. 전체 index를 loop

4. sorted[i] > min condition 이 duplicate index 가 몇개가 있던지간에 다음 큰 수가 있는 index number which is 'i' 로 넘어가게 한다. 

5. sorted.length - i 를 print 함으로써 남아있는 초의 갯수를 알 수 있다. 

 

이 solution은 굳이 each candle을 subtract하지 않고 풀었다. 

 

 

 

Solution 2 in Javascript 

const arr = [5, 3, 2, 2, 2, 8]

function cutTheSticks(arr) {
    let newArr = [...arr]; //spread operator
    const result = [newArr.length]; //to print the length first

    while (newArr.length > 0) {
        let min = Math.min(...newArr); //spread operator
                          //accumulator, currentValue
        newArr = newArr.reduce((target, stick) => {
            stick > min && target.push(stick - min); //short circuit evaluation
            return target;
        }, []); //accumulator is [] here

        newArr.length > 0 && result.push(newArr.length);
    }
    console.log(result);
}

cutTheSticks(arr); //[6, 3, 2, 1]

 

 이 solution은 each candle 을 min value만큼 뺀 수를 push 했다.

 

 

 

 

Solution 3 in Javascript 

 

 

 

 

 

 

Reference

www.hackerrank.com/challenges/cut-the-sticks/problem

 

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

 

'Algorithms' 카테고리의 다른 글

CamelCase  (0) 2021.02.12
smallest distance  (0) 2021.01.16
Equalize the Array  (0) 2020.12.11
Invert Binary Tree  (0) 2020.11.30
Sequence Equation  (0) 2020.10.30