15 August 2017

List Beautifier

My solution:
def listBeautifier(a):
    res = a[:]
    while res and res[0] != res[-1]:
       b, *res, c = res
    return res

Previous

Mex Function

My solution:
def mexFunction(s, upperBound):
    found = -1
    for i in range(upperBound):
        if not i in s:
            found = i
            break
    else:
        found = upperBound

    return found

Previous Next

Base Conversion

My solution:
def baseConversion(n, x):
    return hex(sum((int(n[i]) if n[i] <= '9' else ord(n[i]) - ord('a') + 10) * x ** (len(n) - 1 - i) for i in range(len(n))))[2:]

Previous Next

Simple Sort

My solution:
def simpleSort(arr):

    n = len(arr)

    for i in range(n):
        j = 0
        stop = n - i
        while j < stop - 1:
            if arr[j] > arr[j + 1]:
                arr[j + 1], arr[j] = arr[j], arr[j + 1]
            j += 1
    return arr

Previous Next

Modulus

My solution:
def modulus(n):
    if type(n) == int:
        return n % 2
    else:
        return -1

Previous Next

Count Bits

My solution:
def countBits(n):
    return n.bit_length()

Previous Next

Language Differences

My answer: "x = 15, y = -4"

Output:
Python 3:
-4
3
1
0
-4

Java:

-4
3
1
0
-3

Previous Next

Special Conditional

My answer: "a == not b"
Two operators ("=="  and "not") cannot be next to each other.

Previous Next

Efficient Comparison

My answer: "Option 1 is the most optimal one."

My solution:
import time
L = 1
x = 2
y = 3
R = 9
t1 = time.perf_counter()
def a():
 if L < x ** y <= R:
  return True

t2 = time.perf_counter()
print(t2 - t1)
t3 = time.perf_counter()
def b():
 if x ** y > L and x ** y <= R:
  return True

t4 = time.perf_counter()
print(t4 - t3)
t5 = time.perf_counter()
def c():
 if x ** y in range(L + 1, R + 1):
  return True

t6 = time.perf_counter()
print(t6 - t5)

Output:
5.131850057605017e-07
1.5395550172814964e-06
1.5395550172815045e-05

Previous Next

Collections Truthness

My answer: [True, False]
Explanation on 4.1 Truth Value Testing.

Next

isCryptSolution

My solution:
bool isCryptSolution(string[] crypt, char[][] solution) 
{
    var words = new List<decimal>();
    foreach (var word in crypt)
    {
        decimal wordsum = 0;
        for (var ci = 0; ci < word.Length; ci++)
            foreach (char[] t in solution)
            {
                if (word[ci] != t[0]) continue;
                if (word[0] == t[0] && t[1] == '0' && word.Length != 1) return false;
                wordsum += Convert.ToInt32(t[1].ToString()) *
                           Convert.ToDecimal(Math.Pow(10, word.Length - 1 - ci));
                break;
            }

        words.Add(wordsum);
    }

    return words[2] == words[0] + words[1];
}

Previous

sudoku2

