본문으로 건너뛰기

· 약 16분
karais89

한마디로 닷컴 내용 정리

INTRODUCTION

주어 만들기 서론 1

문장의 구조

  • 주어 + 동사 + 목적어 + 보어 + 부사
    • She bought a car (보어 X) yesterday
    • He is (목적어 X) ateacher now
    • Tom makes her angry all the time (5형식)
    • 영어는 이 순서에 맞게 단어를 배열한다고 봐도 좋다.
    • (주어)명사 + (동사)동사 + (목적어)명사 + (보어)명사/형용사 + (부사)전치사구 등
    • 문장에는 명사가 많다. 5개 주에 3개 정도가 명사로 이루어져 있다.

주어 만들기 서론 2

명사란 도대체 뭐야?

1) 대명사

  • He is right
    • 그는
    • He = the man 2단어 명사를 "딱 한마디로" 줄인 형태
    • 대명사는 "긴 명사를 딱 한 단어로 줄인 것"

2) 명사

  • God is almighty
    • 신은
    • 사물의 이름이나 명칭

3) 명사구

  • The title of this book is "도가니"
    • 이 책의 제목은
    • 여러 단어로 이루어진 하나의 명사 의미 단위

4) To V

  • To study English is hard
    • 영어 공부하는 건
    • 앞으로 ~하려고 하는 상황

5) V-ing

  • Watching TV is my hobby
    • TV 보는 건
    • 지금 ~하고 있는 장면

6) 명사절

  • Why you love me is a mystery.
    • 왜 니가 날 사랑하는 지

내용은 똑같지만 "어순" 혹은 "순서"만 다르다.

우리말에서도 다양한 명사가 있다. 국어를 잘하는 사람은 영어를 잘할 수 밖에 없다.

주어 만들기 서론 3

명사는 주어, 목적어, 보어, 전치사의 목적어 역할을 할 수 있다.

1) 대명사

  • it
  • It을 주어, 목적어, 보어, 전치사의 목적어로 응용하기
    • It is good. (주어)
    • I love it. (목적어)
    • This is it. (보어) be 동사 뒤는 보어로 많이 쓰인다.
    • Let me talk about it. (전치사 + 명사 (전명구))

2) 명사

  • Tom
  • Tom을 주어, 목적어, 보어, 전치사의 목적어로 응용하기
    • Tom is good. (주어)
    • I love Tom. (목적어)
    • This is Tom. (보어) be 동사 뒤는 보어로 많이 쓰인다.
    • Let me talk about Tom. (전치사 + 명사 (전명구))

3) 명사구

  • One of them
  • One of them을 주어, 목적어, 보어, 전치사의 목적어로 응용하기
    • One of them is good. (주어)
    • I love one of them. (목적어)
    • This is one of them. (보어) be 동사 뒤는 보어로 많이 쓰인다.
    • Let me talk about one of them. (전치사 + 명사 (전명구))

4) To V

  • To study English
  • To study English을 주어, 목적어, 보어, 전치사의 목적어(X)로 응용하기
    • To study English is good. (주어)
    • I love to study English. (목적어)
    • This is to study English. (보어 의미가 어색해서 X) -> 이 문장에서 X
    • Let me talk about to study English. (전치사의 목적어 X)
      • 전치사 다음에는 To 가 못온다 ING만 올 수 있다. 이건 외워야 됨!

5) V-ing

  • Studying English
  • Studying English을 주어, 목적어, 보어, 전치사의 목적어로 응용하기
    • Studying English is good. (주어)
    • I love studying English. (목적어)
    • This is studying English. (보어 의미가 어색해서 X) -> 이 문장에서 X
    • Let me talk about studying English. (전치사 + 명사 (전명구))

6) 명사절

  • Why you love me
  • Why you love me을 주어, 목적어, 보어, 전치사의 목적어로 응용하기
    • Why you love me is a non-sense. (주어)
    • I know why you love me. (목적어)
    • This is why you love me. (보어)
    • Let me talk about why you love me. (전치사 + 명사 (전명구))

주어 만들기 서론 4

"그녀의 고향"이라는 명사를 주어, 목적어, 보어, 전치사의 목적어로 활용 "her home town"

  • 그녀의 고향은 서울입니다.
    • 주어
    • Her home town is Seoul
  • 나는 그녀의 고향을 압니다.
    • 목적어
    • I know her home town
  • 여기가 그녀의 고향입니다.
    • 보어
    • Here(This) is her home town
  • 그녀의 고향에 대해 제가 질문해도 되나요?
    • 전치사의 목적어
    • Can I ask a question about her home town?

"영화보는 것"이라는 명사를 주어, 목적어, 보어, 전치사의 목적어로 활용 "watching a movie"

  • 영화보는 것은 그녀의 취미입니다
    • 주어
    • Watching a movie is her hobby.
  • 그녀는 나와 함께 영화보는 것을 좋아하니다.
    • 목적어
    • She likes watching a movie with me.
  • 나의 취미 역시 영화보는 것입니다.
    • My hobby is watching a movie too.
  • 우리는 영화보는 것을 위하여 많은 돈을 썻습니다.
    • We spent much money for watching a movie

