본문으로 건너뛰기

· 약 3분
karais89

Instructions

The museum of incredible dull things

The museum of incredible dull things wants to get rid of some exhibitions. Miriam, the interior architect, comes up with a plan to remove the most boring exhibitions. She gives them a rating, and then removes the one with the lowest rating.

However, just as she finished rating all exhibitions, she's off to an important fair, so she asks you to write a program that tells her the ratings of the items after one removed the lowest one. Fair enough.

Task

Given an array of integers, remove the smallest value. Do not mutate the original array/list. If there are multiple elements with the same value, remove the one with a lower index. If you get an empty array/list, return an empty array/list.

Don't change the order of the elements that are left.

Remover.RemoveSmallest(new List<int>{1,2,3,4,5}) = new List<int>{2,3,4,5}
Remover.RemoveSmallest(new List<int>{5,3,2,1,4}) = new List<int>{5,3,2,4}
Remover.RemoveSmallest(new List<int>{2,2,1,2,1}) = new List<int>{2,2,2,1}

My Solution

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

public class Remover
{
public static List<int> RemoveSmallest(List<int> numbers)
{
// Good Luck!
if (numbers == null || numbers.Count == 0)
{
return new List<int>() { };
}

int minVal = int.MaxValue;
int minIndex = 0;
for (int i = 0; i < numbers.Count; i++)
{
if (minVal > numbers[i])
{
minVal = numbers[i];
minIndex = i;
}
}

List<int> removeSmallests = new List<int>(numbers);
removeSmallests.RemoveAt(minIndex);
return removeSmallests;
}
}

문제 자체는 전달 받은 리스트의 값 변경 없이 최소 값을 뺀 리스트를 반환하는 문제이다.

전달 받은 리스트에서 최소값을 구하고, 그 리스트를 복사한후 최소값을 구한 인덱스를 빼준후 반환해 주는 식으로 구했다.

Best Practices

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

public class Remover
{
public static List<int> RemoveSmallest(List<int> numbers)
{
numbers.Remove(numbers.DefaultIfEmpty().Min());
return numbers;
}
}

Linq를 사용하여 해결 하였다. 하지만 목록을 복제하지는 않아서, 문제에서 요구하는 완벽한 해결 방법은 아닌거 같다.

DefaultIfEmpty

  • IEnumerable<T>의 요소를 반환하거나, 시퀀스가 비어 있으면 기본값이 할당된 singleton 컬렉션을 반환합니다

DefaultIfEmpty 메서드는 객체 자체가 null 일때의 예외 처리도 함께 되어 있다.

public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source, TSource defaultValue)
{
if (source == null)
throw Error.ArgumentNull(nameof (source));
return Enumerable.DefaultIfEmptyIterator<TSource>(source, defaultValue);
}

· 약 2분
karais89

Instructions

All of the animals are having a feast! Each animal is bringing one dish. There is just one rule: the dish must start and end with the same letters as the animal's name. For example, the great blue heron is bringing garlic naan and the chickadee is bringing chocolate cake.

Write a function feast that takes the animal's name and dish as arguments and returns true or false to indicate whether the beast is allowed to bring the dish to the feast.

Assume that beast and dish are always lowercase strings, and that each has at least two letters. beast and dish may contain hyphens and spaces, but these will not appear at the beginning or end of the string. They will not contain numerals.

My Solution

public class Kata
{
public static bool Feast(string beast, string dish)
{
return beast[0] == dish[0] && beast[beast.Length-1] == dish[dish.Length-1];
}
}```


맨 처음 문자열과 맨 마지막 문자열만 같으면 된다.

## Best Practices 1

```csharp
public class Kata
{
public static bool Feast(string beast, string dish)
{
return beast[0] == dish[0] && beast[beast.Length - 1] == dish[dish.Length - 1];
}
}

푸는 방식이 완전히 동일하여 다른 방식이 있나 보니 Linq를 사용하는 방식이 있다.

Linq를 사용하는 방식이 더 직관적인 것 같은데.. 이런걸 보면 무슨 기준으로 표를 주는건지 잘 모르겠다..

Best Practices 2

using System.Linq;

public class Kata
{
public static bool Feast(string beast, string dish) => beast.First() == dish.First() && beast.Last() == dish.Last();
}

· 약 8분
karais89

book image

기간

