Code Katas
Una Code Kata es un pequeño ejercicio que permite mejorar las habilidades de programación poniendo a prueba nuestra capacidad para resolver problemas, creatividad y disciplina, y dónde lo importante no es encontrar la solución sino el proceso que realizamos hasta alcanzarla. Una Code Kata es un lugar donde podemos jugar con el código sin que haya consecuencias graves.
Realiza múltiples implementaciones para cada kata, de esta forma podrás aprender de los errores que hiciste en un intento anterior. También puedes utilizar tu experiencia para crear una solución mejor. A través de este entrenamiento repetitivo perfeccionarás tus habilidades. Así que nada se termina una vez resuelta la kata, ¡eso es sólo el principio!
En esta página encontrarás mis propuestas (que iré completando poco a poco) en C#, F# y IronPython. Puedes bajar el código completo desde el respositorio de GitHub: https://github.com/acasquete/code-katas
/// <summary> /// Implement the reply() method so it returns the message "hello world" /// </summary> /// <returns>the greeting to the world</returns> String reply();
Einstein will choose a random number to start with – for example: 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz…
String answer (int number);
using System;
public class MyKata
{
/// <summary>
/// Welcome a guest
///
/// -Jane Austen is a women, so say Hello Ms. Austen
/// -George Orwell is a man, so say Hello Mr. Orwell
/// -Isaac Newton was knighted, so say Hello Sir Newton
/// </summary>
/// <param name="lastname">the last name of the guest</param>
/// <param name="isWoman">true if the guest is female</param>
/// <param name="isSir">true if the guest was knighted by the queen</param>
/// <returns>issues welcome text to the guest</returns>
public string welcome(string lastname, bool isWoman, bool isSir)
{
var title = "Mr.";
if (isWoman)
title = "Ms.";
else if (isSir)
title = "Sir";
return String.Format("Hello {0} {1}", title, lastname);
}
}
public class NASACountDown
{
public int[] countdown(int start)
{
var count = new int[start + 1];
for (var i = 0; i <= start; i++)
{
count[i] = start - i;
}
return count;
}
}
public class MyKata
{
/// <summary>
/// Calcular el 'máximo común divisor'
/// http://es.wikipedia.org/wiki/Algoritmo_de_Euclides
/// </summary>
/// <param name="number1">el primer número ('numerador')</param>
/// <param name="number2">el segundo número ('denominador')</param>
/// <returns>mcd de number1 y number2</returns>
public int calcGCD(int number1, int number2)
{
return number2 == 0 ? number1 : calcGCD(number2, number1 % number2);
}
}
using System;
using System.Text.RegularExpressions;
public class MyKata
{
/// <summary>
/// Traduce un texto coloquial a un texto compatible con las noticias de TV
/// </summary>
/// <param name="text">cadena completa de slang (p.e. 'I am $kewl$.')</param>
/// <param name="dictionary">diccionario de slang - en parejas, como {{slang, non-slang}, ...}</param>
/// <returns>el texto 'limpio'</returns>
public string translate(string text, string[][] dictionary)
{
const string pat = @"[$][\w|\s]+[$]";
var occurrences = new Regex(pat).Matches(text);
foreach (var match in occurrences)
{
var word = match.ToString().Replace("$", string.Empty);
var index = Array.FindIndex(dictionary, e => e[0].Equals(word));
text = text.Replace(match.ToString(), dictionary[index][1]);
}
return text;
}
}
using System.Collections.Generic;
public class MyKata
{
/// <summary>
/// Convert an Arabic numeral to Roman numeral
/// </summary>
/// <param name="number">an Arabic numeral</param>
/// <returns>the Roman numeral equivalent to the Arabic numeral</returns>
public string convert(int number)
{
var result = string.Empty;
var numeral = new SortedList<int, string>()
{
{ 50, "L" },
{ 40, "XL" },
{ 10, "X" },
{ 9, "IX" },
{ 5, "V" },
{ 4, "IV" },
{ 1, "I" }
};
var i = numeral.Count - 1;
while (number > 0)
{
var arabic = numeral.Keys[i];
while (arabic <= number)
{
result += numeral.Values[i];
number -= arabic;
}
i--;
}
return result;
}
}
using System.Linq;
public class MyKata
{
public bool containsPrimeNumber(string code1, string code2, string code3)
{
return isSumPrime(code1) || isSumPrime(code2) || isSumPrime(code3);
}
private static bool isSumPrime(string code)
{
var n = code.ToCharArray().Sum(c => int.Parse(c.ToString()));
int i;
for (i = 2; i < n; i++)
if (n % i == 0)
return false;
return i == n;
}
}
using System.Collections.Generic;
using System.Linq;
public class MyKata
{
public enum Day { SUN, MON, TUE, WED, THU, FRI, SAT }
private class Ticket
{
public int Age { get; set; }
public bool IsStudent { get; set; }
}
private int _runtime;
private Day _day;
private bool _isParquet;
private bool _is3D;
private List<Ticket> _tickets;
/// <summary>
/// (1) New customers arrive at your ticket booth and tell you
/// what movie they'd like to see (so keep it in mind
/// </summary>
/// <param name="runtime">movie's runtime in minutes</param>
/// <param name="day">day of the week (enum)</param>
/// <param name="isParquet">true if seating category is 'parquet' (and not 'loge')</param>
/// <param name="is3D">true if the movie's shown in 3D</param>
public void startPurchase(int runtime, Day day, bool isParquet, bool is3D)
{
_tickets = new List<Ticket>();
_runtime = runtime;
_day = day;
_isParquet = isParquet;
_is3D = is3D;
}
/// <summary>
/// (2) Add a ticket to the customers' bill
/// </summary>
/// <param name="age">the age of the ticket buyer in years</param>
/// <param name="isStudent">true if the ticket buyer is a student</param>
public void addTicket(int age, bool isStudent)
{
_tickets.Add(new Ticket { Age = age, IsStudent = isStudent});
}
/// <summary>
/// (3) Calculate the total admission for the current customer(s)
/// </summary>
/// <returns>total in dollars</returns>
public float finishPurchase()
{
var numTickets = _tickets.Count;
var basic = _tickets.Sum(t => t.Age < 13 ? 5.5f : (t.Age >= 65 || numTickets >= 20) ? 6f : (t.IsStudent ? 8f : 11f));
var exceptions = 0f;
if (_is3D) exceptions += 3f;
if (_runtime>120) exceptions += 1.5f;
if (_day == Day.THU && _tickets.Count<20) exceptions -= 2.0f;
if (_day == Day.SAT || _day == Day.SUN) exceptions += 1.5f;
if (!_isParquet) exceptions += 1.5f;
exceptions *= numTickets;
return basic + exceptions;
}
}
using System;
using System.Linq;
public class Books
{
/// <summary>
/// Calculate the ISBN-13 check digit
/// </summary>
/// <param name="isbn">an incomplete ISBN code (12 characters, no hyphens)</param>
/// <returns>code's check digit</returns>
public int calcCheckDigit(String isbn)
{
var i = 0;
return (10 - isbn.Sum(c => int.Parse(c.ToString()) * (i++ % 2 == 0 ? 3 : 1)) % 10) % 10;
}
}
using System.Collections.Generic;
public class trainchaos
{
Stack<int> stack = new Stack<int>();
/// <summary>
/// Adds a car to the siding
/// </summary>
/// <param name="car"> a train car (represented by a number)</param>
public void push(int car)
{
stack.Push(car);
}
/// <summary>
/// Removes a car from the siding
/// </summary>
/// <returns>a train car (number), -1 if stack is empty</returns>
public int pop()
{
return stack.Count > 0 ? stack.Pop() : -1;
}
/// <summary>
/// Return the current front car (number) without removing it
/// </summary>
/// <returns> a train car (number), -1 if stack is empty</returns>
public int peek()
{
return stack.Count > 0 ? stack.Peek() : -1;
}
}
using System;
public class HappyNumbers
{
/// <summary>
/// Comprueba si un número es un 'número feliz'
/// </summary>
/// <param name="number">número a comprobar</param>
/// <returns>true si el parámetro es un número feliz</returns>
private bool isHappy(long p)
{
if (p < 10)
{
return p == 1 || p == 7;
}
long sum = 0;
var number = p.ToString();
foreach (var digit in number)
{
var c = digit - '0';
sum = sum + c*c;
}
return isHappy(sum);
}
}
fizz buzz
the tea party
nasa countdown
fibonacci killer
backwards talk
cough syrup gcd
teleprompter
caesar plays lottery
the cube
movie tickets
books for mars
train chaos
happy numbers
teleprompter v2
cd sorting
url rewrite
roman roulette
towers of hanoi
friday the 13th
movie titles
evolution