Light Blue Pointer
본문 바로가기
Coding Test

[프로그래머스] 햄버거 만들기

by Greedy 2023. 12. 16.

문제 주소

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

 

프로그래머스

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

programmers.co.kr

문제 설명

햄버거 가게에서 일을 하는 상수는 햄버거를 포장하는 일을 합니다. 함께 일을 하는 다른 직원들이 햄버거에 들어갈 재료를 조리해 주면 조리된 순서대로 상수의 앞에 아래서부터 위로 쌓이게 되고, 상수는 순서에 맞게 쌓여서 완성된 햄버거를 따로 옮겨 포장을 하게 됩니다. 상수가 일하는 가게는 정해진 순서(아래서부터, 빵 – 야채 – 고기 - 빵)로 쌓인 햄버거만 포장을 합니다. 상수는 손이 굉장히 빠르기 때문에 상수가 포장하는 동안 속 재료가 추가적으로 들어오는 일은 없으며, 재료의 높이는 무시하여 재료가 높이 쌓여서 일이 힘들어지는 경우는 없습니다.

예를 들어, 상수의 앞에 쌓이는 재료의 순서가 [야채, 빵, 빵, 야채, 고기, 빵, 야채, 고기, 빵]일 때, 상수는 여섯 번째 재료가 쌓였을 때, 세 번째 재료부터 여섯 번째 재료를 이용하여 햄버거를 포장하고, 아홉 번째 재료가 쌓였을 때, 두 번째 재료와 일곱 번째 재료부터 아홉 번째 재료를 이용하여 햄버거를 포장합니다. 즉, 2개의 햄버거를 포장하게 됩니다.

상수에게 전해지는 재료의 정보를 나타내는 정수 배열 ingredient가 주어졌을 때, 상수가 포장하는 햄버거의 개수를 return 하도록 solution 함수를 완성하시오.


제한사항

  • 1 ≤ ingredient의 길이 ≤ 1,000,000
  • ingredient의 원소는 1, 2, 3 중 하나의 값이며, 순서대로 빵, 야채, 고기를 의미합니다.

입출력 예

ingredient result

[2, 1, 1, 2, 3, 1, 2, 3, 1] 2
[1, 3, 2, 1, 2, 1, 3, 1, 2] 0

입출력 예 설명

입출력 예 #1

  • 문제 예시와 같습니다.

입출력 예 #2

  • 상수가 포장할 수 있는 햄버거가 없습니다.

 

풀이과정

 

1,2,3,1 →이 됐을때 포장함

String화 시켜서 contains 1231 replacefirst1231으로 풀면 편할거같음…

아니면 배열이나 hashmap에 1231나올때마다 넣어두고 모두 있으면 answer에다 더하고 숫자 줄여버리자!!

아 배열이나 hashmap으로 풀면 안됨 순서가 중요해서 ㅋㅋ

queue로 풀어도 될거같긴 한데…

걍 queue로 풀어봄

 

⭐Java queue

import java.util.LinkedList;
import java.util.Queue;
 
public class QueueExample {
    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();
 
        // add elements to the queue
        queue.add("apple");
        queue.add("banana");
        queue.add("cherry");
 
        // print the queue
        System.out.println("Queue: " + queue);
 
        // remove the element at the front of the queue
        String front = queue.remove();
        System.out.println("Removed element: " + front);
 
        // print the updated queue
        System.out.println("Queue after removal: " + queue);
 
        // add another element to the queue
        queue.add("date");
 
        // peek at the element at the front of the queue
        String peeked = queue.peek();
        System.out.println("Peeked element: " + peeked);
 
        // print the updated queue
        System.out.println("Queue after peek: " + queue);
    }
}

앜 ㅋㅋㅋ pop이 왜 없나 찾아다녔는데 내가 하고싶은건 queue가 아니라 stack이었음

https://www.geeksforgeeks.org/stack-class-in-java/

Java stack

// Java code for stack implementation
 
import java.io.*;
import java.util.*;
 
