Coffee Errand (with.Java)
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
order | result |
---|---|
[ā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.