CHAPTER 1 - UNIT 1

주어에는 6가지 종류가 있다.

대명사, 명사, 명사구의 주어는 생략한다 (쉽다)

TO부정사, ING, 명사절 복잡한 주어로 구성된 문장을 연습한다.

TO부정사 주어 1

  • 진지한 검토 없이 우리 마을에 새 공장을 세우는 것은 좋은 생각이 아니다
    • 진지한 검토 없이 우리 마을에 새 공장을 세우는 것은 (주어)
      • 세우는 것 / 새 공장을 / 우리 마을에 / 진지한 검토 없이
      • To build / a new factory / in our town / without serious consideration
    • 좋은 생각이 아니다 (서술어)
      • is not a good idea.
    • It is not a good idea to build a new factory in our town without serious consideration
      • 가주어/진주어
      • It은 뜻이 있다.

TO부정사 주어 2

  • 앞으로 3년안에 최대한 많은 나라를 방문하는 것이 내 꿈이다.
    • 앞으로 3년안에 최대한 많은 나라를 방문하는 것이 (주어)
    • It is my dream / to visit / as many countries / as possible / in 3 years / from now.

TO부정사 주어 3

  • 단지 당신이 가난하다고 해서 별다른 근거없이 자신을 쓸모없다고 여기는 것은 어리석은 짓이다
    • 단지 당신이 가난하다고 해서 별다른 근거없이 자신을 쓸모없다고 여기는 것(주어)
    • 어리석은 짓이다 (서술어)
    • It is stupid / to regard / yourself / as useless (one) / without specific ground / just because you are poor

TO부정사 주어 4

  • 풍부한 미네랄을 포함하는 물을 매일 5잔 이상 마시는 것은 당신의 건강을 위해 매우 좋다.
    • 풍부한 미네랄을 포함하는 물을 매일 5잔 이상 마시는 것은 (주어)
    • 당신의 건강을 위해 매우 좋다. (서술어)
    • It is very beneficial / for your health / to drink / everyday / more / than 5 glasses / of water / containing / abundant minerals.

TO부정사 주어 5

  • 모든 사람들이 수긍하는 적절한 근거없이 남들을 비난하는 것은 옳지 않다.
    • It is not right / to blame / others (other people) / without proper ground / (that) everyone agrees to.

TO부정사 주어 6

  • 나는 스터디그룹에서 다른 사람들과 함께 공부하는 것보다 도서관에서 혼자 공부하는걸 선호한다.
    • 나는 (주어)
    • 목적어 연습용 문장
    • I prefer / to study / alone (by myself) / in the library / than / to study / (together) / with others / in a study group.
    • A than B

CHAPTER 1 - UNIT 2

ING(동명사) 주어 1

동명사는 ing형의 여러가지 이름 중 하나 입니다.

  • 그 자동차는 / 새거다.

    • 명사 주어
    • The car is brandnew.
  • 커피 마시는 것은 / 건강에 좋다.

    • 동명사 주어
    • Drinking coffee is good for health.
  • Go

    • Going / to North Korea / with kim taehee / next year / is illegal.
      • 가는 것 / 북한으로 / 김태희랑 / 내년에 / 불법이다.
      • 주어 : Going / to North Korea / with kim taehee / next year
      • 서술어 : is illegal.
      • It is illegal
    • 주어
    • 목적어
      • I enjoyed / going to North Korea with kim taehee last year
    • 보어
      • My plan is / going to North Korea with kim taehee next year
        • 계획은 미래를 나타내기 때문에 going 보다는 to go가 더 낫긴 하다.
    • 전명구
      • I talked about / going to North Korea with kim taehee next year
  • Water

    • Water is important
    • I need water.
    • This is water.
    • I heard about water.

ING(동명사) 주어 2

  • 지금보다 훨씬 더 많은 직원들을 고용하는 것은 돈 낭비이다.
    • 주어 : 지금보다 훨씬 더 많은 직원들을 고용하는 것은
    • 서술어 : 돈 낭비이다.
    • 고용하는 것 / 훨씬 더 많은 직원들을 / 지금보다 / 돈 낭비이다
    • Hiring / much more employees / than now / is waste of money.
    • 지금보다 훨씬 더 많은 책을 읽는 것은 시간 낭비이다.
      • Reading much more books than now is waste of time.
  • 이 보고서를 다음주 월요일까지 완성하는 건 나에게 거의 불가능하다.
    • 주어 : 이 보고서를 다음주 월요일까지 완성하는 건
    • 서술어 : 나에게 거의 불가능하다.
    • Completing / this report / by next Monday(Monday next week) / is almost imposible for me
    • 이 책을 다음 주 월요일까지 끝내는 건 나에게 거의 불가능하다.
      • Finishing this book by next Monday is almost impossible for me
    • It is almost impossible for me completing this report by next Monday.