My solution:
bool sudoku2(char[][] grid) 
{
    var columnList = new List<Dictionary<char, int>>();
    var rowList = new List<Dictionary<char, int>>();
    var nineList = new List<Dictionary<char, int>>();
    foreach (var t in grid)
    {
        var dict = new Dictionary<char, int>();
        for (var j = 0; j < grid[0].Length; j++)
            if (dict.ContainsKey(t[j]))
                dict[t[j]]++;
            else
                dict[t[j]] = 1;

        rowList.Add(dict);
    }

    if (rowList.Any(d => d.Count(pair => pair.Key != '.' && pair.Value > 1) > 0))
        return false;

    for (var i = 0; i < grid.Length; i++)
    {
        var dict = new Dictionary<char, int>();
        for (var j = 0; j < grid[0].Length; j++)
            if (dict.ContainsKey(grid[j][i]))
                dict[grid[j][i]]++;
            else
                dict[grid[j][i]] = 1;

        columnList.Add(dict);
    }

    if (columnList.Any(d => d.Count(pair => pair.Key != '.' && pair.Value > 1) > 0))
        return false;

    for (var i = 0; i < grid.Length / 3; i++)
    {
        for (var j = 0; j < grid[0].Length / 3; j++)
        {
            var dict = new Dictionary<char, int>();
            if (dict.ContainsKey(grid[i * 3][j * 3]))
                dict[grid[i * 3][j * 3]]++;
            else
                dict[grid[i * 3][j * 3]] = 1;

            if (dict.ContainsKey(grid[i * 3][j * 3 + 1]))
                dict[grid[i * 3][j * 3 + 1]]++;
            else
                dict[grid[i * 3][j * 3 + 1]] = 1;

            if (dict.ContainsKey(grid[i * 3][j * 3 + 2]))
                dict[grid[i * 3][j * 3 + 2]]++;
            else
                dict[grid[i * 3][j * 3 + 2]] = 1;

            if (dict.ContainsKey(grid[i * 3 + 1][j * 3]))
                dict[grid[i * 3 + 1][j * 3]]++;
            else
                dict[grid[i * 3 + 1][j * 3]] = 1;

            if (dict.ContainsKey(grid[i * 3 + 1][j * 3 + 1]))
                dict[grid[i * 3 + 1][j * 3 + 1]]++;
            else
                dict[grid[i * 3 + 1][j * 3 + 1]] = 1;

            if (dict.ContainsKey(grid[i * 3 + 1][j * 3 + 2]))
                dict[grid[i * 3 + 1][j * 3 + 2]]++;
            else
                dict[grid[i * 3 + 1][j * 3 + 2]] = 1;

            if (dict.ContainsKey(grid[i * 3 + 2][j * 3]))
                dict[grid[i * 3 + 2][j * 3]]++;
            else
                dict[grid[i * 3 + 2][j * 3]] = 1;

            if (dict.ContainsKey(grid[i * 3 + 2][j * 3 + 1]))
                dict[grid[i * 3 + 2][j * 3 + 1]]++;
            else
                dict[grid[i * 3 + 2][j * 3 + 1]] = 1;

            if (dict.ContainsKey(grid[i * 3 + 2][j * 3 + 2]))
                dict[grid[i * 3 + 2][j * 3 + 2]]++;
            else
                dict[grid[i * 3 + 2][j * 3 + 2]] = 1;

            nineList.Add(dict);
        }
    }

    return !nineList.Any(d => d.Count(pair => pair.Key != '.' && pair.Value > 1) > 0);
}

Previous Next

firstNotRepeatingCharacter

My solution:
char firstNotRepeatingCharacter(string s) 
{
    var d = new Dictionary<char, int>();
    foreach (var c in s)
        if (!d.ContainsKey(c))
            d[c] = 1;
        else
            d[c]++;

    return d.Any(pair => pair.Value == 1) ? d.Where(pair => pair.Value == 1).Select(pair => pair.Key).First() : '_';
}

Previous Next

firstDuplicate

My solution:
int firstDuplicate(int[] a) 
{
    var list = new SortedSet<int>();
    foreach (int d in a)
    {
        if (list.Contains(d))
            return d;
        
        list.Add(d);
    }
    
    return -1;
}

Next

rotateImage

My solution:
int[][] rotateImage(int[][] a) 
{
    var list = new List<List<int>>();
    foreach (var t in a)
    {
        var column = new List<int>();
        for (var j = 0; j < a[0].Length; j++)
            column.Add(t[j]);

        list.Add(column);
    }

    var solution = new int[a.Length][];
    for (var i = 0; i < a.Length; i++)
        solution[i] = new int[a.Length];

    for (var i = 0; i < a.Length; i++)
        for (var j = 0; j < a[0].Length; j++)
            solution[i][j] = list[a.Length - 1 - j][i];

    return solution;
}