class Test
{   
    // Pushing element on the top of the stack
    static void stack_push(Stack<Integer> stack)
    {
        for(int i = 0; i < 5; i++)
        {
            stack.push(i);
        }
    }
     
    // Popping element from the top of the stack
    static void stack_pop(Stack<Integer> stack)
    {
        System.out.println("Pop Operation:");
 
        for(int i = 0; i < 5; i++)
        {
            Integer y = (Integer) stack.pop();
            System.out.println(y);
        }
    }
 
    // Displaying element on the top of the stack
    static void stack_peek(Stack<Integer> stack)
    {
        Integer element = (Integer) stack.peek();
        System.out.println("Element on stack top: " + element);
    }
     
    // Searching element in the stack
    static void stack_search(Stack<Integer> stack, int element)
    {
        Integer pos = (Integer) stack.search(element);
 
        if(pos == -1)
            System.out.println("Element not found");
        else
            System.out.println("Element is found at position: " + pos);
    }
 
 
    public static void main (String[] args)
    {
        Stack<Integer> stack = new Stack<Integer>();
 
        stack_push(stack);
        stack_pop(stack);
        stack_push(stack);
        stack_peek(stack);
        stack_search(stack, 2);
        stack_search(stack, 6);
    }
}
Pop Operation:
4
3
2
1
0
Element on stack top: 4
Element is found at position: 3
Element not found

import java.io.*;
import java.util.*;

Stack stack1 = new Stack();
Stack<String> stack2 = new Stack<String>();
 
stack1.push("4");

stack2.push("Geeks");

stack.peek();
stack.pop();

stack.isEmpty()

 

    }
}

 

 

import java.util.LinkedList;
import java.util.Stack;
class Solution {
    public int solution(int[] ingredient) {
        Stack<Integer> stack = new Stack<Integer>();
        int answer = 0;
        int [] counts = new int [4];
        for(int i = 0; i<ingredient.length; i++)
        {
            
            if(ingredient[i]==1){
                if(stack.search(3)==0){
                    if(stack.search(2)==1){
                        if(stack.search(1)==2){
                            answer++;
                            stack.pop();
                            stack.pop();
                            stack.pop();
                            continue;
                        }
                    }
                }
            }
            stack.push(new Integer(ingredient[i]));
           
        }
        return answer;
    }
}

0이 나온다

테스트 1
입력값 〉	[2, 1, 1, 2, 3, 1, 2, 3, 1]
기댓값 〉	2
실행 결과 〉	실행한 결괏값 0이 기댓값 2과 다릅니다.
테스트 2
입력값 〉	[1, 3, 2, 1, 2, 1, 3, 1, 2]
기댓값 〉	0
실행 결과 〉	테스트를 통과하였습니다.

answer++; 부분이 하나도 안 되나봄 지금