ING(동명사) 주어 3

  • 임시 직원에게 충분한 관심을 주는것은 고용주의 기본적인 의무이다.
    • part-time worker 임시직원, 아르바이트
    • pay attention 관심을 주다
    • employer 고용주
    • basic 기본적인
    • duty 의무
    • 주어 : 임시 직원에게 충분한 관심을 주는것은
    • 서술어 : 고용주의 기본적인 의무이다.
    • Paying / enough attention / to temporary employees / is a basic duty / of employers.
  • 이번에 이 광고를 선택하는것은 당신의 회사에 큰 혜택을 가져올 것이다.
    • 주어 : 이번에 이 광고를 선택하는것은
    • Choosing / this advertisement / this time / will bring a huge benefit / to your company

ING(동명사) 주어 4

  • 이 기계를 최적의 상태로 유지하는 것은 그 경쟁에서 승리하기 위해 매우 중요하다.
    • optimal : 최적의
    • maintain : 유지하다
    • competition : 경쟁
    • 주어 : 이 기계를 최적의 상태로 유지하는 것
    • 서술어 : 그 경쟁에서 승리하기 위해 매우 중요하다.
    • 서술어도 길기 때문에 가주어 진주어를 안해도 된다.
    • Maintaining / this machine / in optimal condition / is very important / for winning (in order to win) / in the competition
    • Maintaining is very important. 에서 시작 되었다.

ING(동명사) 주어 5

  • 당신의 인생을 그런 남자를 위해 낭비하는 것은 좋은 생각이 아니다.
    • 주어: 당신의 인생을 그런 남자를 위해 낭비하는 것은
    • such a 명사 : 그런(따위) ~
    • Wasting / your life / for such a man / is not a good idea.
    • It is not a good idea wasting your life for such a man.
  • 못생긴 남자와 지루한 영화를 보는 건 그녀에게 별난 일이 아니었다.
    • 주어 : 못생긴 남자와 지루한 영화를 보는 건
    • Watching / a boring movie / with an ugly man / was not uncommon / for her
    • bore : 지루하게 하다
    • boring : 지루하게 하는
    • common : 흔한
    • uncommon : 별난
  • 재미없는 책을 읽는 것이 재미없는 여자와 데이트하는 것보다 훨씬 낫다
    • 주어 : 재미없는 책을 읽는 것
    • Reading / a boring book / is much better / than dating / (with) a boring woman.
    • than : ~보다
    • A is better than B

ING(동명사) 주어 6

  • 오늘 당신의 아내를 화나게 만드는 건 내일 당신을 미치게 할 거다.
    • 주어 : 오늘 당신의 아내를 화나게 만드는 건
    • Making / your wife / angry / today / will make / you(yourself) / crazy / tomorrow.
  • 나쁜 아내와 한 집에 사는 건 황야에서 혼자 사는 것보다 훨씬 나쁘다.
    • 주어 : 나쁜 아내와 한 집에 사는 건
    • the same : 똑같은
    • bad - worse - worst
    • Living / with a bad wife / in the same house / is much worse than living alone in the wild.

· 약 2분
karais89

Instructions

Instructions A stream of data is received and needs to be reversed.

Each segment is 8 bits long, meaning the order of these segments needs to be reversed, for example:

11111111 00000000 00001111 10101010
(byte1) (byte2) (byte3) (byte4)

should become:

10101010 00001111 00000000 11111111
(byte4) (byte3) (byte2) (byte1)

The total number of bits will always be a multiple of 8.

The data is given in an array as such:

[1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]

My Solution

namespace Main{

using System;
public class Kata
{
public static int[] DataReverse(int[] data)
{
const int SEG_COUNT = 8;
int segNum = data.Length / SEG_COUNT;
int[] dataRevers = new int[data.Length];
for (int i = 0; i < data.Length; i++)
{
int currSeg = i / SEG_COUNT;
int idx = ((segNum - currSeg - 1) * SEG_COUNT) + i % SEG_COUNT;
dataRevers[idx] = data[i];
}

return dataRevers;
}
}
}

8 비트씩 끊어서 뒤에다 정렬해 줘야되는 문제 for문에서 해당 인덱스값으로 변환해주어서 해결 하였다.

Best Practices

namespace Main
{

using System;
public class Kata
{
public static int[] DataReverse(int[] data)
{
int[] bits = data;

for(int i = 0; i < data.Length; i+=8)
{
Array.Reverse(bits, i, 8);
}

Array.Reverse(bits);

return bits;
}
}
}

8비트씩 끊어서 리버스를 해준다음에 전체 리버스를 해주면 해당되는 값이 나온다.

이걸 어떻게 생각했지?? 란 생각이 드네.. 기발하네..

(원래 값)
11111111 00000000 00001111 10101010
(8비트 리버스)
11111111 00000000 11110000 01010101
(전체 리버스)
10101010 00001111 00000000 11111111

· 약 2분
karais89

Instructions

You have to extract a portion of the file name as follows:

  • Assume it will start with date represented as long number
  • Followed by an underscore
  • Youll have then a filename with an extension
  • it will always have an extra extension at the end

Inputs:

1231231223123131_FILE_NAME.EXTENSION.OTHEREXTENSION