Previous Next

12 May 2017

Make Array Consecutive 2

My solution:
int makeArrayConsecutive2(int[] statues) 
{
    return statues.Max() - statues.Min() + 1 - statues.Length;
}

Previous

Replace Middle

My solution:
int[] replaceMiddle(int[] arr) 
{
    return arr.Length % 2 == 1
                ? arr
                : arr.Select((i, i1) => i1 != arr.Length / 2 - 1 ? i : arr[arr.Length / 2 - 1] + arr[arr.Length / 2])
                    .Where((i, i1) => i1 != arr.Length / 2)
                    .ToArray();
}

Previous Next

Is Smooth?

My solution:
bool isSmooth(int[] arr) 
{
    return arr.Length % 2 == 0
                ? arr.First().Equals(arr.Last()) && arr.First().Equals(arr[arr.Length / 2 - 1] + arr[arr.Length / 2])
                : arr.First().Equals(arr.Last()) && arr.First().Equals(arr[arr.Length / 2]);
}

Previous Next

Remove Array Part

My solution:
int[] removeArrayPart(int[] inputArray, int l, int r) 
{
    return inputArray.Select(i => i).Where((i, i1) => i1 < l || i1 > r).ToArray();
}

Previous Next

Concatenate Arrays

My solution:
int[] concatenateArrays(int[] a, int[] b) 
{
    return a.Concat(b).ToArray();
}

Previous Next

First Reverse Try

My solution:
int[] firstReverseTry(int[] arr) 
{
    return arr.Select((i, i1) => i1 == 0 || i1 == arr.Length - 1 ? i1 == 0 ? arr.Last() : arr.First() : i).ToArray();
}

Previous Next

Array Replace

My solution:
int[] arrayReplace(int[] inputArray, int elemToReplace, int substitutionElem) 
{
    return inputArray.Select(i => i == elemToReplace ? substitutionElem : i).ToArray();
}

Previous Next

Create Array

My solution:
int[] createArray(int size) 
{
    return Enumerable.Repeat(1, size).ToArray();
}

Previous Next

Candles

My solution:
int candles(int candlesNumber, int makeNew) 
{
    var sum = candlesNumber;
    while (candlesNumber >= makeNew)
    {
        sum += candlesNumber / makeNew;
        candlesNumber = candlesNumber / makeNew + (candlesNumber - candlesNumber / makeNew * makeNew);
    }

    return sum;
}

Previous Next

Rounders

My solution:
int rounders(int value) 
{
    if (value < 10)
        return value;

    var ic = value.ToString().Reverse().ToList();
    var s = "0";
    for (var i = 1; i < ic.Count; i++)
    {
        if (ic[i - 1] > '4')
        {
            if (ic[i] == '9')
                ic.Add('1');

            ic[i] = ic[i] != '9' ? (char) (ic[i] + 1) : '0';
        }

        if (i != ic.Count - 1)
            s += "0";
        else if (ic[i] != '9')
            s += ic[i];
        else
            s += "01";
    }

    return int.Parse(new string(s.Reverse().ToArray()));
}

Previous Next

Increase Number Roundness

My solution:
bool increaseNumberRoundness(int n) 
{
    return n.ToString().TrimEnd('0').Contains('0');
}

Previous Next

Apple Boxes

My solution:
int appleBoxes(int k) 
{
    return Enumerable.Range(1, k).Select(i => Convert.ToInt32(Math.Pow(-1, i) * Math.Pow(i, 2))).Sum();
}

Previous Next

Addition Without Carrying

My solution:
int additionWithoutCarrying(int param1, int param2) 
{
    return (param1 / 10000 + param2 / 10000) % 10 * 10000 + (param1 / 1000 + param2 / 1000) % 10 * 1000 + (param1 / 100 + param2 / 100) % 10 * 100 + (param1 / 10 + param2 / 10) % 10 * 10 + (param1 + param2) % 10;
}

Previous Next

