Light Blue Pointer
본문 바로가기
Coding Test

[프로그래머스] 광물 캐기

by Greedy 2024. 4. 2.

문제 주소

https://school.programmers.co.kr/learn/courses/30/lessons/172927

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 설명

마인은 곡괭이로 광산에서 광석을 캐려고 합니다. 마인은 다이아몬드 곡괭이, 철 곡괭이, 돌 곡괭이를 각각 0개에서 5개까지 가지고 있으며, 곡괭이로 광물을 캘 때는 피로도가 소모됩니다. 각 곡괭이로 광물을 캘 때의 피로도는 아래 표와 같습니다.

예를 들어, 철 곡괭이는 다이아몬드를 캘 때 피로도 5가 소모되며, 철과 돌을 캘때는 피로도가 1씩 소모됩니다. 각 곡괭이는 종류에 상관없이 광물 5개를 캔 후에는 더 이상 사용할 수 없습니다.

마인은 다음과 같은 규칙을 지키면서 최소한의 피로도로 광물을 캐려고 합니다.

  • 사용할 수 있는 곡괭이중 아무거나 하나를 선택해 광물을 캡니다.
  • 한 번 사용하기 시작한 곡괭이는 사용할 수 없을 때까지 사용합니다.
  • 광물은 주어진 순서대로만 캘 수 있습니다.
  • 광산에 있는 모든 광물을 캐거나, 더 사용할 곡괭이가 없을 때까지 광물을 캡니다.

즉, 곡괭이를 하나 선택해서 광물 5개를 연속으로 캐고, 다음 곡괭이를 선택해서 광물 5개를 연속으로 캐는 과정을 반복하며, 더 사용할 곡괭이가 없거나 광산에 있는 모든 광물을 캘 때까지 과정을 반복하면 됩니다.

마인이 갖고 있는 곡괭이의 개수를 나타내는 정수 배열 picks와 광물들의 순서를 나타내는 문자열 배열 minerals가 매개변수로 주어질 때, 마인이 작업을 끝내기까지 필요한 최소한의 피로도를 return 하는 solution 함수를 완성해주세요.


제한사항

  • picks는 [dia, iron, stone]과 같은 구조로 이루어져 있습니다.
    • 0 ≤ dia, iron, stone ≤ 5
    • dia는 다이아몬드 곡괭이의 수를 의미합니다.
    • iron은 철 곡괭이의 수를 의미합니다.
    • stone은 돌 곡괭이의 수를 의미합니다.
    • 곡괭이는 최소 1개 이상 가지고 있습니다.
  • 5 ≤ minerals의 길이 ≤ 50
    • minerals는 다음 3개의 문자열로 이루어져 있으며 각각의 의미는 다음과 같습니다.
    • diamond : 다이아몬드
    • iron : 철
    • stone : 돌

입출력 예

picks minerals result

[1, 3, 2] ["diamond", "diamond", "diamond", "iron", "iron", "diamond", "iron", "stone"] 12
[0, 1, 1] ["diamond", "diamond", "diamond", "diamond", "diamond", "iron", "iron", "iron", "iron", "iron", "diamond"] 50

입출력 예 설명

입출력 예 #1

다이아몬드 곡괭이로 앞에 다섯 광물을 캐고 철 곡괭이로 남은 다이아몬드, 철, 돌을 1개씩 캐면 12(1 + 1 + 1 + 1+ 1 + 5 + 1 + 1)의 피로도로 캘 수 있으며 이때가 최소값입니다.

입출력 예 #2

철 곡괭이로 다이아몬드 5개를 캐고 돌 곡괭이고 철 5개를 캐면 50의 피로도로 캘 수 있으며, 이때가 최소값입니다.

 

제출 코드

import java.util.Arrays;
import java.lang.Math;