2일

목적

프로그래머 관련 서적을 읽고 싶어서 도서관에서 대여 하였다. 샘 라이트스톤이라는 IBM 소속의 소프트웨어 엔지니어 분이 쓴 책. 국내 프로그래머분들의 이야기를 다룬 프로그래머로 산다는 것보다 조금 더 전문적인 내용을 다루고 있다.

리뷰

성공하는 소프트웨어 프로그래머를 위한 경력 관리 비결!

소프트웨어 업계에서 성공하는 방법과 조직 생활에 필요한 기술을 소개하는 책이며, 책 자체는 크게 기본적인 내용, 리더십에 관한 내용, 거성이 되는 것과 관련된 내용 이렇게 세 부분으로 나누어져 있다.

사실 글씨 폰트 자체도 작고, 책 자체가 조금 두꺼운 편이라 분량이 생각보다 많은 책이다.

전반적으로 모든 내용을 책에 담으려고 해서 그런지.. 몇 몇 챕터들의 경우 필요 없는 부분이 존재하여, 넘어가면서 읽었다.

중간 중간 인터뷰 내용 또한 처음에는 좋았지만. 모든 인터뷰는 같은 질문으로 구성되어 있어. 결국 성공하는 사람들의 대답은 거의 한결 같다는 생각? 때문에 뒤에 인터뷰 몇 몇은 넘어갔다.

저자가 프로그래머라서 그런지 몰라도, 중간 중간 부분은 상당히 지루하게 읽혀진다.

그래도 분명히 책의 내용 자체는 좋고, 프로그래머가 되고 싶거나, 현재 프로그래머인 사람이 읽으면 충분히 자극을 받을 수 있는 내용으로 구성되어 있는건 변함없는 사실이다.

책 내용 정리

  • 자기 일에서 재미를 느끼는 것은 어떤 전문 분야에서든 성공적인 커리어에 있어서 결정적인 역할을 한다.
  • 훌륭한 소프트웨어를 만든다는 것은 올바른 시기에 유용한 소프트웨어를 시장에 내놓는것을 뜻한다
  • IBM 의 원칙 : 우리가 하는 모든 일의 원동력은 시장이다
  • 마리사 메이어 : 항상 중요도 순으로 할 일의 목록을 정리 했다. 중요도 순으로 정리하고 맨 위에 있는 것부터 했다. 당연히 더 중요한 일이 생기면 덜 중요한 일은 목록에서 아래로 밀려났다.
  • 회사에서는 혼자서만 일하는 습관을 버리고, 업무는 공유해야 하며 여럿이 함께해야 한다는 믿음을 받아들여야만 한다.
  • 존 벤틀리
    • 만족을 느낄때
      • 어려운 문제 해결
      • 내가 한 일이 널리 쓰이는 것
      • 기술 분야에 파급 효과 미치기
    • 더 열심히 일할수록 더 큰 행운이 찾아온다
    • 자기 자신을 잘 챙기자. 기술 분야는 마라톤과 같다. 자기 페이스를 유지하자.
    • 성공하는 방법에 대한 조언
      • 행복을 찾으세요
      • 배울 수 있는 건 뭐든 배우세요 언젠가, 어딘가에서, 어떤 식으로든 자기 일에도 도움이 될겁니다.
      • 새로운 것을 시도해 보세요. 하지만 옛 것을 지키세요
      • 최고의 사람과 함께 일하세요
      • 조언자를 찾으세요. 자신이 존경하는 사람으로부터 배우세요
      • 자기 팀, 자기 회사, 자기분야, 자기 이웃에게 보답하세요
      • 글쓰기와 코딩을 꾸준히 연습하세요
      • 멋진 사람이 되세요
      • 좋은 책을 읽으세요.
  • 소프트웨어 회사를 살펴 볼 때는 다음과 같이 10가지 생각해 보자
    • 전문적인 고품질 시스템을 만든 경험이 있는 회사인가
    • 뭔가 배울만한 진정 재능을 갖춘 사람 있는 회사인가
    • 내가 들어갈 자리가 흥미로운 잘 있고 내가 믿을 수 있는 것과 관련하여 장기적인 성장가능성을 가진 자리인가
    • 성공하기 위한 필요조건을 제대로 이해하고 실제 성공 실적을 가진 상식에 맞게 행동하는 경영진이 있는 회사입니다
    • 자기가 생산하는 제품에 대한 비전을 분명하게 가지고 있는 회사인가
    • 독립 연구 조직 회사인가
    • 어떻게 혁신하는 회사인가
    • 쾌적하고 유연한 업무환경 갖추고 있는가
    • 회사가 안정적일 것 같은가
    • 업계 표준에 걸맞는 수준의 급여를 지급하는 회사인가
    • 업계 자체의 역동성과 빠른 변화 속도로 인해 누구든 자기 개발과 학습에 초점을 맞춰야 한다
  • 개발자 로써의 첫 5년은 가장 큰 가르침을 얻을 수 있는 시기이다
  • 재능을 극대화 하는 두 가지 중요하지만 급하지 않은 일에 시간을 투자 하는 것이고 다른 하나는 시간이 지남에 따라 고위직 전문가로서의 적합성을 극적으로 향상 해줄 수 있는 EI를 계발 하는 것이다
  • 많이 읽고 많이 대화하고 여러 기술을 써보려고 노력합니다
  • 소프트웨어 관련 직장에서의 초기 적응 기간은 보통 꽤 고통 스럽다. 고통 스럽지만 그게 정상이다.
  • 최고의 위치에 오르는 가장 빠른 방법은 회사를 세워서 키우는 것이다.
  • 성공하는 사람들의 공통점
    • 목표 지향적이다
    • 감성 지능이 높다
    • 엄청나게 똑똑하다
    • 자기 분야의 전문성을 가지고 있다
    • 놀랄 만큼 집요하면서도 예의는 갖출 줄 안다.

