본문으로 건너뛰기

"codewars" 태그로 연결된 63개 게시물개의 게시물이 있습니다.

모든 태그 보기

· 약 2분
karais89

Instructions

링크

In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?

Example:

Kata.MakeNegative(1); // return -1
Kata.MakeNegative(-5); // return -5
Kata.MakeNegative(0); // return 0

Notes:

The number can be negative already, in which case no change is required. Zero (0) is not checked for any specific sign. Negative zeros make no mathematical sense.

My Solution

using System;

public static class Kata
{
public static int MakeNegative(int number)
{
return number > 0 ? -number : number;
}
}

  • 오랜만에 코드워 문제를 다시 풀었다.
  • 난이도 자체는 말도 안되게 쉬운 문제이고, 다양한 방법으로 풀 수 있을 것이라고 기대를 하고 만든 문제인듯 하다.
  • 일단 난 내가 생각하는 정석적인 방법으로 문제를 풀겠다.
  • 이정도 문제의 경우 삼항 연산자를 사용하는게 깔끔할 것 같다.

Best Practices

using System;

public static class Kata
{
public static int MakeNegative(int number)
{
return -Math.Abs(number);
}
}
  • 문제 자체가 무조건 마이너스(-)를 붙이는 문제라, 이게 더 직관적인 해결 방법인 것 같다.
  • 내가 푼 방식은 2번째로 표를 많이 받았다.

· 약 1분
karais89

Instructions

링크

Given an array of integers your solution should find the smallest integer.

For example:

  • Given [34, 15, 88, 2] your solution will return 2
  • Given [34, -345, -1, 100] your solution will return -345

You can assume, for the purpose of this kata, that the supplied array will not be empty.

My Solution

public class Kata
{
public static int FindSmallestInt(int[] args)
{
int min = int.MaxValue;
for (int i = 0; i < args.Length; i++)
{
if (min > args[i])
{
min = args[i];
}
}
return min;
}
}
  • 가장 작은 값을 구하는 간단한 문제다.

Best Practices 1

using System.Linq;

public class Kata
{
public static int FindSmallestInt(int[] args)
{
return args.Min();
}
}
  • Linq의 Min 메서드를 사용

Best Practices 2

using System.Linq;

public class Kata
{
public static int FindSmallestInt(int[] args) => args.Min();

}
  • 위와 똑같은 방식인데 C# 에서 새로 추가된 기능으로 더 짧게 사용할 수 있다.

· 약 3분
karais89

Instructions

링크

In a small town the population is p0 = 1000 at the beginning of a year. The population regularly increases by 2 percent per year and moreover 50 new inhabitants per year come to live in the town. How many years does the town need to see its population greater or equal to p = 1200 inhabitants?

At the end of the first year there will be:
1000 + 1000 * 0.02 + 50 => 1070 inhabitants

At the end of the 2nd year there will be:
1070 + 1070 * 0.02 + 50 => 1141 inhabitants (number of inhabitants is an integer)

At the end of the 3rd year there will be:
1141 + 1141 * 0.02 + 50 => 1213

It will need 3 entire years.

More generally given parameters:

p0, percent, aug (inhabitants coming or leaving each year), p (population to surpass)

the function nb_year should return n number of entire years needed to get a population greater or equal to p.

aug is an integer, percent a positive or null number, p0 and p are positive integers (> 0)

Examples:
nb_year(1500, 5, 100, 5000) -> 15
nb_year(1500000, 2.5, 10000, 2000000) -> 10

Note: Don't forget to convert the percent parameter as a percentage in the body of your function: if the parameter percent is 2 you have to convert it to 0.02.

My Solution

using System;

class Arge {

public static int NbYear(int p0, double percent, int aug, int p) {
// your code
int population = p0;
double per = percent / 100;
int year = 0;

while (true)
{
population += (int)(population * per) + aug;
year++;

if (population >= p)
{
return year;
}
}
return year;
}
}

Best Practices 1

using System;

class Arge {

public static int NbYear(int p0, double percent, int aug, int p) {
int year;
for (year = 0; p0 < p; year++)
p0 += (int)(p0*percent/100) + aug;
return year;
}
}
  • for문을 사용하여 해결

Best Practices 2

using System;

class Arge
{
public static int NbYear(int p0, double percent, int aug, int p)
{
int expectedPopulation = p;

int cityPopulation = p0;
int newInhabitantsPerYear = aug;
double increasePerYear = percent / 100;

int years = 0;

while(cityPopulation < expectedPopulation)
{
cityPopulation += (int)(cityPopulation * increasePerYear) + newInhabitantsPerYear;

years++;
}

return years;
}
}
  • 변수 네이밍이 괜찮아보여서, 기록해봄.

· 약 2분
karais89