class Solution {
    public int solution(int[] picks, String[] minerals) {
        
        int allpicks = 0;
        for(int i: picks){
            allpicks += i;
        }
        
        int number = Math.min(allpicks,(int)Math.ceil(minerals.length/5)+1);

        Group [] groups = new Group[number];
        
        for(int i=0;i<groups.length;i++){
            groups[i] = new Group(0,0,0);
        }

        for(int i=0;i<minerals.length;i++){
            if(i/5>=groups.length){
                break;
            }
            String element = minerals[i];
            if(element.equals("diamond")){
                groups[i/5].diamond++;
            }
            if(element.equals("iron")){
                groups[i/5].iron++;
            }
            if(element.equals("stone")){
                groups[i/5].stone++;
            }            
        }
        //정렬 후 계산
        
        Arrays.sort(groups);
        
        int [] toolcost = {25,5,1};
        
        int index = 0;
        int sum = 0;
        for(int i=0; i<groups.length; i++){
            
            if(index >= picks.length) {
                break;
            }

            while(picks[index] <= 0) {
                index++;
            } 
            
            picks[index]--;
            int mined = 0;
            mined = mine(groups[i].diamond, toolcost[index], 25);
            sum += mined;
            
            mined = mine(groups[i].iron, toolcost[index], 5);
            sum += mined;
            
            mined = mine(groups[i].stone, toolcost[index], 1);
            sum += mined;

        }   
            
        return sum;
    }
    
    public int mine(int number, int tool, int cost){
        int i = Math.max(cost/tool,1);
        return i*number;
    }
}

class Group implements Comparable<Group>{
    int diamond;
    int iron;
    int stone;
    
    public int compareTo(Group o){
        if(this.diamond>o.diamond){
            return -1;
        }else if(this.diamond==o.diamond){
            if(this.iron>o.iron){
                return -1;
            }else if(this.iron==o.iron){
                return 0;
            }
        }
        return 1;
    }
    
    public Group(int d, int i, int s){
        diamond = d;
        iron = i;
        stone = s;
    }
}

코드 설명

Group으로 5개씩 묶어서 다이아,철,돌의 개수를 세서 넣어줌

 

numbers: 

곡괭이가 광물을 다 캐기 전에 떨어지는 경우가 있으므로

곡괭이의 수를 세어서 곡괭이*5보다 (5개의 광물을 캘 수 있으므로) 작은 경우는 Group을 더 이상 생성하지 않음

 

다이아 개수, 철 개수에 따라서 정렬함

다이아가 제일 많은 순 -> 철이 제일 많은 순으로 다이아 -> 철 -> 돌 곡괭이를 사용하게 해서 최소 피로도가 계산되게 함

 

그리고 피로도를 계산해서 다 더해줌

 

 

풀이 과정

곡괭이 하나당 5개를 캐니까 그냥 5개씩 나눠서 그룹지어봄

import java.util.Arrays;

class Solution {
    public int solution(int[] picks, String[] minerals) {

        Group [] groups = new Group[minerals.length/5];
        
        for(int i=0;i<groups.length;i++){
            groups[i] = new Group(0,0,0);
        }

        for(int i=0;i<minerals.length;i++){
            String element = minerals[i];
            if(element.equals("diamond")){
                groups[i/5].diamond++;
            }
            if(element.equals("iron")){
                groups[i/5].iron++;
            }
            if(element.equals("stone")){
                groups[i/5].stone++;
            }
        }
        //정렬 후 계산
        
        Arrays.sort(groups);
        
        int [] toolcost = {25,5,1};
        
        int index = 0;
        int sum = 0;
        for(int i=0; i<groups.length; i++){
            while(picks[index]<=0){
                index++;
            }  
            
            picks[index]--;
            
            sum += cost(groups[i].diamond, toolcost[index], 25);
            sum += cost(groups[i].iron, toolcost[index], 5);
            sum += cost(groups[i].stone, toolcost[index], 1);

        }   
            
        return sum;
    }
    
    public int cost(int number, int tool, int cost){
        int i = cost/tool;
        return i*number;
        
    }
}

class Group implements Comparable<Group>{
    int diamond;
    int iron;
    int stone;
    