Lineup

My solution:
int lineUp(string commands) 
{
    var b = true;
    var count = 0;
    foreach (var c in commands)
        if ((c == 'L' || c == 'R') && b)
            b = false;
        else if ((c == 'L' || c == 'R') && !b)
        {
            b = true;
            count++;
        }
        else if (c == 'A')
            if (b)
                count++;

    return count;
}

Previous Next

Magical Well

My solution:
int magicalWell(int a, int b, int n) 
{
    var sum = 0;
    while (n != 0)
    {
        sum += a * b;
        a++;
        b++;
        n--;
    }

    return sum;
}

Previous Next

Count Sum Of Two Representations 2

My solution:
int countSumOfTwoRepresentations2(int n, int l, int r) 
{
    var count = 0;
    for (var a = l; a <= r; a++)
        if (a <= n - a && n - a >= l && n - a <= r)
            count++;

    return count;
}

Previous Next

Least Factorial

My solution:
int leastFactorial(int n) 
{
    var i = 1;
    while (Factorial(i) < n)
        i++;

    return Factorial(i);
}

int Factorial(int p0)
{
    if (p0 > 1)
        return Factorial(p0 - 1) * p0;

    return 1;
}

Previous Next

27 April 2017

Metro Card

My solution:
int[] metroCard(int lastNumberOfDays) 
{
    return lastNumberOfDays == 28 || lastNumberOfDays == 30 ? new [] { 31 } : new [] { 28, 30, 31 };
}

Previous Next

Will You?

My solution:
bool willYou(bool young, bool beautiful, bool loved) 
{
    return (young && beautiful && !loved) || ((!young || !beautiful) && loved);
}

Previous Next

Tennis Set

My solution:
bool tennisSet(int score1, int score2) 
{
    return (Math.Min(score1, score2) < 5 && Math.Max(score1, score2) == 6) || ((Math.Min(score1, score2) == 5 || Math.Min(score1, score2) == 6) && Math.Max(score1, score2) == 7);
}

Previous Next

Arithmetic Expression

My solution:
bool arithmeticExpression(int A, int B, int C) 
{
    return A + B == C || A - B == C || A * B == C || A / B == C && A % B == 0;
}

Previous Next

Is Infinite Process?

My solution:
bool isInfiniteProcess(int a, int b) 
{
    return a > b || Math.Abs(a - b) % 2 == 1;
}

Previous Next

Extra Number

My solution:
int extraNumber(int a, int b, int c) 
{
    return (a == b) ? c : (a == c) ? b : a;
}

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)
        return value2;
    else if (weight2 > maxW)
        return value1;
    else
        return value1 > value2 ? value1 : value2;
}

Previous Next

Reach Next Level

My solution:
bool reachNextLevel(int experience, int threshold, int reward) 
{
    return experience + reward >= threshold;
}

Previous Next

Phone Call

My solution:
int phoneCall(int min1, int min2_10, int min11, int s) 
{
    var min = 0;
    while (s > 0)
    {
        if (min == 0)
        {
            if (s >= min1)
            {
                s -= min1;
                min = 1;
            }
            else
                s = 0;
        }
        else if (min == 1)
        {
            if (s >= min2_10 * 9)
            {
                min = 10;
                s -= min2_10 * 9;
            }
            else if (s < min2_10)
            {
                min = 2;
                s = 0;
            }
            else
            {
                min += s / min2_10;
                s = 0;
            }
            
        }
        else if (min == 10)
        {
            if (s < min11)
                min++;
            else
                min += s / min11;
            
            s = 0;
            
        }
    }
    
    return min;
}

Previous Next

Late Ride

My solution:
int lateRide(int n) 
{
    return (n / 60) / 10 + (n / 60) % 10 + (n % 60) / 10 + (n % 60) % 10;
}

Previous Next

Circle Of Numbers

My solution:
int circleOfNumbers(int n, int firstNumber) 
{
    return (firstNumber + n / 2) % n;
}

