Contents

Coffee Errand (with.Java)

   Nov 29, 2023     2 min read

This is a post about the ā€œcoffee errandā€ problem.

Weā€™re going to take a look at solving a coding test problem, reflect on how we solved it, and learn about other ways to solve it.

Letā€™s start with the problem.

The problem

Cheolsoo, the youngest member of the team, wants to buy coffee for his teammates at a cafƩ that only serves Americano and cafƩ latte.

The prices of an Americano and a cafƩ latte are 4500 and 5000 won, respectively, whether cold or hot.

Each team member is asked to write down a menu of what they would like to drink, and it is decided that those who write down only the menu will get a cold one, and those who write down ā€œanythingā€ will get a cold Americano.

Write a solution function that returns the amount of money to be paid at the cafe given the menu written by each employee as a string array order.

Only the following elements of order are allowed, and their meanings are given below.

Meaning of elements in order

ā€œiceamericanoā€, ā€œamericanoiceā€ Cold Americano

ā€œhotamericanoā€, ā€œamericanohotā€ Hot Americano

ā€œicecafelatteā€, ā€œcafelatteiceā€ Cold cafe latte

ā€œhotcafelatteā€, ā€œcafelattehotā€ hot cafe latte

ā€œamericanoā€ Americano

ā€œcafelatteā€ cafe latte

ā€œanythingā€ anything

Example input and output

orderresult
[ā€œcafelatteā€, ā€œamericanoiceā€, ā€œhotcafelatteā€, ā€œanythingā€]19000
[ā€œamericanoiceā€, ā€œamericanoā€, ā€œiceamericanoā€]13500

My solution to the ### problem

class Solution {
    public int solution(String[] order) {
        int answer = 0;
        for(String temp: order){
            if(temp.contains("americano")){
                answer += 4500;
            } else if(temp.contains("cafelatte")){
                answer += 5000;
            } else {
                answer += 4500;
            }
        }
        return answer;
    }
}

solution description

int answer = 0; : Initialize an integer variable answer to store the result.

for(String temp : order) : Iterates over the string array order, examining each order temp.

if(temp.contains(ā€œamericanoā€)) : If the order contains the string ā€œamericanoā€:

Add 4500 to the price.

else if(temp.contains(ā€œcafelatteā€)) : if the order contains the string ā€œcafelatteā€:

Add 5000 to the price.

else : Otherwise (if itā€™s any other drink):

Add 4500 to the price.

return answer;: return answer after calculating the price for all orders.