    public int compareTo(Group o){
        if(this.diamond>o.diamond){
            return 1;
        }else if(this.diamond==o.diamond){
            if(this.iron>o.iron){
                return 1;
            }else if(this.iron==o.iron){
                return 0;
            }
        }
        return -1;
    }
    
    public Group(int d, int i, int s){
        diamond = d;
        iron = i;
        stone = s;
    }
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
	at Solution.solution(Unknown Source)
	at SolutionTest.lambda$main$0(Unknown Source)
	at SolutionTest$SolutionRunner.run(Unknown Source)
	at SolutionTest.main(Unknown Source)

 

인덱스 에러가 뜸

로그 찍어봄

 

import java.util.Arrays;
import java.lang.Math;

class Solution {
    public int solution(int[] picks, String[] minerals) {

        Group [] groups = new Group[(int)Math.ceil(minerals.length/5)];
        
        for(int i=0;i<groups.length;i++){
            groups[i] = new Group(0,0,0);
        }

        for(int i=0;i<minerals.length;i++){
            String element = minerals[i];
            if(element.equals("diamond")){
                groups[Math.min(i/5, groups.length - 1)].diamond++;
            }
            if(element.equals("iron")){
                groups[Math.min(i/5, groups.length - 1)].iron++;
            }
            if(element.equals("stone")){
                groups[Math.min(i/5, groups.length - 1)].stone++;
            }
        }
        //정렬 후 계산
        
        Arrays.sort(groups);
        
        for(int i=0;i<groups.length;i++){
            Group g =groups[i];
            System.out.println(g.diamond+","+g.iron+","+g.stone);
        }
        
        int [] toolcost = {25,5,1};
        
        int index = 0;
        int sum = 0;
        for(int i=0; i<groups.length; i++){
            while(picks[index]<=0){
                index++;
            }  
            
            picks[index]--;
            
            sum += cost(groups[i].diamond, toolcost[index], 25);
            sum += cost(groups[i].iron, toolcost[index], 5);
            sum += cost(groups[i].stone, toolcost[index], 1);

        }   
            
        return sum;
    }
    
    public int cost(int number, int tool, int cost){
        int i = cost/tool;
        return i*number;
        
    }
}

class Group implements Comparable<Group>{
    int diamond;
    int iron;
    int stone;
    
    public int compareTo(Group o){
        if(this.diamond>o.diamond){
            return -1;
        }else if(this.diamond==o.diamond){
            if(this.iron>o.iron){
                return -1;
            }else if(this.iron==o.iron){
                return 0;
            }
        }
        return 1;
    }
    
    public Group(int d, int i, int s){
        diamond = d;
        iron = i;
        stone = s;
    }
}
테스트 1
입력값 〉	[1, 3, 2], ["diamond", "diamond", "diamond", "iron", "iron", "diamond", "iron", "stone"]
기댓값 〉	12
실행 결과 〉	실행한 결괏값 4이 기댓값 12과 다릅니다.
출력 〉	4,3,1
테스트 2
입력값 〉	[0, 1, 1], ["diamond", "diamond", "diamond", "diamond", "diamond", "iron", "iron", "iron", "iron", "iron", "diamond"]
기댓값 〉	50
실행 결과 〉	실행한 결괏값 75이 기댓값 50과 다릅니다.
출력 〉	
5,0,0
1,5,0

엥 제대로 안 들어갔네 5개씩 들어가야 하는데…???!?!?!

groups[Math.min(i/5, groups.length - 1)].stone++;

여기서 걸린듯 하여….

저걸 바꿔보는데 계속 array index out of bound 이슈가 생김…

groups 의 길이를 ceil하고 곡괭이가 먼저 떨어지면 break 하게 함

import java.util.Arrays;
import java.lang.Math;

class Solution {
    public int solution(int[] picks, String[] minerals) {
        
        int number = (int)Math.ceil(minerals.length/5);
        if(minerals.length%5==0){
            number += 0;
        }else{
            number += 1;
        }

        Group [] groups = new Group[number];
        
        for(int i=0;i<groups.length;i++){
            groups[i] = new Group(0,0,0);
        }

        for(int i=0;i<minerals.length;i++){
            String element = minerals[i];
            if(element.equals("diamond")){
                groups[i/5].diamond++;
            }
            if(element.equals("iron")){
                groups[i/5].iron++;
            }
            if(element.equals("stone")){
                groups[i/5].stone++;
            }            
        }
        //정렬 후 계산
        
        Arrays.sort(groups);
        
        for(int i=0;i<groups.length;i++){
            Group g =groups[i];
            System.out.println(g.diamond+","+g.iron+","+g.stone);
        }
        
        int [] toolcost = {25,5,1};
        
        int index = 0;
        int sum = 0;
        for(int i=0; i<groups.length; i++){
            
            if(index >= picks.length) {
                break;
            }

            while(index < picks.length && picks[index] <= 0) {
                index++;
            } 
            
            if(index >= picks.length) {
                break;
            }
            
            while(picks[index]<=0){
                index++;
            }  
            
            picks[index]--;
            
            sum += cost(groups[i].diamond, toolcost[index], 25);
            sum += cost(groups[i].iron, toolcost[index], 5);
            sum += cost(groups[i].stone, toolcost[index], 1);

        }   
            
        return sum;
    }
    
