Skip to content

Instantly share code, notes, and snippets.

View LostInKadath's full-sized avatar

LostInKadath LostInKadath

View GitHub Profile
from functools import reduce
def naive(ar, length):
# Наивное решение полным перебором. Сложность - O(n**2).
# Проверяем все возможные подмассивы в массиве.
# Уверен, что не пройдет по быстродействию.
if 0 == length:
return 0
if 1 == length:
return 1 if ar[0] else 0
@LostInKadath
LostInKadath / Task207.cpp
Created February 9, 2020 10:47
Task 207. Lineland
#include <iostream>
#include <thread>
#include <vector>
std::ostream& operator<<(std::ostream& os, const std::vector<int>& v)
{
os << "[";
for (const auto& i : v)
os << i << ' ';
return os << "]";
#include <iostream>
#include <string>
std::string Initialize(unsigned short number)
{
std::string sequence;
sequence.reserve(2 * number);
for (auto i = 0; i < number; ++i)
sequence += '(';
for (auto i = 0; i < number; ++i)
@LostInKadath
LostInKadath / task73.py
Created May 12, 2019 12:59
Реализовать операции вычитания, умножения и деления через операцию сложения
def reverse(a):
'''Complexity - O(a).'''
if a == 0:
return 0
result = 0
change = -1 if a > 0 else +1
while a != 0:
result += change
@LostInKadath
LostInKadath / task169.cpp
Last active May 11, 2019 11:57
Найти минимальный общий элемент трех массивов
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int Task169(const std::vector<int>& first,
const std::vector<int>& second,
const std::vector<int>& third)
{
// Защита от дурака
@LostInKadath
LostInKadath / task70.cpp
Last active May 5, 2019 10:55
Найти элемент в отсортированной матрице
#include <algorithm>
#include <cassert>
#include <iostream>
#include <memory>
template <typename T>
class Matrix
{
public:
Matrix(size_t rows, size_t cols, T value)
@LostInKadath
LostInKadath / task69.cpp
Last active April 20, 2019 08:43
Найти цикл в односвязном списке
#include <iostream>
template <typename T>
struct Node
{
Node() = default;
Node(const T& data) : m_data(data) {}
T data() { return m_data; }
Node* next() { return m_next.get(); }
@LostInKadath
LostInKadath / task156.cpp
Last active February 15, 2019 14:56
Отсортировать числа по возрастанию суммы составляющих цифр
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using std::cout;
using std::vector;
template <typename ContainerT, bool stable = false>
class digsum_sort
@LostInKadath
LostInKadath / task152.py
Created January 17, 2019 17:22
Заменить символ в каждом слове, ограниченном разделителями
'''https://t.me/unilecs
Задача 152.
Дана строка слов `string` и массив возможных разделителей `delimiters`.
Словом считается последовательность символов между разделителями.
Заменить в каждом слове символ с порядковым номером `index` на заданный символ `symbol`.
Так как строка - неизменяемый тип данных, то мы вынуждены сначала разбить ее на что-то изменяемое - например, список.
Далее работаем со счетчиком символов. Если счетчик равен заданному индексу - заменяем символ.
Счетчик сбрасывается по достижении разделителя.
'''
@LostInKadath
LostInKadath / task151.py
Last active January 15, 2019 13:59
Найти три первых числа Смита, больших заданного числа
'''https://t.me/unilecs
Задача 151. Найти три первых числа Смита, больших заданного числа
Число Смита - это составное число, у которого сумма составляющих его цифр равна сумме цифр, составляющих его разложение на простые сомножители.
Например:
4937775 = 3 * 5 * 5 * 65837,
4 + 9 + 3 + 7 + 7 + 7 + 5 = 42,
3 + 5 + 5 + 6 + 5 + 8 + 3 + 7 = 42.
Поэтому топорный подход "в лоб". Проверяем каждое число, большее заданного.
Раскладываем его на простые сомножители, находим суммы цифр, сравниваем.