Previous Next

Max Multiple

My solution:
int maxMultiple(int divisor, int bound) 
{
    return (bound / divisor) * divisor;
}

Previous Next

Seats In Theater

My solution:
int seatsInTheater(int nCols, int nRows, int col, int row) 
{
    return (nCols - col + 1) * (nRows - row);
}

Previous Next

Candies

My solution:
int candies(int n, int m) 
{
    return m / n * n;
}

Largest Number

My solution:
int largestNumber(int n) 
{
    return int.Parse(new string('9', n));
}

Previous Next

26 April 2017

Add Two Digits

My solution:
int addTwoDigits(int n) 
{
    return n % 10 + n / 10;
}

Previous Next

Sudoku

My solution:
bool sudoku(int[][] grid) 
{
    var horizontalLists = new List<List<int>>();
    var verticalLists = new List<List<int>>();
    var clustersLists = new List<List<int>>();
    for (var y = 0; y < 9; y++)
        verticalLists.Add(grid[y].ToList());

    for (var x = 0; x < 9; x++)
    {
        var horizontalList = new List<int>();
        for (var y = 0; y < 9; y++)
            horizontalList.Add(grid[y][x]);

        horizontalLists.Add(horizontalList);
    }

    for (var x = 0; x < 9; x += 3)
        for (var y = 0; y < 9; y += 3)
        {
            var clustersList = new List<int>();
            clustersList.Add(grid[y][x]);
            clustersList.Add(grid[y + 1][x]);
            clustersList.Add(grid[y + 2][x]);
            clustersList.Add(grid[y][x + 1]);
            clustersList.Add(grid[y + 1][x + 1]);
            clustersList.Add(grid[y + 2][x + 1]);
            clustersList.Add(grid[y][x + 2]);
            clustersList.Add(grid[y + 1][x + 2]);
            clustersList.Add(grid[y + 2][x + 2]);
            clustersLists.Add(clustersList);
        }

    return !horizontalLists.Any(
               horizontalList => horizontalList.Any(i => horizontalList.Count(i1 => i1 == i) != 1)) && !verticalLists.Any(
               verticalList => verticalList.Any(i => verticalList.Count(i1 => i1 == i) != 1)) && !clustersLists.Any(
               clustersList => clustersList.Any(i => clustersList.Count(i1 => i1 == i) != 1));
}

Previous Next

spiralNumbers

My solution:
int[][] spiralNumbers(int n) 
{
    var answer = new int[n][];
    for (var i = 0; i < n; i++)
        answer[i] = new int[n];

    var j = 1;
    var start = 0;
    var row = start;
    var col = start;
    var end = n - 1;
    while (j <= n * n)
    {
        // Horizontal to the right
        while (true)
        {
            if (answer[row][col] == 0)
            {
                answer[row][col] = j;
                j++;
            }

            if (col == end)
                break;

            col++;
        }

        // Vertically down
        while (true)
        {
            if (answer[row][col] == 0)
            {
                answer[row][col] = j;
                j++;
            }

            if (row == end)
                break;

            row++;
        }

        // Horizontal to the left
        while (true)
        {
            if (answer[row][col] == 0)
            {
                answer[row][col] = j;
                j++;
            }

            if (col == start)
                break;

            col--;
        }

        // Vertically up
        while (true)
        {
            if (answer[row][col] == 0)
            {
                answer[row][col] = j;
                j++;
            }

            if (row == start)
                break;

            row--;
        }

        row++;
        start++;
        end--;
    }

    return answer;
}

Previous Next

messageFromBinaryCode

My solution:
string messageFromBinaryCode(string code) 
{
    var answer = string.Empty;
    for (var i = 0; i < code.Length / 8; i++)
        answer += (char) (128 * int.Parse(code[i * 8].ToString()) + 64 * int.Parse(code[i * 8 + 1].ToString()) + 32 * int.Parse(code[i * 8 + 2].ToString()) + 16 * int.Parse(code[i * 8 + 3].ToString()) + 8 * int.Parse(code[i * 8 + 4].ToString()) + 4 * int.Parse(code[i * 8 + 5].ToString()) + 2 * int.Parse(code[i * 8 + 6].ToString()) + int.Parse(code[i * 8 + 7].ToString()));

    return answer;
}