평점 및 한줄평

프로그래머로서 인생을 살아갈 분이라면 한번은 읽어봐도 괜찮을 책

4/5

· 약 1분
karais89

Instructions

Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.

invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []

My Solution

using System.Linq;
namespace Solution
{
public static class ArraysInversion
{
public static int[] InvertValues(int[] input)
{
//Code it!
int[] inversArray = new int[input.Length];
for (int i = 0; i < input.Length; i++)
{
inversArray[i] = -input[i];
}
return inversArray;
}
}
}

새로운 배열을 만들고, 역이 되는 정수를 저장하고 반환.

Best Practices

using System.Linq;
namespace Solution
{
public static class ArraysInversion
{
public static int[] InvertValues(int[] input)
{
return input.Select(n => -n).ToArray();
}
}
}

Linq의 Select 함수를 사용하여 역을 만들고 그 역을 배열로 반환해준다.

· 약 2분
karais89

Instructions

Create a function isDivisible(n, x, y) that checks if a number n is divisible by two numbers x AND y. All inputs are positive, non-zero digits.

Example:
isDivisible(3,1,3)--> true because 3 is divisible by 1 and 3
isDivisible(12,2,6)--> true because 12 is divisible by 2 and 6
isDivisible(100,5,3)--> false because 100 is not divisible by 3
isDivisible(12,7,5)--> false because 12 is neither divisible by 7 nor 5

My Solution

public class DivisibleNb {
public static bool isDivisible(long n, long x, long y) {
// your code
return n % x == 0 && n % y == 0;
}
}

조건 자체가 모든 수는 0이 아니고, 자연수이기때문에 따로 조건 체크는 하지 않고, 두개의 수를 나누었을때 나머지가 0이 아닌 경우를 구하여 리턴 해 주었다.

Best Practices

public class DivisibleNb {
public static bool isDivisible(long n, long x, long y) {
return (x != 0 && y != 0 && n % x == 0 && n % y == 0);
}
}

문제 해결 방법은 똑같은것 같고, 여기서는 x, y에 대한 0 검사를 해주어 Division by zero에 대한 처리를 해주었다.

이 해결에 대한 의견으로 아래와 같은 의견이 달림.

All inputs are positive, non-zero digits!
x != 0 && y != 0 superfluous

· 약 1분
karais89

Instructions

Nathan loves cycling.

Because Nathan knows it is important to stay hydrated, he drinks 0.5 litres of water per hour of cycling.

You get given the time in hours and you need to return the number of litres Nathan will drink, rounded to the smallest value.

For example:

time = 3 ----> litres = 1

time = 6.7---> litres = 3

time = 11.8--> litres = 5

My Solution

using System;

