08 April 2017

Bishop and Pawn

My solution:
bool bishopAndPawn(string bishop, string pawn) 
{
    return Math.Abs(bishop[1] - pawn[1]).Equals(Math.Abs(bishop[0] - pawn[0]));
}

Previous

digitDegree

My solution:
int digitDegree(int n) 
{
    if (n < 10)
        return 0;

    var times = 0;
    var sum = n.ToString().Select(x => int.Parse(x.ToString())).Sum();
    while (sum >= 10 || n >= 10)
    {
        times++;
        n = sum;
        sum = n.ToString().Select(x => int.Parse(x.ToString())).Sum();
    }

    return times;
}

Previous Next

longestDigitsPrefix

My solution:
string longestDigitsPrefix(string inputString) 
{
    return Regex.Match(inputString, "^\\d+").Value;
}

Previous Next

Knapsack Light

My solution:
int knapsackLight(int value1, int weight1, int value2, int weight2, int maxW) 
{
    if (weight1 + weight2 <= maxW)
        return value1 + value2;
    else if (weight1 > maxW && weight2 > maxW)
        return 0;
    else if (weight1 <= maxW && weight2 > maxW)
        return value1;
    else if (weight2 <= maxW && weight1 > maxW)
        return value2;
    else if (value1 >= value2)
        return value1;
    else if (value1 < value2)
        return value2;
    
    return 0;
}

Previous Next

growingPlant

My solution:
int growingPlant(int upSpeed, int downSpeed, int desiredHeight) 
{
    var days = 0;
    
    // Day = true, Night = false.
    var isday = true;
    while (desiredHeight > 0)
        if (isday)
        {
            desiredHeight -= upSpeed;
            days++;
            isday = false;
        }
        else
        {
            desiredHeight += downSpeed;
            isday = true;
        }
    
    return days;
}

Previous Next

arrayMaxConsecutiveSum

My solution:
int arrayMaxConsecutiveSum(int[] inputArray, int k) 
{
    var max = 0;
    var rem = 0;
    for (var i = 0; i <= inputArray.Length - k; i++)
    {
        if (i == 0)
            rem = inputArray.Where((i1, i2) => i2 >= i && i2 < i + k).Sum();
        else
            rem = rem + inputArray[i + k - 1] - inputArray[i - 1];

        max = Math.Max(rem, max);
    }

    return max;
}

Previous Next

differentSymbolsNaive

My solution:
int differentSymbolsNaive(string s) 
{
    return s.Distinct().Count();
}

Previous Next

firstDigit

My solution:
char firstDigit(string inputString) 
{
    return Regex.Match(inputString, "\\d{1}").Value[0];
}

Previous Next

extractEachKth

My solution:
int[] extractEachKth(int[] inputArray, int k) 
{
    return inputArray.Where((i, i1) => i1 % k != k - 1).ToArray();
}

Previous Next