Это мой последний пост в году, и мне приятно оглядываться назад на то, что я узнал за последние 12 месяцев. Я создал пару приложений, выполнил несколько задач по программированию, выучил другой язык и решил сотни задач по доске. Мне еще предстоит многому научиться, и я стараюсь не критиковать себя за то, что не учился так быстро, как я надеялся.

Одна вещь, которую я хотел бы отметить, заключается в том, что, хотя я ранее решал эти проблемы с белой доской на Swift, я узнал C #, и декабрьские задачи были полностью решены на C #. Кроме того, я практиковался в написании модульных тестов для них в Visual Studio, поэтому для каждой из приведенных ниже проблем я написал модульный тест. Ура, проверяю жизнь!

Вещи, которые я узнал / открыл, решая алгоритмы на C #:

  • Написание модульных тестов полезно и приносит удовлетворение (когда они проходят :-).
  • Массивы в Swift кажутся изменяемыми, а в C # списки имеют ту же функциональность (т.е. .Append() против .Add()).
  • Рекурсию можно использовать, если вы рассматриваете «базовый случай», к которому в конечном итоге направляется каждая проблема.
  • Понимание того, как работает стек вызовов, может помочь вам понять, как работает рекурсия - они идут рука об руку.

1 декабря - Чередование сумм (CodeFights)

Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on. You are given an array of positive integers - the weights of the people. Return an array of two integers, where the first element is the total weight of team 1, and the second element is the total weight of team 2 after the division is complete.

2 декабря - похожи ли треугольники (CodeFights)

You have two triangles A1B1C1 and A2B2C2 on a plane. Your task is to determine whether they are rather similar, i.e. if their corresponding angles have the same measurements.       
In order for two triangles to be rather similar, the following equations must be true:        
angle(A1B1, B1C1) = angle(A2B2, B2C2)        
angle(A1C1, C1B1) = angle(A2C2, C2B2)        
angle(B1A1, A1C1) = angle(B2A2, A2C2)        
where angle(AB, CD) refers to an angle between segments AB and CD in the triangle.        
Example        
For coordinates = [0, 0, 0, 1, 1, 0, 0, 0, 0, -3, -3, 0], the output should be        
areTrianglesSimilar(coordinates) = true.

3 декабря - Проверка существования одного и того же элемента (CodeFights)

Given two sorted arrays of integers, check if there is at least one element which occurs in both arrays.        
Example        
For arr1 = [1, 2, 3, 5] and arr2 = [1, 4, 5], the output should be        checkSameElementExistence(arr1, arr2) = true;        
For arr1 = [1, 3, 5] and arr2 = [-2, 0, 2, 4, 6], the output should be        
checkSameElementExistence(arr1, arr2) = false.

4 декабря - Извлечение каждого K-го (CodeFights)

Given array of integers, remove each kth element from it.        Example 2, 5, 8        
For inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and k = 3,         the output should be        
extractEachKth(inputArray, k) = [1, 2, 4, 5, 7, 8, 10].

5 декабря - Заполните комнату коробками (от коллеги)

1. Write a function called FillRoomWithBoxes that takes in an int called roomSize, a List<int> called possibleSizes, and a List<int> called boxes.        
  a. The possibleSizes list should contain all possible box sizes.You can assume this list is sorted in descending order. 
       
2.The function should implement a greedy recursive algorithm to        fill the room as full as it can get with the least number of boxes,         and should store the size of each box used in the boxes list, one entry per box        
  a.For example, if your possible sizes list contained 7, 3, 1, and your roomSize was 25, the boxes list should contain 7, 7, 7, 3, 1 when your function exits

6 декабря - Сравнение фракций (CodeFights)

Compare the two given fractions.
Example
  • Для a = [3, 4] и b = [6, 8] вывод должен быть
    fractionComparison(a, b) = '=';
  • Для a = [3, 2] и b = [2, 5] вывод должен быть
    fractionComparison(a, b) = '>';
  • Для a = [3, 5] и b = [2, 3] вывод должен быть
    fractionComparison(a, b) = '<'.