public class Kata
{
public static int Litres(double time)
{
int intTime = (int)time;

//The fun begins here.
return (intTime / 2);
}
}

어렵지 않게 해결.

Best Practices

using System;

public class Kata
{
public static int Litres(double time)
{
return (int)(time/2);
}
}

내 해결 방법과 유사하다.

Best Practices 2

using System;

public class Kata
{
public static int Litres(double time) => (int)(time*0.5);

}

2번째로 좋은 Best Practices인데..

C# 6.0 에서 새로 추가된 Expression-bodied member 기능을 사용하여 한줄로 표현 할 수 있다.

· 약 2분
karais89

Instructions

Sum all the numbers of the array (in F# and Haskell you get a list) except the highest and the lowest element (the value, not the index!).

(The highest/lowest element is respectively only one element at each edge, even if there are more than one with the same value!)

{ 6, 2, 1, 8, 10 } => 16
{ 1, 1, 11, 2, 3 } => 6

If array is empty, null or None, or if only 1 Element exists, return 0. Note:In C++ instead null an empty vector is used. In C there is no null. ;-)

-- There's no null in Haskell, therefore Maybe [Int] is used. Nothing represents null.

My Solution

using System;
using System.Linq;

public static class Kata
{
public static int Sum(int[] numbers)
{
if (numbers == null || numbers.Length == 0)
{
return 0;
}

int minVal = numbers[0];
int maxVal = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
if (numbers[i] < minVal)
{
minVal = numbers[i];
}

if (numbers[i] > maxVal)
{
maxVal = numbers[i];
}
}

int sum = 0;
bool isCheckMinVal = false;
bool isCheckMaxVal = false;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == minVal && !isCheckMinVal)
{
isCheckMinVal = true;
continue;
}

if (numbers[i] == maxVal && !isCheckMaxVal)
{
isCheckMaxVal = true;
continue;
}
sum += numbers[i];
}
return sum;
}
}

8kyu 문제인데, 너무 어렵게 풀었다.. 생각해보면 문제 자체가 배열의 합에서 가장 큰 수와 가장 작은 수를 빼라는 문제인데. 가장 큰 수와 가장 작은 수의 배열 자체를 구하려고 해서 문제 자체를 좀 어렵게 풀이 했다. 잘못된 방법인듯.

Best Practices

using System;
using System.Linq;

public static class Kata
{
public static int Sum(int[] numbers)
{
return numbers == null || numbers.Length < 2
? 0
: numbers.Sum() - numbers.Max() - numbers.Min();
}
}

Linq를 사용하면 한줄이면 해결된다..

· 약 2분
karais89

Instructions

Given an array of integers.

Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers.

If the input array is empty or null, return an empty array.

My Solution

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

public class Kata
{
public static int[] CountPositivesSumNegatives(int[] input)
{
if (input == null || input.Length == 0)
{
return new int[] { };
}

int positiveCount = 0;
int negativeSum = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i] > 0)
{
positiveCount++;
}
else
{
negativeSum += input[i];
}
}

return new int[] { positiveCount, negativeSum };
}
}

배열에서 양수의 경우 양수가 몇개 있는지 구하고, 음수의 경우 음수값 합을 구하여 배열로 반환하라.

Best Practices

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

public class Kata
{
public static int[] CountPositivesSumNegatives(int[] input)
{
if(input == null || !input.Any())
{
return new int[] {};
}

int countPositives = input.Count(n => n > 0);
int sumNegatives = input.Where(n => n < 0).Sum();

return new int[] { countPositives, sumNegatives };
}
}

Linq를 사용하여 해결. Codwars에서 C# 문제의 경우 Best Practices의 경우 Linq를 사용하여 풀이한 정답이 채택되는 것 같다. 논리 자체는 Linq를 사용하지 않아도 충분히 해결 가능하지만 Linq 자체의 장점이 분명히 존재하기 때문에 Linq쪽으로 해결하면 Best Practices로 채택되는 것 같다.

· 약 2분
karais89

Instructions

In a factory a printer prints labels for boxes. For one kind of boxes the printer has to use colors which, for the sake of simplicity, are named with letters from a to m.

The colors used by the printer are recorded in a control string. For example a "good" control string would be aaabbbbhaijjjm meaning that the printer used three times color a, four times color b, one time color h then one time color a...