    public int cost(int number, int tool, int cost){
        int i = cost/tool;
        return i*number;
        
    }
}

class Group implements Comparable<Group>{
    int diamond;
    int iron;
    int stone;
    
    public int compareTo(Group o){
        if(this.diamond>o.diamond){
            return -1;
        }else if(this.diamond==o.diamond){
            if(this.iron>o.iron){
                return -1;
            }else if(this.iron==o.iron){
                return 0;
            }
        }
        return 1;
    }
    
    public Group(int d, int i, int s){
        diamond = d;
        iron = i;
        stone = s;
    }
}
테스트 1
입력값 〉	[1, 3, 2], ["diamond", "diamond", "diamond", "iron", "iron", "diamond", "iron", "stone"]
기댓값 〉	12
실행 결과 〉	실행한 결괏값 9이 기댓값 12과 다릅니다.
출력 〉	
3,2,0
1,1,1
테스트 2
입력값 〉	[0, 1, 1], ["diamond", "diamond", "diamond", "diamond", "diamond", "iron", "iron", "iron", "iron", "iron", "diamond"]
기댓값 〉	50
실행 결과 〉	테스트를 통과하였습니다.
출력 〉	
5,0,0
1,0,0
0,5,0

오 이제 똑바로 들어가짐!!!

오… 근데 곡괭이 소진 이슈가 있는걸 생각을 못 해서 …

1,0,0은 원래대로라면 곡괭이가 다 떨어지고 나오는 건데 그 앞의 5개를 건너뛰고 저걸 캘 수 없어서

알고리즘 바꿔줌

 

곡괭이 갯수대로만 넣어주고 정렬하면 될듯함!!

import java.util.Arrays;
import java.lang.Math;

class Solution {
    public int solution(int[] picks, String[] minerals) {
        
        int allpicks = 0;
        for(int i: picks){
            allpicks += i;
        }
        
        int number = Math.min(allpicks,(int)Math.ceil(minerals.length/5)+1);

        Group [] groups = new Group[number];
        
        for(int i=0;i<groups.length;i++){
            groups[i] = new Group(0,0,0);
        }

        for(int i=0;i<minerals.length;i++){
            if(i/5>=groups.length){
                break;
            }
            String element = minerals[i];
            if(element.equals("diamond")){
                groups[i/5].diamond++;
            }
            if(element.equals("iron")){
                groups[i/5].iron++;
            }
            if(element.equals("stone")){
                groups[i/5].stone++;
            }            
        }
        //정렬 후 계산
        
        Arrays.sort(groups);
        
        for(int i=0;i<groups.length;i++){
            Group g =groups[i];
            System.out.println(g.diamond+","+g.iron+","+g.stone);
        }
        
        int [] toolcost = {25,5,1};
        
        int index = 0;
        int sum = 0;
        for(int i=0; i<groups.length; i++){
            
            if(index >= picks.length) {
                break;
            }

            while(picks[index] <= 0) {
                index++;
            } 
            
            picks[index]--;
            
            sum += mine(groups[i].diamond, toolcost[index], 25);
            sum += mine(groups[i].iron, toolcost[index], 5);
            sum += mine(groups[i].stone, toolcost[index], 1);

        }   
            
        return sum;
    }
    