1_This_is_an_otherExample.mpg.OTHEREXTENSIONadasdassdassds34

1231231223123131_myFile.tar.gz2

Outputs:

FILE_NAME.EXTENSION

This_is_an_otherExample.mpg

myFile.tar

Acceptable characters for random tests:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-0123456789

The recommend way to solve it is using RegEx and specifically groups.

My Solution

using System;

namespace Solution
{
class FileNameExtractor
{
public static bool IsOnlyNumber(string str)
{
foreach (char s in str)
{
if (s < '0' || s > '9')
{
return false;
}
}
return true;
}

public static string ExtractFileName(string dirtFileName)
{
// 앞에 숫자 제외 뒤에 확장자 제거 하고 반환?
string fileName = dirtFileName;
string[] underSplit = dirtFileName.Split('_');
string firstSplit = underSplit[0];
if (IsOnlyNumber(firstSplit))
{
// number remove
int index = fileName.IndexOf('_');
if (index != -1)
{
fileName = fileName.Substring(index + 1);
}
}

// extension remove
int exIndex = fileName.LastIndexOf('.');
if (exIndex != -1)
{
fileName = fileName.Substring(0, exIndex);
}

// Your code here
return fileName;
}
}
}

문제 자체에 아예 정규 표현식을 사용하라고 나와있다.

하지만 나는 당당히.. 정규 표현식을 사용하지 않고 풀어야지..

해결 방법은 간단하다.

  1. 언더스코어(_) 기준으로 문자열을 쪼갠다음에 맨 첫번째 문자가 숫자로 구성되어 있으면 제거 해준다.
  2. 점(.) 기준으로 또 문자열을 찾은다음에 찾은 문자열 다음에는 제거 해준다.
  3. 구한 값을 리턴 해준다.

Best Practices

using System.Text.RegularExpressions;

public class FileNameExtractor
{
public static string ExtractFileName(string s) => Regex.Match(s, @"(?<=_).+(?=\.)").Value;
}

정규 표현식을 쓰면 한줄이면 해결 할 수 있다!

· 약 3분

-- title: "[Codewars #24] Alphabet war - airstrike - letters massacre (6kyu)" authors: [karais89]

tags: [codewars, kata]

Instructions

There is a war and nobody knows - the alphabet war! There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began. The letters called airstrike to help them in war - dashes and dots are spreaded everywhere on the battlefield.

Task

Write a function that accepts fight string consists of only small letters and * which means a bomb drop place. Return who wins the fight after bombs are exploded. When the left side wins return Left side wins!, when the right side wins return Right side wins!, in other case return Let's fight again!.

The left side letters and their power:

 w - 4
p - 3
b - 2
s - 1

The right side letters and their power:

m - 4
q - 3
d - 2
z - 1

The other letters don't have power and are only victims. The bombs kills the adjacent letters ( i.e. aaaa => a_a, aa => ____ );

Example

AlphabetWar("s*zz"); //=> Right side wins!
AlphabetWar("*zd*qm*wp*bs*"); //=> Let's fight again!
AlphabetWar("zzzz*s*"); //=> Right side wins!
AlphabetWar("www*www****z"); //=> Left side wins!

My Solution

 using System;
using System.Collections.Generic;

public class Kata
{
public static string AlphabetWar(string fight)
{
Dictionary<char, int> leftSideScores = new Dictionary<char, int>()
{
{ 'w', 4 }, { 'p', 3 }, { 'b', 2 }, { 's', 1 }
};

Dictionary<char, int> rightSideScores = new Dictionary<char, int>()
{
{ 'm', 4 }, { 'q', 3 }, { 'd', 2 }, { 'z', 1 }
};

// remove *
char[] arr = fight.ToCharArray();
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == '*')
{
arr[i] = '_';

if (i-1 >= 0 && arr[i-1] != '*')
arr[i-1] = '_';

if (i+1 < arr.Length && arr[i+1] != '*')
arr[i+1] = '_';
}
}

int totalLeftScore = 0;
int totalRightScore = 0;
for (int i = 0; i < arr.Length; i++)
{
if (leftSideScores.ContainsKey(arr[i]))
totalLeftScore += leftSideScores[arr[i]];
else if (rightSideScores.ContainsKey(arr[i]))
totalRightScore += rightSideScores[arr[i]];
}


if (totalLeftScore > totalRightScore)
{
return "Left side wins!";
}
else if (totalLeftScore < totalRightScore)
{
return "Right side wins!";
}

return "Let's fight again!";
}
}

Left Side Score 및 Right Side Score의 경우 딕셔너리에 저장해서 사용. String을 Char 배열로 만든 후에 *의 제거 처리를 하고, 점수를 구하는 식으로 해결

Best Practices

using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
using System.Collections.Generic;
public class Kata
{
public static string AlphabetWar(string fight)
{
Regex rgx = new Regex(@"\w{0,1}[*+]\w{0,1}");
int leftPower = 0;
int rightPower = 0;
string afterBombing = rgx.Replace(fight, "");
foreach(char c in afterBombing)
{
if(lefts.ContainsKey(c)) leftPower += lefts[c];
else if(rights.ContainsKey(c)) rightPower += rights[c];
}
if (leftPower == rightPower) return "Let's fight again!";
else return (leftPower > rightPower)? "Left side wins!":"Right side wins!";
}
}
  • 문자를 제거하는 부분을 정규 표현식을 사용하여 코드의 길이를 줄였다. 나머지 점수를 구하는 방식은 똑같다.