7 декабря - Получите сумму между числами (от коллеги)

Write a function called GetSumBetweenNumbers that takes in an int min and an int max and returns an int. The function should get the sum of all the numbers between (and including) min and max. The function should solve the problem using iteration. If min > max, the function should return 0. Solve the problem using recursion and test it.

8 декабря - парольные фразы с высокой энтропией (CodeFights)

A new system policy has been put in place that requires all accounts to use a passphrase instead of simply a password. A passphrase consists of a series of words (lowercase letters) separated by spaces.  To ensure security, a valid passphrase must contain no duplicate words.    
For example:    
aa bb cc dd ee is valid.    
aa bb cc dd aa is not valid - the word aa appears more than once.    aa bb cc dd aaa is valid - aa and aaa count as different words.    The system's full passphrase list is available as your puzzle input. How many passphrases are valid?

9 декабря - Сумма номеров домов (CodeFights)

A boy is walking a long way from school to his home.  
To make the walk more fun he decides to add up all the numbers         of the houses that he passes by during his walk. Unfortunately,         not all of the houses have numbers written on them, and on top of         that the boy is regularly taking turns to change streets, so the         numbers don't appear to him in any particular order.        
At some point during the walk the boy encounters a house with number         0 written on it, which surprises him so much that he stops adding         numbers to his total right after seeing that house.        
For the given sequence of houses determine the sum that the boy        will get.It is guaranteed that there will always be at least one         0 house on the path.        
Example        
For inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2], the output should be        houseNumbersSum(inputArray) = 11.        
The answer was obtained as 5 + 1 + 2 + 3 = 11.

10 декабря - Арифметическая прогрессия (CodeFights)

Given a sequence of integers find the length of its largest subsequence that forms an arithmetic progression.
Example
For a = [1, 7, 3, 5, 4, 2], the output should be
longestSequence(a) = 3.
Explanation: [1, 3, 5] is a subsequence that's also an arithmetic progression.

11 декабря - делится на 6 (CodeFights)

A masked number is a string that consists of digits and one asterisk (*) that should be replaced by exactly one digit. Given a masked number find all the possible options to replace the asterisk with a digit to produce an integer divisible by 6.
Example
For inputString = "1*0", the output should be
isDivisibleBy6(inputString) = ["120", "150", "180"].

12 декабря - повторение первого символа (от коллеги)

Write a function called IsFirstCharRepeated that takes in a string and returns a bool.  The function should return true if the first character is repeated anywhere else in the string.

13 декабря - Мне повезет (CodeFights)

Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half.        
Given a ticket number n, determine if it's lucky or not.        Example        
For n = 1230, the output should be        
isLucky(n) = true;        
For n = 239017, the output should be        
isLucky(n) = false.

14 декабря - Счастливое число (CodeFights)

Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7.        Example        
For n = 47, the output should be        
isLuckyNumber(n) = true.

15 декабря - Поздняя поездка (CodeFights)

One night you go for a ride on your motorcycle. At 00:00 you start        your engine, and the built-in timer automatically begins counting        the length of your ride, in minutes. Off you go to explore the         neighborhood.  When you finally decide to head back, you realize there's a chance the bridges on your route home are up, leaving you stranded! Unfortunately, you don't have your watch on you and don't know what time it is. All you know thanks to the bike's timer is that n minutes have passed since 00:00. Using the bike's timer, calculate the current time. Return an answer as the sum of digits that the digital timer in the format hh:mm would show.        Example        
For n = 240, the output should be lateRide(n) = 4. Since 240 minutes have passed, the current time is 04:00. The digits sum up to 0 + 4 + 0 + 0 = 4, which is the answer.        
For n = 808, the output should be lateRide(n) = 14. 808 minutes mean that it's 13:28 now, so the answer should be 1 + 3 + 2 + 8 = 14.

16 декабря - Максимальный делитель (CodeFights)

Given a number and a range, find the largest integer within the given range that's divisible by the given number.        
Example        
For left = 1, right = 10 and divisor = 3, the output should be        maxDivisor(left, right, divisor) = 9.        
The largest integer divisible by 3 in range[1, 10] is 9.