Instructions

링크

Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any char.

Examples input/output:

XO("ooxx") => true
XO("xooxx") => false
XO("ooxXm") => true
XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
XO("zzoo") => false

My Solution

using System.Linq;
using System;
public static class Kata
{
public static bool XO (string input)
{
string lowerStr = input.ToLower();
int xCnt = 0, oCnt = 0;
for (int i = 0; i < lowerStr.Length; i++)
{
if (lowerStr[i] == 'x')
{
xCnt++;
}
else if (lowerStr[i] == 'o')
{
oCnt++;
}
}
return xCnt == oCnt;
}
}
  • 모두 소문자로 변경후 해당 문자열의 카운터를 검사한 후 증가.
  • 마지막에 두 문자의 카운터 개수를 비교.
  • 습관적으로 계속 for 문을 사용하는데 foreach 문을 사용 하는게 가독성 부분에서 +1 정도는 나은 부분일 듯 하다.

Best Practices

using System.Linq;
using System;
public static class Kata
{
public static bool XO (string input)
{
return input.ToLower().Count(i => i == 'x') == input.ToLower().Count(i => i == 'o');
}
}
  • Linq는 이미 나올것 같았고. 이 Linq문은 그래도 보기가 편하긴 하다. (조건 자체가 복잡하지 않기 때문에)

· 약 2분
karais89

Instructions

링크

The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:

maxSequence [-2, 1, -3, 4, -1, 2, 1, -5, 4]
-- should be 6: [4, -1, 2, 1]

Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.

Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.

My Solution

public static class Kata {

public static bool IsAllNativeInteger(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] >= 0)
{
return false;
}
}
return true;
}

public static int MaxSequence(int[] arr) {
if (arr == null || arr.Length == 0 || IsAllNativeInteger(arr))
{
return 0;
}

int maxSum = 0;
for (int i = 0; i < arr.Length; i++)
{
int max = 0;
for (int j = i; j < arr.Length; j++)
{
max += arr[j];
if (max > maxSum)
{
maxSum = max;
}
}
}

return maxSum;
}
}
  • 5kyu 문제 자체는 상당히 짧은데 생각해야 되는 것들이 좀 있다.
  • 일단 가장 먼저 생각난건 처음부터 연속된 숫자를 조회하면서 가장 큰 수가 나올때 까지 계속 수를 더해 가는 방법.
  • 이 방법 이외의 방법은 딱히 생각 나지 않는다.

Best Practices

public static class Kata
{
public static int MaxSequence(int[] arr)
{
int max = 0, res = 0, sum = 0;
foreach(var item in arr)
{
sum += item;
max = sum > max ? max : sum;
res = res > sum - max ? res : sum - max;
}
return res;
}
}
  • for문을 한번만 쓰고 해결이 가능한 문제인가보다.

· 약 2분
karais89

Instructions

링크

Your task is to create a function that does four basic mathematical operations.

The function should take three arguments - operation(string/char), value1(number), value2(number). The function should return result of numbers after applying the chosen operation.

Examples:

basicOp('+', 4, 7) // Output: 11
basicOp('-', 15, 18) // Output: -3
basicOp('*', 5, 5) // Output: 25
basicOp('/', 49, 7) // Output: 7

My Solution

namespace Solution
{
public static class Program
{
public static double basicOp(char operation, double value1, double value2)
{
switch (operation)
{
case '+': return value1 + value2;
case '-': return value1 - value2;
case '*': return value1 * value2;
case '/': return value1 / value2;
}

return 0;
}
}
}
  • 문자에 따라 각 연산을 해주면 된다.

Best Practices

namespace Solution
{
public static class Program
{
public static double basicOp(char op, double val1, double val2)
{
switch(op){
case '+': return val1+val2;
case '-': return val1-val2;
case '*': return val1*val2;
case '/': return val1/val2;
default:
throw new System.ArgumentException("Unknown operation!", op.ToString());
}
}
}
}
  • 똑같지만, 여기서는 default일때 예외 발생 코드가 추가되어 있음.

· 약 1분
karais89

Instructions

링크

Given a string, you have to return a string in which each character (case-sensitive) is repeated once.

DoubleChar("String") == "SSttrriinngg"

DoubleChar("Hello World") == "HHeelllloo WWoorrlldd"

DoubleChar("1234!_ ") == "11223344!!__ "

My Solution

using System;
using System.Text;

public class Kata
{
public static string DoubleChar(string s)
{
// your code here
StringBuilder doubleStr = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
doubleStr.Append(s[i]);
doubleStr.Append(s[i]);
}
return doubleStr.ToString();
}
}
  • 각 문자 2번씩 반복 하기.

Best Practices

using System;
using System.Linq;