· 약 2분
karais89

Instructions

Given a node object representing a binary tree:

Node:
value: <int>,
left: <Node> or null,
right: <Node> or null

Node:
value: <int>,
left: <Node> or null,
right: <Node> or null

struct node
{
int value;
node* left;
node* right;
}

public class Node
{
public int Value;
public Node Left;
public Node Right;

public Node(int value, Node left = null, Node right = null)
{
Value = value;
Left = left;
Right = right;
}
}

write a function that returns the sum of all values, including the root. Absence of a node will be indicated with a null value.

10
| \
1 2
=> 13

1
| \
0 0
\
2
=> 3

My Solution

using System;
using System.Collections.Generic;

public static class Kata
{
public static int SumTree(Node root)
{
return RecusiveTree(root);
}

public static int RecusiveTree(Node root)
{
if (root == null)
{
return 0;
}

if (root.Left == null && root.Right == null)
{
return root.Value;
}

if (root.Left != null && root.Right != null)
{
return root.Value + RecusiveTree(root.Left) + RecusiveTree(root.Right);
}
else if (root.Right != null)
{
return root.Value + RecusiveTree(root.Right);
}
else if (root.Left != null)
{
return root.Value + RecusiveTree(root.Left);
}
return 0;
}
}

전체 트리의 합 구하는 문제

트리의 합은 재귀 호출 밖에 없나?? 라는 생각을 하면서 재귀 호출을 사용하여 구하였다..

Best Practices

using System;

public static class Kata
{
public static int SumTree(Node root)
{
return root == null ? 0 : root.Value + SumTree(root.Left) + SumTree(root.Right);
}
}

재귀 호출을 사용하여 해결 한줄로 짤 수 있는 코드 였구나..

쓸데 없는 비교 검사문등을 집어 넣어서, 코드가 길어 졌다. 반성 하자.

재귀 호출을 사용하지 않고 해결하는 방법

public static void preTraverseNoRec(Node root){
Stack<Node> stack = new Stack<eNode>();
stack.push(root);
while(stack.size()!=0) {
Node node = stack.pop();
System.out.println(node.data);
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
}
}

· 약 3분
karais89

Instructions

In this kata you parse RGB colors represented by strings. The formats are primarily used in HTML and CSS. Your task is to implement a function which takes a color as a string and returns the parsed color as a map (see Examples).

Input: The input string represents one of the following:

  • 6-digit hexadecimal - "#RRGGBB" e.g. "#012345", "#789abc", "#FFA077" Each pair of digits represents a value of the channel in hexadecimal: 00 to FF
  • 3-digit hexadecimal - "#RGB" e.g. "#012", "#aaa", "#F5A" Each digit represents a value 0 to F which translates to 2-digit hexadecimal: 0->00, 1->11, 2->22, and so on.
  • Preset color name e.g. "red", "BLUE", "LimeGreen" You have to use the predefined map PRESET_COLORS (JavaScript, Python, Ruby), presetColors (Java, C#, Haskell), or preset-colors (Clojure). The keys are the names of preset colors in lower-case and the values are the corresponding colors in 6-digit hexadecimal (same as 1. "#RRGGBB").
Parse("#80FFA0") === new RGB(128, 255, 160))
Parse("#3B7") === new RGB( 51, 187, 119))
Parse("LimeGreen") === new RGB( 50, 205, 50))

// RGB struct is defined as follows:
struct RGB
{
public byte r, g, b;
public RGB(byte r, byte g, byte b);
}

My Solution

using System;
using System.Collections.Generic;

class HtmlColorParser
{
private readonly IDictionary<string, string> presetColors;

public HtmlColorParser(IDictionary<string, string> presetColors)
{
this.presetColors = presetColors;
}

public RGB Parse(string color)
{
string sixDigit = color;
if (color.Substring(0, 1) == "#")
{
if (color.Length == 4)
{
string r = color.Substring(1, 1);
string g = color.Substring(2, 1);
string b = color.Substring(3, 1);

sixDigit = $"#{r}{r}{g}{g}{b}{b}";
}
}
else
{
string colorLow = color.ToLower();
sixDigit = presetColors[colorLow];
}

byte[] rgb = new byte[3];
for (int i = 0; i < rgb.Length; i++)
{
string hex = sixDigit.Substring((i*2) + 1, 2);
rgb[i] = Convert.ToByte(hex, 16);
}

return new RGB(rgb[0], rgb[1], rgb[2]);
}
}

3-digit일때 굳이 Substring으로 변환 하나하나 받아와서 사용하지 않고, 바로 인덱스에 접근하면 되는데.. 쓸데 없는 짓을 했네..

Best Practices

using System;
using System.Collections.Generic;

