일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- Algorithm
- pyenv
- codewar
- vscode
- 유닉스의탄생
- organizeImports
- ProxyServer
- flake8
- python
- GlobalInterprintLock
- conf
- maxlinelength
- 코로나백신
- goalng
- printer_helper
- 글쓰기가필요하지않은인생은없다
- pep8
- codewars
- loadimpact
- 조엘온소프트웨어
- opensouce
- typevar
- 독후감
- 규칙없음
- Golang
- httppretty
- Lint
- restfulapi
- springboot
- 오큘러스퀘스트2
- Today
- Total
일상적 이야기들.
codewar: Alphabet war 본문
문제:
- https://www.codewars.com/kata/alphabet-war
Codewars: Train your coding skills
Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.
www.codewars.com
문제풀이:
- 소스는 Java로 작성되었습니다.
- 각 문자는, 점수와 진영이 나눠져있습니다.
- Left 진영: s, b, p, w
- Right 진영: z, d, q, m
- 중립 : 그 외의 문자
- 그리고, 진영의 문자들은 점수가 존재합니다.
- 이 점수들을, 배열의 index로 구성을 하였습니다.
- 또한, 진영은 Left는 '음수', Right는 '양수' 로 구분을 짓습니다.
- 문자열에서, For문을 이용하여 하나의 문자만을 가져오고 ( char word = fight.charAt(i) ),
- 문자가 어느 진영에 포함이 되는지 확인 후 점수를 계산합니다.
- loop: left_word , right_word.
- 그 이후, 합산된 점수를 통하여 Left진영이 이겼는지, Right진영이 이겼는지, 무승부인지 출력을 하게 됩니다.
public class Kata{
public static String alphabetWar(String fight){
char []left_word = {'s', 'b', 'p', 'w'};
char []right_word = {'z', 'd', 'q', 'm'};
int sum = 0;
for(int i=0; i<fight.length(); ++i)
{
char word = fight.charAt(i);
boolean is_hit = false;
for(int j=0; j<left_word.length; ++j)
{
if( left_word[j] == word )
{
int value = j+1;
sum -= value;
is_hit = true;
break;
}
}
if( is_hit ) {
continue;
}
for(int j=0; j<left_word.length; ++j)
{
if( right_word[j] == word )
{
int value = j+1;
sum += value;
}
}
}
String result_msg = "Let's fight again!";
if(sum < 0)
{
result_msg = "Left side wins!";
} else if (sum > 0) {
result_msg = "Right side wins!";
}
return result_msg;
}
}
부연.
해당 문제를 풀 수 있는 방법은 여러가지 케이스가 존재합니다.
1. 위의 풀이와 같이 Left, Right 진영을 배열로 구성을 하여 체크하는 방식
2. HashMap을 이용하여, 각 문자를 key 값으로 점수를 부여하는 방식
3. Switch 문을 이용하여, 점수를 계산하는 방식
점수를 계산할 시에도 다음과 같은 케이스가 존재합니다.
1. 하나의 변수로 관리를 하는 방식 ( Left는 음수, Right는 양수 )
2. 두개의 변수로 관리하는 방식 ( Left Score, Right Score )
'프로그래밍 > 알고리즘 문제풀이' 카테고리의 다른 글
codewar: Errors: histogram (0) | 2019.06.21 |
---|---|
codewar: Scalling Squared Strings. (0) | 2019.06.18 |
codewar: RemoveString Spaces (0) | 2019.06.18 |
codewar: Find the missing letter (0) | 2019.06.12 |
codewar: Beginner - Lost Without a Map (0) | 2019.06.12 |