Previous Next

File Naming

My solution:
string[] fileNaming(string[] names)
{
    var list = new List<string>();
    foreach (var name in names)
        if (!list.Contains(name))
            list.Add(name);
        else
            for (var i = 1; i < 16; i++)
            {
                if (list.Contains(name + "(" + i + ")")) continue;
                list.Add(name + "(" + i + ")");
                break;
            }

    return list.ToArray();
}

Previous Next

digitsProduct

My solution:
int digitsProduct(int product) 
{
    switch (product)
    {
        case 0:
            return 10;
        case 1:
            return 1;
        default:
            var i = 9;
            var answer = string.Empty;
            var copyOfProduct = product;
            while (product != 1 && i != 1)
            {
                if (product % i == 0)
                {
                    product /= i;
                    answer += i.ToString();
                }
                else
                    i--;
            }

            if (i == 1 && copyOfProduct == product)
                return -1;

            return i == 1 && copyOfProduct == product ? -1 : int.Parse(new string(answer.Reverse().ToArray()));
    }
}

Previous Next

Different Squares

My solution:
int differentSquares(int[][] matrix) 
{
    var two_x_two_s = new HashSet<Tuple<int, int, int, int>>();
    for (var row = 0; row < matrix.Length - 1; row++)
        for (var column = 0; column < matrix[0].Length - 1; column++)
            two_x_two_s.Add(new Tuple<int, int, int, int>(matrix[row][column], matrix[row][column + 1],
                matrix[row + 1][column], matrix[row + 1][column + 1]));

    return two_x_two_s.Count;
}

Previous Next

sumUpNumbers

My solution:
int sumUpNumbers(string inputString) 
{
    return Regex.Matches(inputString, "\\d+").Cast<Match>().Sum(match => int.Parse(match.Value));
}

Previous Next

Valid Time

My solution:
bool validTime(string time) 
{
    return Regex.IsMatch(time, "^([01]\\d|2[0-3]):([0-5]\\d)$");
}

Previous Next

longestWord

My solution:
string longestWord(string text) 
{
    var list = (from Match match in Regex.Matches(text, "[A-Za-z]+") select match.Value).ToList();
    return list.First(s => s.Length == list.Select(s1 => s1.Length).Max());
}

Previous Next

25 April 2017

Hanzi Week 3

Characters and Words:

Week 3
Lesson 9:
1. xué  2. shēng (shēng hái zi, xué sheng, nǚ shēng)  3.  (xué xí)  4. lǎo (lǎo rén)  5. shī (lǎo shī)  6. wén (wén xué, wén zǐ, zuò wén)

Lesson 10:
1.  (dà rén, dà xué, dà xué shēng)  2. xiǎo (xiǎo háir, xiǎo xué, xiǎo xué shēng, dà xiǎo)  3. duō  4. shǎo (duō shao)  5. hǎo (hǎo duō, hǎo rén)  6. huài (huài rén., huài hǎo)

Lesson 11:
1. lái  2.   3. jìn (jìn lai, jìn qu)  4. chū (chū lai, chū qu, chū shēng)  5. kāi (kāi xué)  6. guān (kāi guān)

Lesson 12:
1. cháng  2. duǎn (cháng duǎn)  3. gāo (gāo gè zi)  4. xìng (gāo xìng)  5. xīn (xīn shēng)  6. jiù (xīn jiù)

Previous
from Coursera Chinese Characters for beginner 汉字 by Peking University
Link: https://www.coursera.org/learn/hanzi/home

22 April 2017

Hanzi Week 2

Characters and Words:

Week 2
Lesson 5:
1.   2.   3. men (rén men, nǐ men, tā men)  4. zuò (gōng zuò)  5. shén  6. me (shén me)

Lesson 6:
1.  (nǚ rén) 2.  (tā men)  3.  (mā ma)  4. jiě (jiě jie)  5. mèi (mèi mei, jiě mèi)  6. nǎi (nǎi nai)

Lesson 7:
1.   2. qīn (fù qin)  3.  (bà ba)  4.  (yé ye)  5.  (mǔ qin, fù mǔ)  6.  (wǒ men)

Lesson 8:
1. ér (nǚ ér)  2.  (ér zi, gè zi, zǐ nǚ)  3. sūn (sūn zi, sūn nü)  4. hái (hái zi, nü háir)  5. míng  6.  ( míng zi)

Previous Next
from Coursera Chinese Characters for beginner 汉字 by Peking University
Link: https://www.coursera.org/learn/hanzi/home

21 April 2017

Hanzi Week 1

Characters and Words:

Week 1
Lesson 1:
1.   2. èr  3. sān  4. liù  5.   6. shí (shí yī, shí èr, shí sān, shí liù, shí bā, èr shí, sān shí, liù shí, bā shí)

Lesson 2:
1.  (shí sì, sì shí)  2.  (shí wǔ, wǔ shí)  3.  (shí qī, qī shí)  4. jiǔ (shí jiǔ, jiǔ shí) 5.   6. liǎng (liǎng gè)

Lesson 3:
1.  (jǐ gè)  2. bàn (bàn gè, yí bàn)  3. bǎi (yì bǎi, sān bǎi)  4. qiān (yì qiān, wǔ qiān)  5. wàn (yí wàn)  6. rén

Lesson 4:
1. gōng (gōng rén) 2. gān  3. tiān (yì tiān, liǎng tiān, bàn tiān)  4. jīn (jīn tiān) 5,   6. zhàng (zhàng fu)

Next
from Coursera Chinese Characters for beginner 汉字 by Peking University
Link: https://www.coursera.org/learn/hanzi/home

12 April 2017

deleteDigit

My solution:
int deleteDigit(int n) 
{
    return int.Parse(n.ToString().Select((c, i) => n.ToString().Remove(i, 1)).Max());;
}

Previous Next

chessKnight

My solution:
int chessKnight(string cell) 
{
    var possible_moves = new List<string>();

    // Upward
    if (int.Parse(cell[1].ToString()) + 2 <= 8)
    {
        if (cell[0] >= 'b')
            possible_moves.Add((char)(cell[0] - 1) + ((char) (cell[1] + 2)).ToString());

        if (cell[0] <= 'g')
            possible_moves.Add((char)(cell[0] + 1) + ((char)(cell[1] + 2)).ToString());
    }

    // Rightward
    if (cell[0] <= 'f')
    {
        if (int.Parse(cell[1].ToString()) <= 7)
            possible_moves.Add((char)(cell[0] + 2) + ((char)(cell[1] + 1)).ToString());

        if (int.Parse(cell[1].ToString()) >= 2)
            possible_moves.Add((char)(cell[0] + 2) + ((char)(cell[1] - 1)).ToString());
    }

    // Downward
    if (int.Parse(cell[1].ToString()) - 2 >= 1)
    {
        if (cell[0] >= 'b')
            possible_moves.Add((char)(cell[0] - 1) + ((char)(cell[1] - 2)).ToString());

        if (cell[0] <= 'g')
            possible_moves.Add((char)(cell[0] + 1) + ((char)(cell[1] - 2)).ToString());
    }

    // Leftward
    if (cell[0] >= 'c')
    {
        if (int.Parse(cell[1].ToString()) <= 7)
            possible_moves.Add((char)(cell[0] - 2) + ((char)(cell[1] + 1)).ToString());

        if (int.Parse(cell[1].ToString()) >= 2)
            possible_moves.Add((char)(cell[0] - 2) + ((char)(cell[1] - 1)).ToString());
    }

    return possible_moves.Count;
}