class HtmlColorParser
{
private readonly IDictionary<string, string> presetColors;

public HtmlColorParser(IDictionary<string, string> presetColors)
{
this.presetColors = presetColors;
}

public RGB Parse(string color)
{
color = color.ToLower();
string hex;

if (presetColors.ContainsKey(color))
hex = presetColors[color];
else if (color.Length == 4)
hex = string.Format("#{0}{0}{1}{1}{2}{2}", color[1], color[2], color[3]);
else
hex = color;

var n = Convert.ToInt32(hex.Substring(1), 16);
return new RGB((byte)((n >> 16) & 0xFF), (byte)((n >> 8) & 0xFF), (byte)(n & 0xFF));
}
}

제일 높은 표이긴 한데 표 자체가 2개 밖에 없어서 추가 검증이 필요하다. 지금 문제 푸는게 최신 문제 위주로 문제가 주어지나 싶다..

16진수를 RGB 값으로 변환할때 여기서는 그냥 바로 스트링값 전부를 int로 변환했다. 그리고 비트 연산자와 & 연산자를 사용하여 각 값들을 추출해서 사용 함. 이 부분을 좀 볼 필요가 있을 듯하다.

· 약 4분
karais89

Instructions

Longest Palindrome

Find the length of the longest substring in the given string s that is the same in reverse.

As an example, if the input was “I like racecars that go fast”, the substring (racecar) length would be 7.

If the length of the input string is 0, the return value must be 0.

"a" -> 1
"aab" -> 2
"abcde" -> 1
"zzbaabcd" -> 4
"" -> 0

My Solution

using System;
using System.Collections.Generic;
using System.Linq;

public class Kata
{
public static string ReverseString(string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}

public static int GetLongestPalindrome(string str)
{
//your code :)
if (str == null || str.Length == 0)
{
return 0;
}

// 맨 처음 글자와 맨 마지막 글자가 일치하고, 점 점 차이를 좁히면서 모두 일치하면 회문이다?
// 아니면 그냥 처음문자를 뒤집은것과 일치하면 회문?
int longestVal = 0;

// 회문 판단
for (int i = 0; i < str.Length; i++)
{
char ch = str[i];
for (int j = str.Length - 1; j >= i; j--)
{
if (ch != str[j])
{
continue;
}

string subStr = str.Substring(i, j-i+1);
if (subStr == ReverseString(subStr))
{
if (longestVal < subStr.Length)
{
longestVal = subStr.Length;
}
}
}
}

return longestVal;
}
}

회문 판단 알고리즘

내 해결책은 먼저 첫번째 문자 부터 판단하여, 가장 마지막 문자에서부터 문자가 같은지 판단한다. 만약 문자가 같으면 회문이 될 가능성이 있는 문장이므로, ReverseString으로 문자를 뒤짚어도 같은 문자열인지 판단할 후 있다.

Best Practices 1

using System;
using System.Collections.Generic;
using System.Linq;

public class Kata
{
public static int GetLongestPalindrome(string str)
{
//Case String is Null or Empty
if (string.IsNullOrEmpty(str)) return 0;
//Variable to store the length of the longest reversible word
int longest = 0;
//Array with all the subtrings in the string passed to the function
string [] subStrs = GetSubstrings(str);
//For each string in the array verify if it is reversible and if it is,
//compare its length with longest
foreach (string s in subStrs)
longest = IsReversible(s) && s.Length > longest ? s.Length :
longest;
return longest;
}

//Function that verifies if a word is reversible
public static bool IsReversible(string word)
{
char [] temp = word.ToCharArray();
Array.Reverse(temp);
string revWord = new string (temp);
//Console.WriteLine(word + " " + revWord);
return (revWord != word) ? false : true;
}

//Function that gets an array of all the substrings in a string
public static string [] GetSubstrings(string word)
{
int count = 0;
int length = word.Length;
List<string> Substrs = new List<string>();
for (int i = 0; i < word.Length; i++)
{
Substrs.Add(word.Substring(i));
for (int j = 1; j < length; j++)
{
Substrs.Add(word.Substring(i,j));
}
length--;
}
return Substrs.ToArray();
}
}

표 3개를 획득한 답안이다.

Best Practices 2

using System;
using System.Collections.Generic;
using System.Linq;

public class Kata
{
public static bool IsPalindrome(string str)
{
var arr = str.ToCharArray();
Array.Reverse(arr);
var reversed = new string(arr);
return str == reversed;
}

public static int GetLongestPalindrome(string str)
{
if (str == null)
return 0;

int max = 0;
for (int i = 0; i < str.Length; ++i)
for (int j = i; j < str.Length; ++j)
if (IsPalindrome(str.Substring(i, j - i + 1)))
max = Math.Max(max, j - i + 1);

return max;
}
}

이게 더 깔끔한 방법 인듯 하다.

· 약 4분
karais89

Instructions

The prime numbers are not regularly spaced. For example from 2 to 3 the step is 1. From 3 to 5 the step is 2. From 7 to 11 it is 4. Between 2 and 50 we have the following pairs of 2-steps primes:

3, 5 - 5, 7, - 11, 13, - 17, 19, - 29, 31, - 41, 43

We will write a function step with parameters:

  • g (integer >= 2) which indicates the step we are looking for,
  • m (integer >= 2) which gives the start of the search (m inclusive),
  • n (integer >= m) which gives the end of the search (n inclusive)

In the example above step(2, 2, 50) will return [3, 5] which is the first pair between 2 and 50 with a 2-steps.

So this function should return the first pair of the two prime numbers spaced with a step of g between the limits m, n if these g-steps prime numbers exist otherwise nil or null or None or Nothing or [] or "0, 0" or {0, 0} (depending on the language).

Examples:

step(2, 5, 7) --> [5, 7] or (5, 7) or {5, 7} or "5 7"

step(2, 5, 5) --> nil or ... or [] in Ocaml or {0, 0} in C++

step(4, 130, 200) --> [163, 167] or (163, 167) or {163, 167}

See more examples for your language in "RUN" Remarks: ([193, 197] is also such a 2-steps primes between 130 and 200 but it's not the first pair).

step(6, 100, 110) --> [101, 107] though there is a prime between 101 and 107 which is 103; the pair 101-103 is a 2-step.

Notes: The idea of "step" is close to that of "gap" but it is not exactly the same. For those interested they can have a look at http://mathworld.wolfram.com/PrimeGaps.html.

A "gap" is more restrictive: there must be no primes in between (101-107 is a "step" but not a "gap". Next kata will be about "gaps":-).

For Go: nil slice is expected when there are no step between m and n. Example: step(2,4900,4919) --> nil

FUNDAMENTALSNUMBERS

Poweredby qualified Solution:

class StepInPrimes { public static long[] Step(int g, long m, long n) { // your code } } Sample Tests:

using System; using NUnit.Framework;

[TestFixture] public static class StepInPrimesTests {

[Test] public static void test1() {

My Solution

using System;
using System.Text;
public class Kata
{
public static string[] TowerBuilder(int nFloors)
{
string[] towers = new string[nFloors];
int totalCnt = nFloors * 2 - 1;
for (int i = 0; i < nFloors; i++)
{
int spaceCnt = (nFloors - 1 - i) * 2;
int starCnt = totalCnt - spaceCnt;
towers[i] = MakeTowerStr(spaceCnt, starCnt);
}
return towers;
}
private static string MakeTowerStr(int spaceCnt, int starCnt)
{
int halfSpaceCnt = spaceCnt / 2;
StringBuilder sb = new StringBuilder();
// before space
for (int i = 0; i < halfSpaceCnt; i++)
{
sb.Append(" ");
}
// star
for (int i = 0; i < starCnt; i++)
{
sb.Append("*");
}
// after space
for (int i = 0; i < halfSpaceCnt; i++)
{
sb.Append(" ");
}
return sb.ToString();
}
}

학부때 많이 했던 별 찍기 문제.

Best Practices

public class Kata
{
public static string[] TowerBuilder(int nFloors)
{
var result = new string[nFloors];
for(int i=0;i<nFloors;i++)
result[i] = string.Concat(new string(' ',nFloors - i - 1),
new string('*',i * 2 + 1),
new string(' ',nFloors - i - 1));
return result;
}
}

Concat 및 new String의 2번째 인자를 사용하여 깔끔하게 풀었다. String 2번째 인자가 반복할 개수를 받을 수 있는걸 몰라서 괜히 어렵게 풀었다. 문제를 풀때 msdn 한번씩 뒤져보는것도 좋을 수 있겠다.

https://docs.microsoft.com/ko-kr/dotnet/api/system.string?view=netframework-4.7.2

// Create a string that consists of a character repeated 20 times.
string string2 = new string('c', 20);

· 약 5분
karais89

Instructions

The prime numbers are not regularly spaced. For example from 2 to 3 the step is 1. From 3 to 5 the step is 2. From 7 to 11 it is 4. Between 2 and 50 we have the following pairs of 2-steps primes:

3, 5 - 5, 7, - 11, 13, - 17, 19, - 29, 31, - 41, 43

We will write a function step with parameters:

  • g (integer >= 2) which indicates the step we are looking for,
  • m (integer >= 2) which gives the start of the search (m inclusive),
  • n (integer >= m) which gives the end of the search (n inclusive)

In the example above step(2, 2, 50) will return [3, 5] which is the first pair between 2 and 50 with a 2-steps.

So this function should return the first pair of the two prime numbers spaced with a step of g between the limits m, n if these g-steps prime numbers exist otherwise nil or null or None or Nothing or [] or "0, 0" or {0, 0} (depending on the language).

Examples:

step(2, 5, 7) --> [5, 7] or (5, 7) or {5, 7} or "5 7"

step(2, 5, 5) --> nil or ... or [] in Ocaml or {0, 0} in C++

step(4, 130, 200) --> [163, 167] or (163, 167) or {163, 167}

See more examples for your language in "RUN" Remarks: ([193, 197] is also such a 2-steps primes between 130 and 200 but it's not the first pair).

step(6, 100, 110) --> [101, 107] though there is a prime between 101 and 107 which is 103; the pair 101-103 is a 2-step.

Notes: The idea of "step" is close to that of "gap" but it is not exactly the same. For those interested they can have a look at http://mathworld.wolfram.com/PrimeGaps.html.

A "gap" is more restrictive: there must be no primes in between (101-107 is a "step" but not a "gap". Next kata will be about "gaps":-).

For Go: nil slice is expected when there are no step between m and n. Example: step(2,4900,4919) --> nil

My Solution

using System;
using System.Collections.Generic;

class StepInPrimes
{
public static List<long> GetPrimeList(long start, long end)
{
long[] arr = new long[end+1];
for (long i = 0; i < arr.Length; i++)
{
arr[i] = i;
}

for (long i = 2; i < arr.Length; i++)
{
// 이미 체크된 수의 배수는 확인하지 않는다
if (arr[i] == 0)
{
continue;
}

// i를 제외한 i의 배수들은 0으로 체크
for (long j = i + i; j < arr.Length; j += i)
{
arr[j] = 0;
}
}

List<long> newList = new List<long>(arr);
newList.RemoveAll(item => item == 0);
newList.RemoveAll(item => item == 1);
newList.RemoveAll(item => item < start);

return newList;
}

public static long[] Step(int g, long m, long n)
{
List<long> primeNumbers = GetPrimeList(m, n);
for (int i = 0; i < primeNumbers.Count; i++)
{
for (int j = i+1; j < primeNumbers.Count; j++)
{
if (primeNumbers[j] - primeNumbers[i] == g)
{
return new long[] { primeNumbers[i], primeNumbers[j] };
}
}
}

return null;
}
}

처음에 그냥 소수를 그냥 구하는 식으로 해서 문제를 풀려고 했는데 타임아웃이 걸려서 결국 다른 방법으로 문제를 풀어야 했다. 사실 소수를 찾는 방법 중 가장 유명한 에라토스테네스의 체를 이미 알고 있었기 때문에 해당 방법을 찾아서 문제를 풀었다.

Best Practices

using System;
class StepInPrimes
{
public static long[] Step(int g, long m, long n)
{
for (long i = m; i <= n; i++)
{
if (isPrime(i))
{
if (isPrime(i + g) && (i + g) <= n)
{
return new long[2] { i, i + g };
}
}
}
return null;
}

public static bool isPrime(long number)
{
if (number == 1) return false;
if (number == 2) return true;

if (number % 2 == 0) return false; //Even number

for (int i = 3; i <= Math.Ceiling(Math.Sqrt(number)); i += 2)
{
if (number % i == 0) return false;
}
return true;
}
}

제일 높은 표를 받은 해결책이긴 한데 표 자체가 4개 밖에 없어서 추가 검증이 필요하다. 에라토스테네스의 체의 공식을 C#에서 적용하는 다른 소스등을 참고하는게 도움이 될 듯하다. 결국 문제의 핵심은 소수를 구하는 것이다.

아래는 스택 오버플로우에서 찾은 소수 인지 판단하는 함수

https://stackoverflow.com/questions/15743192/check-if-number-is-prime-number

public static bool IsPrime(int number)
{
if (number <= 1) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;

var boundary = (int)Math.Floor(Math.Sqrt(number));

for (int i = 3; i <= boundary; i+=2)
if (number % i == 0)
return false;

return true;
}

· 약 2분
karais89

Instructions

You are given two arrays a1 and a2 of strings. Each string is composed with letters from a to z. Let x be any string in the first array and y be any string in the second array.

Find max(abs(length(x) − length(y)))

If a1 and/or a2 are empty return -1 in each language except in Haskell (F#) where you will return Nothing (None).

Example:

a1 = ["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"]
a2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"]
mxdiflg(a1, a2) --> 13

Bash note:

  • input : 2 strings with substrings separated by ,
  • output: number as a string

My Solution

using System;

public class MaxDiffLength
{

public static int Mxdiflg(string[] a1, string[] a2)
{
if (a1 == null || a1.Length == 0 || a2 == null || a2.Length == 0)
return -1;

int maxVal = int.MinValue;
for (int i = 0; i < a1.Length; i++)
{
for (int j = 0; j < a2.Length; j++)
{
int diff = Math.Abs(a1[i].Length - a2[j].Length);
if (diff > maxVal)
maxVal = diff;
}
}

return maxVal;
}
}

두 배열의 길이의 값 차이 중 가장 큰 값을 구하는 문제

Best Practices

using System;
using System.Linq;

public class MaxDiffLength
{

public static int Mxdiflg(string[] a1, string[] a2)
{
if(a1.Length <= 0 || a2.Length <= 0)
return -1;
var first = Math.Abs(a1.Max(x => x.Length) - a2.Min(x => x.Length));
var second = Math.Abs(a2.Max(x => x.Length) - a1.Min(x => x.Length));
return Math.Max(first, second);
}
}

Linq 사용

a1 최대값 - a2 최소값 혹은 a2 최대값 - a1 최소값 중에 가장 큰 값 반환