    public int mine(int number, int tool, int cost){
        int i = cost/tool;
        return i*number;
    }
}

class Group implements Comparable<Group>{
    int diamond;
    int iron;
    int stone;
    
    public int compareTo(Group o){
        if(this.diamond>o.diamond){
            return -1;
        }else if(this.diamond==o.diamond){
            if(this.iron>o.iron){
                return -1;
            }else if(this.iron==o.iron){
                return 0;
            }
        }
        return 1;
    }
    
    public Group(int d, int i, int s){
        diamond = d;
        iron = i;
        stone = s;
    }
}
테스트 1
입력값 〉	[1, 3, 2], ["diamond", "diamond", "diamond", "iron", "iron", "diamond", "iron", "stone"]
기댓값 〉	12
실행 결과 〉	실행한 결괏값 9이 기댓값 12과 다릅니다.
출력 〉	
3,2,0
1,1,1
테스트 2
입력값 〉	[0, 1, 1], ["diamond", "diamond", "diamond", "diamond", "diamond", "iron", "iron", "iron", "iron", "iron", "diamond"]
기댓값 〉	50
실행 결과 〉	테스트를 통과하였습니다.
출력 〉	
5,0,0
0,5,0

오 이제 똑바로 들어가지만 피로도 계산이 잘못됨

로그 찍어봄

		      	int mined = 0;
            mined = mine(groups[i].diamond, toolcost[index], 25);
            sum += mined;
            System.out.println("dia"+mined);
            
            mined = mine(groups[i].iron, toolcost[index], 5);
            sum += mined;
            System.out.println("iron"+mined);
            
            mined = mine(groups[i].stone, toolcost[index], 1);
            sum += mined;
            System.out.println("stone"+mined);

3,2,0
1,1,1
dia3
iron0
stone0
dia5
iron1
stone0

1이어야 하는데 0이 되는 이슈가 있길래 1처리 해줌

public int mine(int number, int tool, int cost){
        int i = Math.max(cost/tool,1);
        return i*number;
    }

public int mine(int number, int tool, int cost){
        int i = Math.max(cost/tool,1);
        return i*number;
    }
테스트 1
입력값 〉	[1, 3, 2], ["diamond", "diamond", "diamond", "iron", "iron", "diamond", "iron", "stone"]
기댓값 〉	12
실행 결과 〉	테스트를 통과하였습니다.
출력 〉	3,2,0
1,1,1
dia3
iron2
stone0
dia5
iron1
stone1
테스트 2
입력값 〉	[0, 1, 1], ["diamond", "diamond", "diamond", "diamond", "diamond", "iron", "iron", "iron", "iron", "iron", "diamond"]
기댓값 〉	50
실행 결과 〉	테스트를 통과하였습니다.
출력 〉	5,0,0
0,5,0
dia25
iron0
stone0
dia0
iron25
stone0

통과되어서 코드 제출함!

import java.util.Arrays;
import java.lang.Math;

class Solution {
    public int solution(int[] picks, String[] minerals) {
        
        int allpicks = 0;
        for(int i: picks){
            allpicks += i;
        }
        
        int number = Math.min(allpicks,(int)Math.ceil(minerals.length/5)+1);

        Group [] groups = new Group[number];
        
        for(int i=0;i<groups.length;i++){
            groups[i] = new Group(0,0,0);
        }

        for(int i=0;i<minerals.length;i++){
            if(i/5>=groups.length){
                break;
            }
            String element = minerals[i];
            if(element.equals("diamond")){
                groups[i/5].diamond++;
            }
            if(element.equals("iron")){
                groups[i/5].iron++;
            }
            if(element.equals("stone")){
                groups[i/5].stone++;
            }            
        }
        //정렬 후 계산
        
        Arrays.sort(groups);
        
        int [] toolcost = {25,5,1};
        
        int index = 0;
        int sum = 0;
        for(int i=0; i<groups.length; i++){
            
            if(index >= picks.length) {
                break;
            }

            while(picks[index] <= 0) {
                index++;
            } 
            
            picks[index]--;
            int mined = 0;
            mined = mine(groups[i].diamond, toolcost[index], 25);
            sum += mined;
            
            mined = mine(groups[i].iron, toolcost[index], 5);
            sum += mined;
            
            mined = mine(groups[i].stone, toolcost[index], 1);
            sum += mined;

        }   
            
        return sum;
    }
    