if(stack.search(3)==0){

Integer랑 int가 비교가 안 되나?

how to compare integer with int

int vs Integer comparison Java

The Integer is compared with . equals while the int uses two equal signs, == . The Integer class is a wrapper class for the int, while the int is not a class at all.

import java.util.LinkedList;
import java.util.Stack;
class Solution {
    public int solution(int[] ingredient) {
        Stack<Integer> stack = new Stack<Integer>();
        int answer = 0;
        int [] counts = new int [4];
        for(int i = 0; i<ingredient.length; i++)
        {
            
            if(ingredient[i]==1){
                if(stack.search(3).equals(new Integer(0))){
                    if(stack.search(2).equals(new Integer(1))){
                        if(stack.search(1).equals(new Integer(2))){
                            answer++;
                            stack.pop();
                            stack.pop();
                            stack.pop();
                            continue;
                        }
                    }
                }
            }
            stack.push(new Integer(ingredient[i]));
           
        }
        return answer;
    }
}

/Solution.java:12: warning: [deprecation] Integer(int) in Integer has been deprecated

if(stack.search(3).equals(new Integer(0))){

^

/Solution.java:12: error: int cannot be dereferenced

if(stack.search(3).equals(new Integer(0))){

^

/Solution.java:13: warning: [deprecation] Integer(int) in Integer has been deprecated

if(stack.search(2).equals(new Integer(1))){

^

/Solution.java:13: error: int cannot be dereferenced

if(stack.search(2).equals(new Integer(1))){

^

/Solution.java:14: warning: [deprecation] Integer(int) in Integer has been deprecated

if(stack.search(1).equals(new Integer(2))){

^

/Solution.java:14: error: int cannot be dereferenced

if(stack.search(1).equals(new Integer(2))){

^

/Solution.java:24: warning: [deprecation] Integer(int) in Integer has been deprecated

stack.push(new Integer(ingredient[i]));

import java.util.LinkedList;
import java.util.Stack;
class Solution {
    public int solution(int[] ingredient) {
        Stack<Integer> stack = new Stack<Integer>();
        int answer = 0;
        int [] counts = new int [4];
        for(int i = 0; i<ingredient.length; i++)
        {
            int pos3 = stack.search(3);
            int pos2 = stack.search(2);
            int pos1 = stack.search(1);
            
            if(ingredient[i]==1){
                if(pos3==0){
                    if(pos2==1){
                        if(pos1==2){
                            answer++;
                            stack.pop();
                            stack.pop();
                            stack.pop();
                            continue;
                        }
                    }
                }
            }
            stack.push(new Integer(ingredient[i]));
           
        }
        return answer;
    }
}

여전히 0이 나옴

테스트 1
입력값 〉	[2, 1, 1, 2, 3, 1, 2, 3, 1]
기댓값 〉	2
실행 결과 〉	실행한 결괏값 0이 기댓값 2과 다릅니다.
테스트 2
입력값 〉	[1, 3, 2, 1, 2, 1, 3, 1, 2]
기댓값 〉	0
실행 결과 〉	테스트를 통과하였습니다.

로그 찍어봄

import java.util.LinkedList;
import java.util.Stack;
class Solution {
    public int solution(int[] ingredient) {
        Stack<Integer> stack = new Stack<Integer>();
        int answer = 0;
        int [] counts = new int [4];
        for(int i = 0; i<ingredient.length; i++)
        {
            int pos3 = stack.search(3);
            int pos2 = stack.search(2);
            int pos1 = stack.search(1);
            
            
            System.out.println(ingredient[i]);
            System.out.println(pos3);
            System.out.println(pos2);
            System.out.println(pos1);
            System.out.println();
            
            if(ingredient[i]==1){
                if(pos3==0){
                    if(pos2==1){
                        if(pos1==2){
                            answer++;
                            stack.pop();
                            stack.pop();
                            stack.pop();
                            continue;
                        }
                    }
                }
            }
            stack.push(new Integer(ingredient[i]));
           
        }
        return answer;
    }
}
테스트 1
입력값 〉	[2, 1, 1, 2, 3, 1, 2, 3, 1]
기댓값 〉	2
실행 결과 〉	실행한 결괏값 0이 기댓값 2과 다릅니다.
출력 〉	
2 -> 처음 들어감
-1
-1
-1

1 -> 두번째로 들어감
-1
1 -> 엥 pos2가 왜 0이 아니고 1이지
-1

1
-1
2
1

2
-1
3
1

3
-1
1
2

1
1
2
3

2
2
3
1

3
3
1
2

1
1
2
3

⚠️아 나는 stack search가 0부터 세어주는줄 알았는데 1부터 세어준다

제출 코드

import java.util.LinkedList;
import java.util.Stack;
class Solution {
    public int solution(int[] ingredient) {
        Stack<Integer> stack = new Stack<Integer>();
        int answer = 0;
        int [] counts = new int [4];
        for(int i = 0; i<ingredient.length; i++)
        {
            int pos3 = stack.search(3);
            int pos2 = stack.search(2);
            int pos1 = stack.search(1);
            
            if(ingredient[i]==1){
                if(pos3==1){
                    if(pos2==2){
                        if(pos1==3){
                            answer++;
                            stack.pop();
                            stack.pop();
                            stack.pop();
                            continue;
                        }
                    }
                }
            }
            stack.push(new Integer(ingredient[i]));
           
        }
        return answer;
    }
}