Contents

Rock, Paper, Scissors (with.Java)

   Feb 1, 2024     1 min read

This article examines the “rock, paper, scissors” problem.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.

Let’s look at the problem first.

problem

Scissors are expressed as 2, rocks are expressed as 0, and paper is expressed as 5.

When rsp, a string representing the order in which Rock, Paper, Scissors is played, is given as a parameter, complete the solution function to return a string representing the cases in which all Rock, Paper, Scissors, stored in rsp, are won.

Restrictions

0 < length of rsp ≤ 100

Returns a string with the same length as rsp.

rsp consists of the numbers 0, 2, and 5.

Input/Output Example

rspresult
“2”“0”
“205”“052”

My solution to the problem

class Solution {
     public String solution(String rsp) {
         StringBuilder answer = new StringBuilder();
         for(char ch : rsp.toCharArray()){
             if(ch == '2'){
                 answer.append('0');
             }else if(ch == '0'){
                 answer.append('5');
             }else{
                 answer.append('2');
             }
         }
         return answer.toString();
     }
}

Solution explanation

Input: rsp - string to convert.

Output: converted string.

Introduction to the functions used: toCharArray(): A method that converts a string to a character array.

Use of constants: In the current code, ‘2’, ‘0’, and ‘5’ are used as constants. You can increase flexibility by replacing these constants with variables.

Input exception handling: You may need exception handling for cases where the input is null or an empty string.

Write test cases: You can verify the stability of your code by writing test cases for various inputs.