Previous Next

lineEncoding

My solution:
string lineEncoding(string s) 
{
    var c = new char();
    var answer = string.Empty;
    var counter = 0;
    for (var i = 0; i < s.Length; i++)
    {
        if (c == '\0')
        {
            c = s[i];
            counter++;
        }
        else if (c == s[i])
        {
            counter++;
            if (i == s.Length - 1)
                answer += counter.ToString() + c;
        }
        else
        {
            if (counter > 1)
                answer += counter.ToString() + c;
            else
                answer += c;

            c = s[i];
            counter = 1;
            if (i == s.Length - 1)
                answer += c;
        }
    }

    return answer;
}

Previous Next

isDigit

My solution:
bool isDigit(char symbol) 
{
    return char.IsDigit(symbol);
}

Previous Next

11 April 2017

Is MAC48 Address?

My solution:
bool isMAC48Address(string inputString) 
{
    return Regex.IsMatch(inputString, "^([0-9A-F]{2}-){5}[0-9A-F]{2}$");
}

Previous Next

Elections Winners

My solution:
int electionsWinners(int[] votes, int k) 
{
    var max = votes.Max();
    return k == 0 && votes.Where(d => d == votes.Max()).Count() == 1 ? 1 : votes.Count(t => t + k > max);
}

Previous Next

buildPalindrome

My solution:
string buildPalindrome(string st) 
{
    var i = 0;
    while (!st.Substring(i).ToArray().SequenceEqual(st.Substring(i).Reverse().ToArray()) && i < st.Length)
        i++;

    return st + new string(st.Substring(0, i).Reverse().ToArray());
}

Previous Next

Find Email Domain

My solution:
string findEmailDomain(string address) 
{
    return Regex.Match(address, "@[A-z0-9\\.-]+$").Value.Substring(1);
}

Previous Next

isBeautifulString

My solution:
bool isBeautifulString(string inputString) 
{
    var sorted = Enumerable.Range('a', inputString.Max(c => c) - 'a' + 1).Select(i => (char)i).ToArray();
    for (var i = 1; i < sorted.Length; i++)
        if (inputString.Count(c => c == sorted[i]) > inputString.Count(c => c == sorted[i - 1]))
            return false;

    return true;
}
Terms of use: http://stackoverflow.com/a/314508 by http://stackoverflow.com/users/4685/pop-catalin, modified under https://creativecommons.org/licenses/by-sa/3.0/.

Previous Next

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

01 April 2017

stringsRearrangement

My solution:
bool stringsRearrangement(string[] inputArray) 
{
    IEnumerable<IEnumerable<int>> permutations =
    GetPermutations(Enumerable.Range(1, inputArray.Length), inputArray.Length);
    Dictionary<int, bool> dictionary = new Dictionary<int, bool>();
    int key = 0;
    foreach (IEnumerable<int> intArray in permutations)
    {
        key++;
        List<int> intList = intArray.ToList();
        for (int i = 0; i < intList.Count - 1; i++)
        {
            int diffcount = 0;
            for (int j = 0; j < inputArray[intList[i] - 1].Length; j++)
                if (inputArray[intList[i] - 1][j] != inputArray[intList[i + 1] - 1][j])
                    diffcount++;

            if (diffcount != 1)
            {
                dictionary.Add(key, false);
                break;
            }
        }

        if (!dictionary.ContainsKey(key))
            dictionary.Add(key, true);
    }

    return dictionary.Any(x => x.Value);
}

IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> list, int length)
{
    if (length == 1) return list.Select(t => (IEnumerable<T>)new T[] { t });

    return GetPermutations(list, length - 1)
        .SelectMany(t => list.Where(e => !t.Contains(e)),
            (t1, t2) => t1.Concat(new T[] { t2 }));
}
Terms of use: Method by pengyang, used under CC BY-SA 3.0

Previous Next