17 декабря - список умножения с помощью «разделяй и властвуй» (от коллеги)

Write a function that takes in a List of ints that multiplies all values in the list.  Use "divide and conquer" with recursion.

18 декабря - Только четные числа (CodeFights)

Return a strictly increasing array of all even numbers between given left and right (both inclusive).
Example
For left = 5 and right = 10, the output should be
onlyEvenNumbers(left, right) = [6, 8, 10].

19 декабря - разница в цифрах (CodeFights)

Given an integer n, find the difference between the sums of its even and odd digits.
Example
For n = 412, the output should be
digitSumsDifference(n) = 5;
For n = 1203, the output should be digitSumsDifference(n) = -2.

20 декабря - Pep Eight (CodeFights)

PEP 8, Style Guide for Python Code, requires a coder to write lines no longer than 79 characters. Given some line's length, find out if it satisfies PEP 8 requirements.
Example
  • Для line = 35 вывод должен быть
    pepEight(line) = true;
  • Для line = 85 вывод должен быть
    pepEight(line) = false.

21 декабря - Максимальная последовательная сумма в массиве (CodeFights)

Given array of integers, find the maximal possible sum of some of its k consecutive elements.
Example
For inputArray = [2, 3, 5, 1, 6] and k = 2, the output should be        arrayMaxConsecutiveSum(inputArray, k) = 8.
All possible sums of 2 consecutive elements are:
2 + 3 = 5;
3 + 5 = 8;
5 + 1 = 6;
1 + 6 = 7.
Thus, the answer is 8.

22 декабря - Ортогональные линии (CodeFights)

Two lines ax + by + c = 0 and a'x + b'y + c' = 0 are orthogonal if and only if a* a' + b * b' = 0. Check if the two given lines are orthogonal.
Example
For line1 = [1, -1, 0] and line2 = [1, 1, 0], the output should be
orthogonalLines(line1, line2) = true.

23 декабря - k-я цифра (CodeFights)

Given an integer, find its kth digit.
Example
For n = 578943 and k = 2, the output should be
kthDigit(n, k) = 7.

24 декабря - Поделись яблоком (CodeFights)

You have a apples, and your friend has b apples.You will be happy if - and only if - you both have the same number of apples.
Given integers a and b, check if you will be happy after you give your friend one of your apples.
Example
For a = 3 and b = 1, the output should be
shareAnApple(a, b) = true.

25 декабря - Извлечение столбца матрицы (CodeFights)

Given a rectangular matrix and an integer column, return an array containing the elements of the columnth column of the given matrix(the leftmost column is the 0th one).
Example
Formatrix = [[1, 1, 1, 2], [0, 5, 0, 4], [2, 1, 3, 6]]
and column = 2, the output should be
extractMatrixColumn(matrix, column) = [1, 0, 3].

26 декабря - Найти сумму (от коллеги)

Given a List of ints, find the sum of all elements by using recursion.

27 декабря - обратные символы в строке (от коллеги)

Given a string, reverse the characters in the string by using recursion.

28 декабря - Прямой треугольник (CodeFights)

For a given triangle determine if it is a right triangle.        Example        
For sides = [3, 5, 4], the output should be        rightTriangle(sides) = true.

29 декабря - Сумма ниже границы (CodeFights)

Given an integer bound, find the maximal integer n such that 1 + 2 + ... + n ≤ bound.        
Example        
For bound = 14, the output should be        
sumBelowBound(bound) = 4.

30 декабря - Три и четыре (CodeFights)

Return a sorted array of all non-negative numbers less than the given n which are divisible both by 3 and 4.

Для n = 30 вывод должен быть

threeAndFour(n) = [0, 12, 24].

31 декабря - X to the Y Power (от коллеги)

Write a function called XToTheYPower that takes in an int x and an int y, and returns an int. The function should return x^y. Solve with recursion.

Я надеюсь, что у вас будут прекрасные зимние каникулы, и надеюсь увидеть вас в новом году. Спасибо за чтение, подписку, подписку и обучение вместе со мной!

🍾 🎉 🎊