public class Kata
{
public static string DoubleChar(string s)
{
return string.Join("", s.Select(x => "" + x + x));
}
}
  • Linq 사용.

· 약 2분
karais89

Instructions

링크

Rock Paper Scissors Let's play! You have to return which player won! In case of a draw return Draw!.

Examples:

rps('scissors','paper') // Player 1 won!
rps('scissors','rock') // Player 2 won!
rps('paper','paper') // Draw!

My Solution

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

public class Kata
{
public int getState(string str)
{
switch (str)
{
case "rock": return 1;
case "scissors": return 2;
case "paper": return 3;
}
return 0;
}

public string Rps(string p1, string p2)
{
// "rock", "scissors", "paper"
int diff = getState(p1) - getState(p2);
if (diff == -1 || diff == 2)
{
return "Player 1 won!";
}
else if (diff == 0)
{
return "Draw!";
}

return "Player 2 won!";
}
}
  • 가독성이 떨어진다.
  • 베스트 솔루션 방식처럼 케이스 바이 케이스 별로 스트링을 구해주는게 더 나은 방법 인듯..

Best Practices

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

public class Kata
{
public string Rps(string p1, string p2)
{
if (p1 == p2)
return "Draw!";

if (((p1 == "rock") && (p2 == "scissors")) ||
((p1 == "scissors") && (p2 == "paper")) ||
((p1 == "paper") && (p2 == "rock")))
{
return "Player 1 won!";
}
else
{
return "Player 2 won!";
}
}
}

· 약 2분
karais89

Instructions

링크

The number 89 is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata. What's the use of saying "Eureka"? Because this sum gives the same number.

In effect: 89 = 8^1 + 9^2

The next number in having this property is 135.

See this property again: 135 = 1^1 + 3^2 + 5^3

We need a function to collect these numbers, that may receive two integers a, b that defines the range [a, b] (inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.

Let's see some cases:

sum_dig_pow(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]

sum_dig_pow(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]

If there are no numbers of this kind in the range [a, b] the function should output an empty list.

sum_dig_pow(90, 100) == []

Enjoy it!!

My Solution

using System;
using System.Collections.Generic;
public class SumDigPower {

public static bool IsSumDigNumber(long a)
{
string strA = a.ToString();
long sum = 0;
for (int i = 0; i < strA.Length; i++)
{
int digit = int.Parse(strA[i].ToString());
sum += (long)Math.Pow(digit, i + 1);
}
return sum == a;
}

public static long[] SumDigPow(long a, long b)
{
// your code
List<long> sumDigs = new List<long>();
for (long i = a; i <= b; i++)
{
if (IsSumDigNumber(i))
{
sumDigs.Add(i);
}
}
return sumDigs.ToArray();
}
}
  • 자리수 구하는 건 확실히 그냥 숫자를 string으로 변경하는게 가장 편한 방법인듯 하다.

Best Practices

using System;
using System.Collections.Generic;
using System.Linq;
public class SumDigPower {

public static long[] SumDigPow(long a, long b)
{
List<long> values = new List<long>();
for (long x = a; x <= b; x++)
{
if (x.ToString().Select((c, i) => Math.Pow(Char.GetNumericValue(c), i + 1)).Sum() == x)
values.Add(x);
}
return values.ToArray();
}
}
  • Char.GetNumericValue 메서드
  • 논리는 비슷하지만 Linq 사용으로 코드가 짧아짐.

· 약 2분
karais89

Instructions

링크

Convert number to reversed array of digits Given a random number:

C#: long; C++: unsigned long; You have to return the digits of this number within an array in reverse order.

Example:

348597 => [7,9,5,8,4,3]

My Solution

using System;
using System.Collections.Generic;

namespace Solution
{
class Digitizer
{
public static long[] Digitize(long n)
{
// Code goes here
string str = n.ToString();
char[] chArr= str.ToCharArray();
Array.Reverse(chArr);
long[] longArr = new long[chArr.Length];
for (int i = 0; i < longArr.Length; i++)
{
long number;
if (Int64.TryParse(chArr[i].ToString(), out number))
{
longArr[i] = number;
}
}
return longArr;
}
}
}
  • 8 kyu의 수준을 잘 모르겠다.
  • long형 변수를 스트링으로 변환한다. 그 후 char 배열로 변환하고 역순의 배열을 만든후에 각 변수들을 long 형으로 변환후 반환한다.

Best Practices

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

namespace Solution
{
class Digitizer
{
public static long[] Digitize(long n)
{
return n.ToString()
.Reverse()
.Select(t => Convert.ToInt64(t.ToString()))
.ToArray();
}
}
}
  • linq 사용.
  • 역순으로 만든 후. 각 값을 순회 하면서 long형으로 변환 해준후 배열로 반환해준다.