Sometimes there are problems: lack of colors, technical malfunction and a "bad" control string is produced e.g. aaaxbbbbyyhwawiwjjjwwm.

You have to write a function printer_error which given a string will output the error rate of the printer as a string representing a rational whose numerator is the number of errors and the denominator the length of the control string. Don't reduce this fraction to a simpler expression.

The string has a length greater or equal to one and contains only letters from a to z.

My Solution

using System;

public class Printer
{
public static string PrinterError(String s)
{
// your code
// a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z
int totalLength = s.Length;
int wrongCharNum = 0;
for (int i = 0; i < totalLength; i++)
{
if (s[i] > 'm')
wrongCharNum++;
}
return wrongCharNum.ToString() + "/" + totalLength.ToString();
}
}

문자열 중에 m 이상의 문자는 잘못된 문자로 판단하여 더해주면 된다. 처음 문제라 간단한 문제가 나옴.

Best Practices

using System.Linq;

public class Printer
{
public static string PrinterError(string s)
{
return s.Where(c => c > 'm').Count() + "/" + s.Length;
}
}

Linq를 사용하여 해결. Linq 부분은 확실히 볼 필요성이 있는 듯.

· 약 5분
karais89

book image

기간

3일

목적

프로그래머 관련 서적을 읽고 싶어서 도서관에서 대여 하였다.

국내 프로그래머 분들의 이야기를 다루고 있고, 다른 프로그래머 분들은 어떤 생각을 하고 이 업계에 종사하고 있을까? 들여볼 수 있지 않을까 하고 읽게 되었다.

리뷰

행복한 프로그래머가 되기 위한 선배들의 노하우!

같은 프로그래머로써 어떤 생각을 가지고 업계에 종사하고 있고, 조금 더 나은 방향을 제시하고 있다.

책 내용 자체가 어려운 내용을 다루지 않고 있어, 술 술 쉽게 읽을 수 있었다.

책에서는 5명의 저자분들의 각자의 이야기를 담고 있지만, 결국에는 어떤 공통된 의견으로 수렴하게 된다.

결국에는 프로그래밍은 무언가를 창조하기 위한 작업이고, 꾸준히 무언가를 만들어보는 사람이 프로그래밍을 잘 할 수 있다.

아래는 책 내용 중 기억에 남는 글들을 정리한 내용이다.

  • 적당히 좋은 것이 완벽한 것보다 더 낫다
  • 잘못된 선택을 하는 것도 위험하지만 아무런 선택을 하지 않는 것이 더 위험하다
  • 일은 한 번에 단 하나만 수행할 수 있으므로 책상 위엔 지금 처리하고 있는 업무 딱 하나만 있어야 한다
  • 회의는 필요악이 아닌 그냥 악
  • 프로그래머들에게 있어서는 영어는 숙명 이니 받아들여야 한다
  • 지속적으로 영어를 접하는 것이 중요하다고 생각한다
  • 책을 많이 읽자. 기술서적 자기계발 서적도 좋지만 그보다는 고전을 많이 읽으라고 강조하고 싶다.
  • 블로그 활동을 하는 것이다. 블로그를 통해 글쓰기를 많이 하다 보면 표현력이 좋아진다
  • 무언가를 하는 것이 어려운 것이 아니라 하겠다는 마음에 먹기까지가 어려운 것이다
  • 인간관계론
  • 진정한 프로그래머는 "만들고 싶은 프로그램이 있기 때문에" 라고 말하는 사람
  • 전산을 전공하지 않았다면 아래 과목을 공부하기를 추천 한다.\
    • 컴퓨터 프로그래밍
    • 시스템 프로그래밍
    • 프로그래밍의 원리
    • 컴파일러
    • 알고리즘
    • 소프트웨어 공학
    • 자료구조
    • 운영체제
  • 처음부터 크게 시작하는 사람들은 극히 드물다 대부분 작게 시작한다 시작하지 않으면 아무것도 이룰 수 없다
  • 짧은 시간이라도 자신이 만들고 싶은 프로그램에 투자 하기 바란다 완벽히 만들 필요는 없다 부족하지만 최소한의 기능을 만들어서 오픈 하기 바란다

평점 및 한줄평

프로그래머로서 인생을 살아갈 분이라면 한번은 읽어봐도 괜찮을 책

4/5