Initial commit
This commit is contained in:
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
*.out
|
||||
80
cpp/programs/knapsack_rewritable_array.cpp
Normal file
80
cpp/programs/knapsack_rewritable_array.cpp
Normal file
@@ -0,0 +1,80 @@
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <algorithm>
|
||||
|
||||
using namespace std;
|
||||
|
||||
ifstream input_stream;
|
||||
ofstream output_stream;
|
||||
|
||||
|
||||
|
||||
int getMaxValue(int P[], int W[], int C, int N) {
|
||||
int table[2][C] = {0};
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
for (int j = 0; j < C; j++) {
|
||||
table[i][j] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < N; i++) {
|
||||
int *topRow;
|
||||
int *bottomRow;
|
||||
if (i % 2 == 0) {
|
||||
topRow = table[0];
|
||||
bottomRow = table[1];
|
||||
} else {
|
||||
topRow = table[1];
|
||||
bottomRow = table[0];
|
||||
}
|
||||
|
||||
|
||||
if (1 >= W[i]) {
|
||||
bottomRow[0] = max(P[i] + topRow[1 - W[i]], bottomRow[1 - 1]);
|
||||
} else {
|
||||
bottomRow[0] = bottomRow[1 - 1];
|
||||
}
|
||||
|
||||
for (int w = 1; w < C; w++) {
|
||||
if (w + 1 > W[i]) {
|
||||
bottomRow[w] = max(P[i] + topRow[(w + 1) - W[i]], topRow[w]);
|
||||
} else {
|
||||
bottomRow[w] = topRow[w];
|
||||
}
|
||||
|
||||
for (int y = 0; y < 2; y++) {
|
||||
for (int x = 0; x < C; x++) {
|
||||
cout << table[y][x] << " ";
|
||||
}
|
||||
cout << endl;
|
||||
}
|
||||
// string tmp;
|
||||
// cin >> tmp;
|
||||
}
|
||||
}
|
||||
|
||||
return max(table[0][C-1], table[1][C-1]);
|
||||
}
|
||||
|
||||
|
||||
int main() {
|
||||
input_stream.open("input.txt");
|
||||
|
||||
int N, C;
|
||||
input_stream >> N;
|
||||
input_stream >> C;
|
||||
|
||||
int P[N];
|
||||
int W[N];
|
||||
|
||||
for (int i = 0; i < N; i++) {
|
||||
input_stream >> W[i];
|
||||
input_stream >> P[i];
|
||||
}
|
||||
|
||||
cout << getMaxValue(P, W, C, N) << endl;
|
||||
|
||||
input_stream.close();
|
||||
return 0;
|
||||
}
|
||||
100
cpp/programs/quick_primes.cpp
Normal file
100
cpp/programs/quick_primes.cpp
Normal file
@@ -0,0 +1,100 @@
|
||||
#include <iostream>
|
||||
#include <list>
|
||||
#include <cmath>
|
||||
using namespace std;
|
||||
|
||||
|
||||
|
||||
int main() {
|
||||
int start, end;
|
||||
|
||||
cin >> start;
|
||||
cin >> end;
|
||||
// const int start = 1;
|
||||
// const int end = 1000000;
|
||||
|
||||
|
||||
|
||||
list<int> primes;
|
||||
|
||||
primes.push_back(1);
|
||||
primes.push_back(2);
|
||||
primes.push_back(3);
|
||||
primes.push_back(5);
|
||||
|
||||
// Fill all numbers, excluding most obvious non-primes numbers
|
||||
for (int i = 6; i <= end; i++) {
|
||||
if (i % 2 == 0 || i % 3 == 0 || i % 5 == 0) {
|
||||
continue;
|
||||
}
|
||||
primes.push_back(i);
|
||||
}
|
||||
|
||||
auto it = primes.begin();
|
||||
advance(it, 4);
|
||||
|
||||
int stop = sqrt(end);
|
||||
for (it; *it <= stop; it++) {
|
||||
/*
|
||||
Go through all numbers in the list that are lower than sqrt(end)
|
||||
The list is modified in the loop, allowing to skip processing of some numbers
|
||||
*/
|
||||
int factor = *it;
|
||||
|
||||
auto it2 = it;
|
||||
it2++;
|
||||
|
||||
auto stop2 = primes.end();
|
||||
for (it2; it2 != stop2; it2++) {
|
||||
/*
|
||||
Go through all numbers that are greater than the *it,
|
||||
removing them if they can be divided by *it
|
||||
*/
|
||||
|
||||
if (*it2 % factor == 0) {
|
||||
auto tmp = next(it2);
|
||||
|
||||
primes.erase(it2);
|
||||
|
||||
it2 = prev(tmp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A dumb way to handle end < 5
|
||||
if (end < primes.back()) {
|
||||
auto trueEnd = primes.begin();
|
||||
auto stop = primes.end();
|
||||
while (trueEnd != stop && *trueEnd <= end) {
|
||||
trueEnd++;
|
||||
}
|
||||
primes.erase(trueEnd, stop);
|
||||
}
|
||||
|
||||
|
||||
auto startIt = primes.end();
|
||||
auto primesEnd = primes.end();
|
||||
|
||||
it = primes.begin();
|
||||
for (it; it != primesEnd; it++) {
|
||||
if (*it >= start) {
|
||||
startIt = it;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (start == end && *startIt != start) {
|
||||
// Range contains only one number and it's not prime
|
||||
cout << "Absent" << endl;
|
||||
} else if (it == primesEnd) {
|
||||
cout << "Absent" << endl;
|
||||
} else {
|
||||
it = startIt;
|
||||
for (it; it != primesEnd; it++) {
|
||||
cout << *it << " ";
|
||||
}
|
||||
cout << endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
98
cpp/programs/random.cpp
Normal file
98
cpp/programs/random.cpp
Normal file
@@ -0,0 +1,98 @@
|
||||
#include <iostream>
|
||||
#include <random>
|
||||
#include <ctime>
|
||||
|
||||
using namespace std;
|
||||
|
||||
|
||||
typedef mt19937 MyRNG;
|
||||
// uint32_t seed_val;
|
||||
|
||||
MyRNG rng;
|
||||
bool rngInitialized = false;
|
||||
|
||||
const string ALPHABET = "abcdefghijklmnopqrstuvwxyz ";
|
||||
const string DESIRED_STRING = "methinks it is like a weasel";
|
||||
|
||||
|
||||
void initialize_random() {
|
||||
rng.seed(time(0));
|
||||
}
|
||||
|
||||
|
||||
int randint(int start, int end) {
|
||||
if (!rngInitialized) {
|
||||
initialize_random();
|
||||
rngInitialized = true;
|
||||
}
|
||||
|
||||
uniform_int_distribution<uint32_t> myDist(start, end);
|
||||
return myDist(rng);
|
||||
}
|
||||
|
||||
|
||||
string generate_string(string seed) {
|
||||
string result;
|
||||
for (int i = 0; i < DESIRED_STRING.length(); i++) {
|
||||
if (seed[i] == DESIRED_STRING[i]) {
|
||||
result = result + seed[i];
|
||||
} else {
|
||||
result = result + ALPHABET[randint(0, 26)];
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
string generate_string() {
|
||||
string seed;
|
||||
for (int i = 0; i < DESIRED_STRING.length(); i++) {
|
||||
seed = seed + '-';
|
||||
}
|
||||
return generate_string(seed);
|
||||
}
|
||||
|
||||
|
||||
int appraise_string(string str) {
|
||||
if (str == DESIRED_STRING) {
|
||||
return 100;
|
||||
}
|
||||
|
||||
int correct = 0;
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
if (str[i] == DESIRED_STRING[i]) {
|
||||
correct++;
|
||||
}
|
||||
}
|
||||
|
||||
return (correct * 100) / DESIRED_STRING.length();
|
||||
}
|
||||
|
||||
|
||||
int main() {
|
||||
string res = generate_string();
|
||||
int current_attempt = appraise_string(res);
|
||||
int best_attempt = current_attempt;
|
||||
string best_attempt_str = res;
|
||||
|
||||
int counter = 0;
|
||||
while(current_attempt != 100) {
|
||||
res = generate_string(best_attempt_str);
|
||||
current_attempt = appraise_string(res);
|
||||
|
||||
if (current_attempt > best_attempt) {
|
||||
best_attempt = current_attempt;
|
||||
best_attempt_str = res;
|
||||
}
|
||||
|
||||
if (counter == 1000) {
|
||||
cout << "Current best attempt with " << best_attempt << "%: " << best_attempt_str << endl;
|
||||
counter = 0;
|
||||
}
|
||||
|
||||
counter++;
|
||||
}
|
||||
|
||||
cout << "Generated result with counter at " << counter << endl;
|
||||
return 0;
|
||||
}
|
||||
92
cpp/programs/sort_merge.cpp
Normal file
92
cpp/programs/sort_merge.cpp
Normal file
@@ -0,0 +1,92 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
void merge(int array[], int left, int mid, int right) {
|
||||
int leftArrLen = mid - left + 1;
|
||||
int rightArrLen = right - mid;
|
||||
|
||||
// Create temp arrays
|
||||
int leftArray[leftArrLen];
|
||||
int rightArray[rightArrLen];
|
||||
|
||||
// Copy data to temp arrays leftArray[] and rightArray[]
|
||||
for (int i = 0; i < leftArrLen; i++) {
|
||||
leftArray[i] = array[left + i];
|
||||
}
|
||||
|
||||
for (auto i = 0; i < rightArrLen; i++) {
|
||||
rightArray[i] = array[mid + 1 + i];
|
||||
}
|
||||
|
||||
int leftArrIndex = 0; // Initial index of first sub-array
|
||||
int rightArrIndex = 0; // Initial index of second sub-array
|
||||
int mergedArrIndex = left; // Initial index of merged array
|
||||
|
||||
// Merge the temp arrays back into array[left..right]
|
||||
while (leftArrIndex < leftArrLen && rightArrIndex < rightArrLen) {
|
||||
// Choose one of the two elements at current positions of left and right arrays
|
||||
if (leftArray[leftArrIndex] <= rightArray[rightArrIndex]) {
|
||||
array[mergedArrIndex] = leftArray[leftArrIndex];
|
||||
leftArrIndex++;
|
||||
} else {
|
||||
array[mergedArrIndex] = rightArray[rightArrIndex];
|
||||
rightArrIndex++;
|
||||
}
|
||||
mergedArrIndex++;
|
||||
}
|
||||
|
||||
// Copy the remaining elements of
|
||||
// left[], if there are any
|
||||
while (leftArrIndex < leftArrLen) {
|
||||
array[mergedArrIndex] = leftArray[leftArrIndex];
|
||||
leftArrIndex++;
|
||||
mergedArrIndex++;
|
||||
}
|
||||
|
||||
// Copy the remaining elements of
|
||||
// right[], if there are any
|
||||
while (rightArrIndex < rightArrLen) {
|
||||
array[mergedArrIndex] = rightArray[rightArrIndex];
|
||||
rightArrIndex++;
|
||||
mergedArrIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void mergeSort(int arr[], int left, int right) {
|
||||
if (left >= right) {
|
||||
return;
|
||||
}
|
||||
|
||||
int middle = (left + right) / 2;
|
||||
mergeSort(arr, left, middle);
|
||||
mergeSort(arr, middle + 1, right);
|
||||
merge(arr, left, middle, right);
|
||||
}
|
||||
|
||||
// 4 1 3 5 2
|
||||
// 4 1 3 5 2 [4, 1] [3]
|
||||
// 4 1 3 5 2 [^1, 4] [^3]
|
||||
// 1 1 3 5 2 [1, ^4] [^3]
|
||||
// 1 3 3 5 2 [1, ^4] [3]^
|
||||
// 1 3 4 5 2 [^5] [^2]
|
||||
// 1 3 4 2 2 [^5] [2]^
|
||||
// 1 3 4 2 5
|
||||
|
||||
|
||||
|
||||
int main() {
|
||||
int N = 50;
|
||||
int arr[N];
|
||||
for (int i = 0; i < N; i++) {
|
||||
arr[i] = N - i;
|
||||
}
|
||||
|
||||
mergeSort(arr, 0, N - 1);
|
||||
|
||||
for (int i = 0; i < N; i++) {
|
||||
cout << arr[i] << " ";
|
||||
}
|
||||
cout << endl;
|
||||
return 0;
|
||||
}
|
||||
73
cpp/programs/sort_quick.cpp
Normal file
73
cpp/programs/sort_quick.cpp
Normal file
@@ -0,0 +1,73 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
|
||||
int partition(int arr[], int start, int end) {
|
||||
int pivot = arr[start];
|
||||
|
||||
int count = 0;
|
||||
for (int i = start + 1; i <= end; i++) {
|
||||
if (arr[i] <= pivot){
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
// Giving pivot element its correct position
|
||||
int pivotIndex = start + count;
|
||||
swap(arr[pivotIndex], arr[start]);
|
||||
|
||||
// Sorting left and right parts of the pivot element
|
||||
int i = start, j = end;
|
||||
|
||||
while (i < pivotIndex && j > pivotIndex) {
|
||||
while (arr[i] <= pivot) {
|
||||
// Find index of the first element from left that is higher than pivot
|
||||
i++;
|
||||
}
|
||||
|
||||
while (arr[j] > pivot) {
|
||||
// Find index of the first element from right that is lower than pivot
|
||||
j--;
|
||||
}
|
||||
|
||||
if (i < pivotIndex && j > pivotIndex) {
|
||||
swap(arr[i], arr[j]);
|
||||
i++;
|
||||
j--;
|
||||
}
|
||||
}
|
||||
|
||||
return pivotIndex;
|
||||
}
|
||||
|
||||
|
||||
void quickSort(int arr[], int low, int high) {
|
||||
if (low < high) {
|
||||
int pi = partition(arr, low, high);
|
||||
|
||||
quickSort(arr, low, pi - 1);
|
||||
quickSort(arr, pi + 1, high);
|
||||
}
|
||||
}
|
||||
// 4 1 3 5 2
|
||||
// 5 1 3 4 2
|
||||
// 2 1 3 4 5
|
||||
// 1 2 3 4 5
|
||||
|
||||
|
||||
|
||||
int main() {
|
||||
int N = 50;
|
||||
int arr[N];
|
||||
for (int i = 0; i < N; i++) {
|
||||
arr[i] = N - i;
|
||||
}
|
||||
|
||||
quickSort(arr, 0, N - 1);
|
||||
|
||||
for (int i = 0; i < N; i++) {
|
||||
cout << arr[i] << " ";
|
||||
}
|
||||
cout << endl;
|
||||
return 0;
|
||||
}
|
||||
8
cpp/Импортирование/main.cpp
Normal file
8
cpp/Импортирование/main.cpp
Normal file
@@ -0,0 +1,8 @@
|
||||
#include "test.cpp"
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(){
|
||||
test_func();
|
||||
return 0;
|
||||
}
|
||||
7
cpp/Импортирование/test.cpp
Normal file
7
cpp/Импортирование/test.cpp
Normal file
@@ -0,0 +1,7 @@
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
void test_func(){
|
||||
cout << "Hello World!\n";
|
||||
}
|
||||
29
cpp/Классы/main.cpp
Normal file
29
cpp/Классы/main.cpp
Normal file
@@ -0,0 +1,29 @@
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
string name = "Cat";
|
||||
|
||||
// Объявление класса
|
||||
class MyClass {
|
||||
public:
|
||||
int myNum;
|
||||
string name;
|
||||
|
||||
string str() {
|
||||
return name;
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
// Создание объекта
|
||||
MyClass myObj;
|
||||
|
||||
// Доступ к атрибутам
|
||||
myObj.myNum = 5;
|
||||
myObj.name = "Vincent";
|
||||
|
||||
cout << myObj.str() << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
20
cpp/Основы/ввод.cpp
Normal file
20
cpp/Основы/ввод.cpp
Normal file
@@ -0,0 +1,20 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main(){
|
||||
/* Ввод
|
||||
Синтаксис: устройство >> переменная
|
||||
cin - console input - консоль как устройство ввода
|
||||
>> оператор ввода
|
||||
*/
|
||||
float num;
|
||||
cout << "Введи число: "; // *Отсутствует endl
|
||||
cin >> num;
|
||||
cout << "Число в квадрате: " << num * num << endl;
|
||||
|
||||
printf("Введи число: ");
|
||||
scanf("%f", &num); // Ввод в стиле C
|
||||
printf("Число, умноженное на 5: %f\n", num * 5);
|
||||
|
||||
return 0;
|
||||
}
|
||||
33
cpp/Основы/вывод.cpp
Normal file
33
cpp/Основы/вывод.cpp
Normal file
@@ -0,0 +1,33 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main(){
|
||||
/* Вывод
|
||||
Синтаксис: устройство << данные
|
||||
cout - console out - консоль как устройство вывода
|
||||
<< - оператор вывода. При использовании этого синтаксиса способен конкатенировать строки.
|
||||
endl - '\n'
|
||||
*/
|
||||
cout << "Ever heard of rubber duck debugging?" << endl;
|
||||
cout << " __ " << endl;
|
||||
cout << " <(o )___-" << endl;
|
||||
cout << " ( .__> /" << endl;
|
||||
cout << " `----' " << endl;
|
||||
|
||||
printf("printf output: \n"); // Вывод в стиле C
|
||||
char t;
|
||||
t = 'f';
|
||||
printf("printf output char: %c\n", t);
|
||||
/*
|
||||
%[flags][width][.precision][length]specifier
|
||||
c - character, s - string, d/i - integer,
|
||||
o - unsigned integer (octal), x/X - unsigned integer (hexadecimal),
|
||||
u - unsigned integer (decimal), f/F - float (decimal),
|
||||
e/E - float (exponential), a/A - float (hexadecimal exponent),
|
||||
g/G - float (decimal/decimal exponential?),
|
||||
n - number of chars written by far using this call function,
|
||||
p - a pointer that points to the implementation-defined character sequence
|
||||
*/
|
||||
|
||||
return 0;
|
||||
}
|
||||
19
cpp/Основы/комментарии.cpp
Normal file
19
cpp/Основы/комментарии.cpp
Normal file
@@ -0,0 +1,19 @@
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main() {
|
||||
// Это комментарий
|
||||
|
||||
/*
|
||||
Это
|
||||
многострочный
|
||||
комментарий
|
||||
*/
|
||||
|
||||
/**
|
||||
Это комментарий для документации
|
||||
*/
|
||||
|
||||
return 0;
|
||||
}
|
||||
25
cpp/Основы/переменные.cpp
Normal file
25
cpp/Основы/переменные.cpp
Normal file
@@ -0,0 +1,25 @@
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main() {
|
||||
/*
|
||||
Синтаксис: тип имя;
|
||||
или: тип имя = значение;
|
||||
*/
|
||||
|
||||
int myInt;
|
||||
myInt = 5;
|
||||
float myFloat = 6.23;
|
||||
double myDouble = 6.2340282;
|
||||
|
||||
// Pointers
|
||||
int *myPointer;
|
||||
myPointer = &myInt; // создание ссылки
|
||||
cout << "Значение из указателя: " << *myPointer << endl; // Получение значения из ссылки
|
||||
|
||||
// None
|
||||
myPointer = nullptr;
|
||||
|
||||
return 0;
|
||||
}
|
||||
55
cpp/Структуры/if.cpp
Normal file
55
cpp/Структуры/if.cpp
Normal file
@@ -0,0 +1,55 @@
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(){
|
||||
|
||||
/*
|
||||
if (condition) {
|
||||
statement1;
|
||||
statement2;
|
||||
...
|
||||
} else if (condition2) {
|
||||
statement3;
|
||||
statement4;
|
||||
...
|
||||
} else {
|
||||
statement 5;
|
||||
statement 6;
|
||||
...
|
||||
}
|
||||
Работает только потому, что единственное выражение не требует {}
|
||||
Иначе это записывалось бы как:
|
||||
if (condition) {
|
||||
statement1;
|
||||
statement2;
|
||||
...
|
||||
} else {
|
||||
if (condition2) {
|
||||
statement3;
|
||||
statement4;
|
||||
...
|
||||
} else {
|
||||
statement5;
|
||||
statement6;
|
||||
...
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
int inp;
|
||||
|
||||
cout << "Введите число: ";
|
||||
cin >> inp;
|
||||
cout << endl;
|
||||
|
||||
if (inp > 5) {
|
||||
cout << "Ваше число больше 5" << endl;
|
||||
} else if (inp == 5) {
|
||||
cout << "Ваше число равно 5" << endl;
|
||||
} else {
|
||||
cout << "Ваше число меньше 5" << endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
41
cpp/Структуры/switch.cpp
Normal file
41
cpp/Структуры/switch.cpp
Normal file
@@ -0,0 +1,41 @@
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
int main() {
|
||||
/*
|
||||
Синтаксис:
|
||||
switch(var:int) {
|
||||
case n:int: (возможно накопление)
|
||||
statement;
|
||||
break;
|
||||
default:
|
||||
statement;
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
int inp;
|
||||
|
||||
cout << "Введите оценку: ";
|
||||
cin >> inp;
|
||||
cout << endl;
|
||||
|
||||
switch (inp) {
|
||||
case 10:
|
||||
case 9:
|
||||
cout << "The grade is A" << endl;
|
||||
break;
|
||||
case 8:
|
||||
cout << "The grade is B" << endl;
|
||||
break;
|
||||
case 7:
|
||||
cout << "The grade is C" << endl;
|
||||
break;
|
||||
case 6:
|
||||
cout << "The grade is D" << endl;
|
||||
break;
|
||||
default:
|
||||
cout << "The grade is F" << endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
38
cpp/Типы данных/atomic.cpp
Normal file
38
cpp/Типы данных/atomic.cpp
Normal file
@@ -0,0 +1,38 @@
|
||||
#include <iostream>
|
||||
#include <cmath> // Функция pow
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main() {
|
||||
// Фундаментальные типы данных
|
||||
|
||||
// Numeric:
|
||||
int myInt;
|
||||
myInt = 5;
|
||||
float myFloat = 6.23;
|
||||
double myDouble = 6.2340282;
|
||||
|
||||
myInt = float(7) / 3; // Округляет вниз
|
||||
cout << "Результат myInt = float(7)/3: " << myInt << endl; // 2
|
||||
|
||||
cout << "Результат 2+3*4: " << (2+3*4) << endl; // Тип integer, 14
|
||||
cout << "Результат float(7)/3: " << float(7)/3 << endl; // Тип float, 2.33333
|
||||
cout << "Результат 7/3: " << 7/3 << endl; // In C++ this is integer division, 2
|
||||
cout << "Результат 7%3: " << 7%3 << endl; // Тип integer, 1
|
||||
cout << "Результат 2^10: " << pow(2, 10) << endl; // Тип integer, 1024
|
||||
cout << "Результат 2^100000: " << pow(2, 100000) << endl; // infinity?, inf
|
||||
|
||||
// Boolean
|
||||
bool myBoolean;
|
||||
// and - &&; or - ||; not - !;
|
||||
|
||||
// Character
|
||||
char myCharacter = 'f'; // Single quotes (') for chars, double (") for strings
|
||||
|
||||
// Конвертация из одного типа в другой:
|
||||
int origin = 50;
|
||||
double origin_transformed = double(origin);
|
||||
cout << "Преобразованная переменная: " << origin_transformed << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
35
cpp/Типы данных/hash_table.cpp
Normal file
35
cpp/Типы данных/hash_table.cpp
Normal file
@@ -0,0 +1,35 @@
|
||||
#include <iostream>
|
||||
#include <unordered_map>
|
||||
#include <string>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main() {
|
||||
/*
|
||||
Синтаксис: unordered_map<тип_ключа, тип_значения> имя;
|
||||
Методы:
|
||||
.count(key) - true если существует ключ key, иначе false
|
||||
.erase(key) - удалить запись с ключом key
|
||||
.begin() - возвращает итератор к первому элементу
|
||||
.end() - возвращет итератор точке после последнего элемента
|
||||
*/
|
||||
unordered_map<string, string> spnumbers;
|
||||
|
||||
spnumbers = { {"one", "uno"}, {"two", "dos"} };
|
||||
|
||||
spnumbers["three"] = "tres";
|
||||
spnumbers["four"] = "cuatro";
|
||||
|
||||
cout << "Значение с ключом 'one': ";
|
||||
cout << spnumbers["one"] << endl;
|
||||
|
||||
cout << "Размер таблицы: ";
|
||||
cout << spnumbers.size() << endl;
|
||||
|
||||
// Итерация таблицы:
|
||||
for (auto i=spnumbers.begin(); i!=spnumbers.end(); i++){
|
||||
cout << i->first << ":";
|
||||
cout << i->second << endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
35
cpp/Типы данных/set.cpp
Normal file
35
cpp/Типы данных/set.cpp
Normal file
@@ -0,0 +1,35 @@
|
||||
#include <iostream>
|
||||
#include <unordered_set>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main() {
|
||||
/* Множества
|
||||
Синтаксис:
|
||||
set<тип> имя = {n1, n2, n3...};
|
||||
*/
|
||||
unordered_set<int> mySet = {1, 3, 5, 78, 90};
|
||||
unordered_set<int> mySet2 = {4, 9};
|
||||
|
||||
// Преобразование массива в множество:
|
||||
char myChArr[] = {"aaabbbccc"};
|
||||
unordered_set<char> mySet3 = unordered_set<char>(begin(myChArr), end(myChArr));
|
||||
|
||||
cout << "Длина множества: " << mySet3.size() << endl;
|
||||
cout << "Элементы множества:" << endl;
|
||||
for (auto iter = mySet3.begin(); iter != mySet3.end(); iter++) {
|
||||
cout << *iter << endl;
|
||||
}
|
||||
|
||||
// Преобразование строки в множество:
|
||||
string myStr = "zfx";
|
||||
mySet3 = unordered_set<char>(begin(myStr), end(myStr));
|
||||
|
||||
cout << "Длина множества: " << mySet3.size() << endl;
|
||||
cout << "Элементы множества:" << endl;
|
||||
for (auto iter = mySet3.begin(); iter != mySet3.end(); iter++) {
|
||||
cout << *iter << endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
37
cpp/Типы данных/векторы.cpp
Normal file
37
cpp/Типы данных/векторы.cpp
Normal file
@@ -0,0 +1,37 @@
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main() {
|
||||
// Вектор - массив, который может расти
|
||||
/* Создание вектора
|
||||
Синтаксис: vector<тип> имя;
|
||||
Методы:
|
||||
.push_back(item) - добавить в конец (append)
|
||||
.pop_back() - удалить последний элемент
|
||||
.insert(i, item) - вставить элемент на индекс i
|
||||
.erase(i) - удалить элемент с индексом i
|
||||
.size() - возвращает размер, занимаемый элементами
|
||||
.capacity() - возвращает размер выделенного места (вместимость)
|
||||
.reserve(amount) - запросить изменение вместимости
|
||||
*/
|
||||
|
||||
cout << "Векторы:" << endl;
|
||||
vector<int> myVector;
|
||||
/*
|
||||
Если не зарезервировать место заранее, то при каждом выходе за пределы размеров вектора
|
||||
весь массив будет копироваться в вдвое большее место в памяти
|
||||
*/
|
||||
// myVector.reserve(19);
|
||||
|
||||
for (int i=0; i<19; i++) {
|
||||
myVector.push_back(i*i);
|
||||
cout << myVector[i] << endl;
|
||||
// cout << "capacity: " << myVector.capacity() << endl;
|
||||
}
|
||||
|
||||
cout << myVector.size() << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
22
cpp/Типы данных/массивы.cpp
Normal file
22
cpp/Типы данных/массивы.cpp
Normal file
@@ -0,0 +1,22 @@
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main() {
|
||||
/* Создание смежного массива
|
||||
Синтаксис: тип название[размер];
|
||||
или: тип название[] = {n1, n2, n3...};
|
||||
*/
|
||||
int myArr[50];
|
||||
int myArr2[] = {1, 2, 3, 4};
|
||||
|
||||
// Функции len нет, поэтому длина массива высчитывается из занимаемого места:
|
||||
cout << "Длина массива: " << sizeof(myArr2) / sizeof(myArr2[0]) << endl;
|
||||
|
||||
// Для новых версий c++:
|
||||
for(int item:myArr2) {
|
||||
cout << item << endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
35
cpp/Типы данных/строки.cpp
Normal file
35
cpp/Типы данных/строки.cpp
Normal file
@@ -0,0 +1,35 @@
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main() {
|
||||
/* Строки
|
||||
Существует 2 типа: string (стиль c++) и массив char (стиль c)
|
||||
Синтаксис:
|
||||
string имя = "строка";
|
||||
char имя = {"строка"};
|
||||
Методы string:
|
||||
.append(string) - добавить строку в конец
|
||||
.push_back(char) - добавить символ в конец
|
||||
.insert(i, string) - добавить строку на индекс i
|
||||
.erase(i, j) - удалить элементы стоящие между i и j
|
||||
.find(item) - возвращает индекс элемента
|
||||
.length() - возвращает длину
|
||||
.size() - тоже возвращает длину
|
||||
*/
|
||||
|
||||
string myStr = "string";
|
||||
char myChArr[] = {"string"};
|
||||
|
||||
cout << myStr << endl;
|
||||
cout << "Размер: " << myStr.size() << "; Длина: " << myStr.length() << endl;
|
||||
cout << "Позиция подстроки 'tr': " << myStr.find("tr") << endl;
|
||||
cout << "Позиция подстроки 'if': " << myStr.find("if") << endl; // Выводит неприменимое число
|
||||
|
||||
cout << "Все символы строки 'string':"<< endl;
|
||||
for (int i = 0; i < myStr.length(); i++) {
|
||||
cout << myStr[i] << endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
6
cpp/Файлы/inp.txt
Normal file
6
cpp/Файлы/inp.txt
Normal file
@@ -0,0 +1,6 @@
|
||||
554
|
||||
1 4
|
||||
2
|
||||
3
|
||||
4
|
||||
5
|
||||
48
cpp/Файлы/main.cpp
Normal file
48
cpp/Файлы/main.cpp
Normal file
@@ -0,0 +1,48 @@
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
ifstream in_stream;
|
||||
ofstream out_stream;
|
||||
|
||||
int main() {
|
||||
in_stream.open("inp.txt");
|
||||
out_stream.open("out.txt");
|
||||
|
||||
// Чтение файла
|
||||
int N;
|
||||
in_stream >> N;
|
||||
|
||||
cout << "Полученное число из файла: ";
|
||||
cout << N << endl;
|
||||
|
||||
// Чтение двух чисел с одной строки:
|
||||
int x;
|
||||
in_stream >> x;
|
||||
cout << "Первое число второй строки: " << x << endl;
|
||||
int y;
|
||||
in_stream >> y;
|
||||
cout << "Второе число второй строки: " << y << endl;
|
||||
|
||||
// Чтение до конца файла:
|
||||
int sum = 0;
|
||||
int tmp;
|
||||
while(!in_stream.eof()) {
|
||||
in_stream >> tmp;
|
||||
sum += tmp;
|
||||
}
|
||||
/* Аналог:
|
||||
while (in_stream >> tmp) {
|
||||
sum += tmp;
|
||||
}
|
||||
*/
|
||||
cout << "Сумма оставшихся чисел в файле: " << sum << endl;
|
||||
|
||||
// Вывод в файл:
|
||||
out_stream << sum << endl;
|
||||
|
||||
in_stream.close();
|
||||
out_stream.close();
|
||||
return 0;
|
||||
}
|
||||
1
cpp/Файлы/out.txt
Normal file
1
cpp/Файлы/out.txt
Normal file
@@ -0,0 +1 @@
|
||||
14
|
||||
38
cpp/Функции/main.cpp
Normal file
38
cpp/Функции/main.cpp
Normal file
@@ -0,0 +1,38 @@
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
/* Синтаксис:
|
||||
возвращаемый_тип имя(тип_параметра параметр, ...) {
|
||||
return значение;
|
||||
}
|
||||
*/
|
||||
|
||||
int timesTwo(int num) {
|
||||
return num * 2;
|
||||
}
|
||||
|
||||
void printNum(int num) {
|
||||
cout << num << endl;
|
||||
}
|
||||
|
||||
double squareroot(double n) {
|
||||
/**
|
||||
Метод Ньютона
|
||||
*/
|
||||
double root = n / 2;
|
||||
|
||||
for (int i = 0; i < 20; i++) {
|
||||
cout << "Guess " << i << " root " << root << endl;
|
||||
root = (.5) * (root + (n / root));
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int res = timesTwo(5); // Вызов функции, возвращающей значение
|
||||
printNum(res); // Вызов функции, не возвращающей значение
|
||||
cout << squareroot(9) << endl;
|
||||
return 0;
|
||||
}
|
||||
72
cpp/Функции/аргументы.cpp
Normal file
72
cpp/Функции/аргументы.cpp
Normal file
@@ -0,0 +1,72 @@
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
void unchangingFunc(int passedVar) {
|
||||
passedVar = 5; // Значение меняется только внутри функции
|
||||
cout << "Новое значение passedVar внутри unchangingFunc: " << passedVar << endl;
|
||||
}
|
||||
|
||||
|
||||
void swap(int &num1, int &num2) {
|
||||
/**
|
||||
& перед именем в списке аргументов означет, что передастся ссылка на память,
|
||||
с которой можно работать как со значением (обратное преобразование не нужно)
|
||||
*/
|
||||
int temp;
|
||||
temp = num1;
|
||||
num1 = num2;
|
||||
num2 = temp;
|
||||
}
|
||||
|
||||
|
||||
void add_lists( int first[], int second[], int total[], int length ) {
|
||||
/**
|
||||
При передаче массива значения в изначальном массиве также меняются
|
||||
Это поведение можно предотвратить используя const:
|
||||
void add_lists( const int first[], const int second[], int total[], int length )
|
||||
При таком объявлении, попытка изменить значения первых двух массивов внутри функции
|
||||
вызовет ошибку
|
||||
*/
|
||||
for( int i = 0; i < length; i++ ) {
|
||||
total[i] = first[i] + second[i];
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Перегрузка функций позволяет создать несколько функций с одинаковыми именами,
|
||||
но разными параметрами или количеством параметров
|
||||
*/
|
||||
void my_func(int first_arg) {
|
||||
cout << "My func called with one int argument" << endl;
|
||||
}
|
||||
|
||||
|
||||
void my_func(double first_arg) {
|
||||
cout << "My func called with one double argument" << endl;
|
||||
}
|
||||
|
||||
|
||||
void my_func(int first_arg, int second_arg) {
|
||||
cout << "My func called with two int arguments" << endl;
|
||||
}
|
||||
|
||||
|
||||
int main() {
|
||||
int myVar = 3;
|
||||
unchangingFunc(myVar); // Внутри main значение myVar остаётся таким же
|
||||
cout << "Новое значение myVar после unchangingFunc: " << myVar << endl;
|
||||
|
||||
int myOtherVar = 9;
|
||||
// При вызове функции, принимающей ссылки, дополнительные преобразования не нужны
|
||||
swap(myVar, myOtherVar);
|
||||
cout << "После смены мест значение myVar=" << myVar << ", myOtherVar=" << myOtherVar << endl;
|
||||
|
||||
// Вызов перегруженный функций
|
||||
my_func(4);
|
||||
my_func(double(4));
|
||||
my_func(3, 5);
|
||||
|
||||
return 0;
|
||||
}
|
||||
19
cpp/Циклы/for.cpp
Normal file
19
cpp/Циклы/for.cpp
Normal file
@@ -0,0 +1,19 @@
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main() {
|
||||
/* Синтаксис:
|
||||
for (создание переменной; условие; выражение) {
|
||||
statement1;
|
||||
statement2;
|
||||
...
|
||||
}
|
||||
*/
|
||||
|
||||
for (int i = 1; i <= 10; i++) {
|
||||
cout << "You wasted another moment. Now here lay " << i << " dead kittens..." << endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
27
cpp/Циклы/while.cpp
Normal file
27
cpp/Циклы/while.cpp
Normal file
@@ -0,0 +1,27 @@
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
int main (){
|
||||
/* Синтаксис:
|
||||
while (condition) {
|
||||
statement1;
|
||||
statement2;
|
||||
...
|
||||
}
|
||||
или
|
||||
do {
|
||||
statement1;
|
||||
statement2;
|
||||
...
|
||||
} while (condition);
|
||||
*/
|
||||
|
||||
int i = 0;
|
||||
while (i < 5) {
|
||||
cout << "Hello world " << i << "! ";
|
||||
i++;
|
||||
}
|
||||
cout << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
70
python/sqlalchemy/core.py
Normal file
70
python/sqlalchemy/core.py
Normal file
@@ -0,0 +1,70 @@
|
||||
from sqlalchemy import MetaData
|
||||
from sqlalchemy import Table, Column, Integer, String
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy import ForeignKey
|
||||
|
||||
# Model declarations
|
||||
metadata_obj = MetaData()
|
||||
|
||||
user_table = Table(
|
||||
"user_account",
|
||||
metadata_obj,
|
||||
Column('id', Integer, primary_key=True),
|
||||
Column('name', String(30)),
|
||||
Column('fullname', String)
|
||||
)
|
||||
|
||||
address_table = Table(
|
||||
"address",
|
||||
metadata_obj,
|
||||
Column('id', Integer, primary_key=True),
|
||||
Column('user_id', ForeignKey('user_account.id'), nullable=False),
|
||||
Column('email_address', String, nullable=False)
|
||||
)
|
||||
|
||||
# Connection
|
||||
engine = create_engine("sqlite+pysqlite:///:memory:", future=True)
|
||||
|
||||
# Model migration
|
||||
metadata_obj.create_all(engine)
|
||||
|
||||
|
||||
|
||||
# INSERT
|
||||
from sqlalchemy import insert, select
|
||||
|
||||
# values method
|
||||
stmt = insert(user_table).values(name='spongebob', fullname="Spongebob Squarepants")
|
||||
with engine.begin() as conn:
|
||||
conn.execute(stmt)
|
||||
|
||||
|
||||
# autogenerate values
|
||||
with engine.connect() as conn:
|
||||
conn.execute(
|
||||
insert(user_table),
|
||||
[
|
||||
{"name": "sandy", "fullname": "Sandy Cheeks"},
|
||||
{"name": "patrick", "fullname": "Patrick Star"}
|
||||
]
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
# insert..select
|
||||
select_stmt = select(user_table.c.id, user_table.c.name + "@aol.com")
|
||||
insert_stmt = insert(address_table).from_select(
|
||||
["user_id", "email_address"], select_stmt
|
||||
)
|
||||
with engine.begin() as conn:
|
||||
res = conn.execute(insert_stmt)
|
||||
|
||||
|
||||
|
||||
# SELECT
|
||||
from sqlalchemy import select
|
||||
|
||||
stmt = select(user_table).where(user_table.c.name == 'spongebob')
|
||||
with engine.connect() as conn:
|
||||
for row in conn.execute(stmt):
|
||||
print(row)
|
||||
54
python/sqlalchemy/orm.py
Normal file
54
python/sqlalchemy/orm.py
Normal file
@@ -0,0 +1,54 @@
|
||||
from sqlalchemy import Column, Integer, String
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy import ForeignKey
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.orm import registry
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
mapper_registry = registry()
|
||||
Base = mapper_registry.generate_base()
|
||||
|
||||
# from sqlalchemy.orm import declarative_base
|
||||
# Base = declarative_base()
|
||||
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = 'user_account'
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String(30))
|
||||
fullname = Column(String)
|
||||
|
||||
addresses = relationship("Address", back_populates="user")
|
||||
|
||||
def __repr__(self):
|
||||
return f"User(id={self.id!r}, name={self.name!r}, fullname={self.fullname!r})"
|
||||
|
||||
|
||||
|
||||
class Address(Base):
|
||||
__tablename__ = 'address'
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
email_address = Column(String, nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('user_account.id'))
|
||||
|
||||
user = relationship("User", back_populates="addresses")
|
||||
|
||||
def __repr__(self):
|
||||
return f"Address(id={self.id!r}, email_address={self.email_address!r})"
|
||||
|
||||
|
||||
engine = create_engine("sqlite+pysqlite:///:memory:", future=True)
|
||||
Base.metadata.create_all(engine)
|
||||
|
||||
|
||||
|
||||
|
||||
# SELECT
|
||||
from sqlalchemy import select
|
||||
stmt = select(User).where(User.name == 'spongebob')
|
||||
with Session(engine) as conn:
|
||||
for row in conn.execute(stmt):
|
||||
print(row)
|
||||
Reference in New Issue
Block a user