    public int mine(int number, int tool, int cost){
        int i = Math.max(cost/tool,1);
        return i*number;
    }
}

class Group implements Comparable<Group>{
    int diamond;
    int iron;
    int stone;
    
    public int compareTo(Group o){
        if(this.diamond>o.diamond){
            return -1;
        }else if(this.diamond==o.diamond){
            if(this.iron>o.iron){
                return -1;
            }else if(this.iron==o.iron){
                return 0;
            }
        }
        return 1;
    }
    
    public Group(int d, int i, int s){
        diamond = d;
        iron = i;
        stone = s;
    }
}
테스트 1 〉	통과 (0.58ms, 74.4MB)
테스트 2 〉	통과 (0.89ms, 78.9MB)
테스트 3 〉	통과 (0.77ms, 84.1MB)
테스트 4 〉	통과 (0.63ms, 72.3MB)
테스트 5 〉	통과 (0.53ms, 71MB)
테스트 6 〉	통과 (0.69ms, 75.4MB)
테스트 7 〉	통과 (0.56ms, 72.7MB)
테스트 8 〉	통과 (0.79ms, 83.6MB)
테스트 9 〉	통과 (0.79ms, 79MB)
테스트 10 〉	통과 (0.83ms, 77.7MB)
테스트 11 〉	통과 (0.82ms, 78.5MB)
테스트 12 〉	통과 (0.80ms, 78.1MB)
테스트 13 〉	통과 (0.72ms, 73.3MB)
테스트 14 〉	통과 (0.63ms, 77.9MB)
테스트 15 〉	통과 (0.79ms, 79.1MB)
테스트 16 〉	통과 (0.73ms, 71.5MB)
테스트 17 〉	통과 (0.57ms, 77.3MB)
테스트 18 〉	통과 (0.57ms, 76.8MB)
테스트 19 〉	통과 (0.84ms, 72.9MB)
테스트 20 〉	통과 (0.82ms, 72.5MB)
테스트 21 〉	통과 (0.56ms, 71.6MB)
테스트 22 〉	통과 (0.61ms, 77.8MB)
테스트 23 〉	통과 (0.73ms, 82.5MB)
테스트 24 〉	통과 (0.79ms, 85.1MB)
테스트 25 〉	통과 (0.55ms, 77.2MB)
테스트 26 〉	통과 (0.85ms, 74.8MB)
테스트 27 〉	통과 (0.79ms, 67.9MB)
테스트 28 〉	통과 (0.60ms, 74.3MB)
테스트 29 〉	통과 (0.56ms, 74.7MB)
테스트 30 〉	통과 (0.81ms, 77.1MB)
테스트 31 〉	통과 (0.81ms, 76.4MB)
테스트 32 〉	통과 (0.90ms, 80.6MB)
테스트 33 〉	통과 (0.80ms, 75.9MB)
테스트 34 〉	통과 (0.79ms, 73.9MB)
테스트 35 〉	통과 (0.79ms, 74.4MB)

'Coding Test' 카테고리의 다른 글

[백준] 암호 만들기  (1) 2024.04.04
[백준] 주유소  (0) 2024.04.02
[백준] 토마토 7569  (0) 2024.04.02
[프로그래머스] 혼자 놀기의 달인  (0) 2024.04.02
[백준] 블랙잭  (0) 2024.04.01