diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..3754daf --- /dev/null +++ b/.clang-format @@ -0,0 +1,244 @@ +--- +Language: Cpp +# BasedOnStyle: WebKit +AccessModifierOffset: -4 +AlignAfterOpenBracket: DontAlign +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseColons: false +AlignEscapedNewlines: Right +AlignOperands: DontAlign +AlignTrailingComments: + Kind: Never + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowBreakBeforeNoexceptSpecifier: Never +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: false +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterExternBlock: false + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Leave +BreakAfterJavaFieldAnnotations: false +BreakArrays: true +BreakBeforeBinaryOperators: All +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: WebKit +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeComma +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +ColumnLimit: 0 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: false +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: false +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: None +IndentRequiresClause: true +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +KeepEmptyLinesAtEOF: false +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: Inner +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 4 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: true +ObjCSpaceBeforeProtocolList: true +PackConstructorInitializers: BinPack +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Left +PPIndentWidth: -1 +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: true +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: true +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..f401109 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.25) + +project(C_Homework C) + +add_subdirectory(src/CompilationProcess) + +add_compile_options(-Wall -Wextra -Wpedantic) \ No newline at end of file diff --git a/src/CompilationProcess/CMakeLists.txt b/src/CompilationProcess/CMakeLists.txt new file mode 100644 index 0000000..9344107 --- /dev/null +++ b/src/CompilationProcess/CMakeLists.txt @@ -0,0 +1,3 @@ +add_executable(braketBalance bracketBalance.c) +add_executable(oneStringInAnother oneStringInAnother.c) +add_executable(zerosInMassive zerosInMassive.c) \ No newline at end of file diff --git a/src/CompilationProcess/bracketBalance.c b/src/CompilationProcess/bracketBalance.c new file mode 100644 index 0000000..bf06707 --- /dev/null +++ b/src/CompilationProcess/bracketBalance.c @@ -0,0 +1,61 @@ +#include +#include +#include + +bool checkBrackets(char* stringWithBrackets, int len) +{ + if (len == 0) { + return false; + } + // специальный счетчик, "(" это +1 ")" это -1. Если скобочная посл-ть + // правильная, counter == 0 + int counter = 0; + for (int i = 0; i < len; i++) { + if (stringWithBrackets[i] == '(') { + counter++; + } + if (stringWithBrackets[i] == ')') { + counter--; + } + if (counter < 0) { + break; + } + } + if (counter == 0) { + return true; + } + return false; +} + +int main() +{ + // подразумеватся, что пользователь может ввести не только скобки и в кол-ве + // символов он должен указать всё кол-во символов включая скобки и не скобки. + int len = 0; + printf("Введите, сколько символов Вы хотите ввести, закончите ввод, нажав " + "enter\n"); + printf("На следующей строке введите скобочную последовательность\n"); + scanf("%d", &len); + // отловим этот '\n' + getchar(); + char* stringWithBrackets = malloc(len * sizeof(char)); + // счетчик чтобы считать кол-во скобок + int counter = 0; + for (int i = 0; i < len; i++) { + char tmp = ' '; + scanf("%c", &tmp); + if (tmp == ')' || tmp == '(') { + stringWithBrackets[counter] = tmp; + ++counter; + } + } + bool isCorrect = checkBrackets(stringWithBrackets, counter); + if (isCorrect) { + printf("Скобочная последовательность правильная\n"); + } else { + printf("Скобочная последовательность неправильная или не было введено ни " + "одной скобки\n"); + } + free(stringWithBrackets); + return 0; +} diff --git a/src/CompilationProcess/oneStringInAnother.c b/src/CompilationProcess/oneStringInAnother.c new file mode 100644 index 0000000..3773e47 --- /dev/null +++ b/src/CompilationProcess/oneStringInAnother.c @@ -0,0 +1,28 @@ +#include +#include +#include + +int main() +{ + char biggerString[] = "hellohellhellolllhello"; + char smallerString[] = "hello"; + size_t lenForBiggerString = sizeof(biggerString) / sizeof(char) - 1; + size_t lenForSmallerString = sizeof(smallerString) / sizeof(char) - 1; + int entryCounter = 0; + // i - индекс эл-та с которого будем рассматривать большую строку + for (unsigned i = 0; i <= lenForBiggerString - lenForSmallerString; i++) { + bool flag = true; + for (unsigned j = 0; j < lenForSmallerString; j++) { + if (biggerString[i + j] != smallerString[j]) { + flag = false; + break; + } + } + if (flag) { + ++entryCounter; + } + } + printf("%d\n", entryCounter); + return 0; +} +// Должно вывести 3 diff --git a/src/CompilationProcess/zerosInMassive.c b/src/CompilationProcess/zerosInMassive.c new file mode 100644 index 0000000..6a8b24b --- /dev/null +++ b/src/CompilationProcess/zerosInMassive.c @@ -0,0 +1,19 @@ +#include + +int main() +{ + // пусть массив задан в программе + int arrayWithNumbers[] = { 0, 1, 3, 0, 6, 0, 7, 4, 6, 2, 0, 0 }; + int zeroCounter = 0; + size_t lengthOfArray = sizeof(arrayWithNumbers) / sizeof(int); + + for (int i = 0; i < lengthOfArray; i++) { + if (arrayWithNumbers[i] == 0) { + ++zeroCounter; + } + } + printf("%d\n", zeroCounter); + return 0; +} + +// выводит 5 - кол-во нулей diff --git a/src/bracketBalance.c b/src/bracketBalance.c new file mode 100644 index 0000000..bf06707 --- /dev/null +++ b/src/bracketBalance.c @@ -0,0 +1,61 @@ +#include +#include +#include + +bool checkBrackets(char* stringWithBrackets, int len) +{ + if (len == 0) { + return false; + } + // специальный счетчик, "(" это +1 ")" это -1. Если скобочная посл-ть + // правильная, counter == 0 + int counter = 0; + for (int i = 0; i < len; i++) { + if (stringWithBrackets[i] == '(') { + counter++; + } + if (stringWithBrackets[i] == ')') { + counter--; + } + if (counter < 0) { + break; + } + } + if (counter == 0) { + return true; + } + return false; +} + +int main() +{ + // подразумеватся, что пользователь может ввести не только скобки и в кол-ве + // символов он должен указать всё кол-во символов включая скобки и не скобки. + int len = 0; + printf("Введите, сколько символов Вы хотите ввести, закончите ввод, нажав " + "enter\n"); + printf("На следующей строке введите скобочную последовательность\n"); + scanf("%d", &len); + // отловим этот '\n' + getchar(); + char* stringWithBrackets = malloc(len * sizeof(char)); + // счетчик чтобы считать кол-во скобок + int counter = 0; + for (int i = 0; i < len; i++) { + char tmp = ' '; + scanf("%c", &tmp); + if (tmp == ')' || tmp == '(') { + stringWithBrackets[counter] = tmp; + ++counter; + } + } + bool isCorrect = checkBrackets(stringWithBrackets, counter); + if (isCorrect) { + printf("Скобочная последовательность правильная\n"); + } else { + printf("Скобочная последовательность неправильная или не было введено ни " + "одной скобки\n"); + } + free(stringWithBrackets); + return 0; +} diff --git a/src/divisionWithoutDivision.c b/src/divisionWithoutDivision.c new file mode 100644 index 0000000..879c8ae --- /dev/null +++ b/src/divisionWithoutDivision.c @@ -0,0 +1,41 @@ +#include +#include +#include + +int main() +{ + int a = 0; + int b = 0; + int howManyTimesBInA = 0; + scanf("%d %d", &a, &b); + + int underZero = false; // флаг, чтобы понять какие значения введены + // 0 - положит + if ((a * b) < 0) { + underZero = true; // впоследствии учтем, что ответ должен быть < 0 + } + + a = abs(a); + b = abs(b); + int rememberA = abs(a); + + if (b == 0) { + printf("devision by zero\n"); + return 1; + } + + while (a - b > 0) { + a = a - b; + howManyTimesBInA += 1; + } + if (b * howManyTimesBInA + a == rememberA) { + if (underZero == true) { + printf("%d\n", howManyTimesBInA * (-1) - 1); + } else { + printf("%d\n", howManyTimesBInA); + } + } + + return 0; +} + diff --git a/src/division_without_devision.c b/src/division_without_devision.c deleted file mode 100644 index 61babcb..0000000 --- a/src/division_without_devision.c +++ /dev/null @@ -1,39 +0,0 @@ -#include -#include - -int main() { - int a; - int b; - int r = 0; // сколько раз вмещается b в a - scanf("%d %d", &a, &b); - int remember_a = a; - int under_zero = 0; // флаг, чтобы понять какие значения введены - // 0 - положит - if ((a < 0 | b < 0) && !(a < 0 && b < 0)) { - under_zero = 1; // впоследствии учтем, что ответ должен быть < 0 - } - - a = abs(a); - b = abs(b); - remember_a = abs(remember_a); - - if (b == 0) { - printf("devision by zero\n"); - } - - else { - while (a - b > 0) { - a = a - b; - r += 1; - } - if (b * r + a == remember_a) { - if (under_zero == 1) { - printf("%d\n", r * (-1) - 1); - } else { - printf("%d\n", r); - } - } - } - - return 0; -} diff --git a/src/file_to_be.c b/src/file_to_be.c deleted file mode 100644 index e69de29..0000000 diff --git a/src/happy_tickets.c b/src/happyTickets.c similarity index 93% rename from src/happy_tickets.c rename to src/happyTickets.c index a997605..92c7ded 100644 --- a/src/happy_tickets.c +++ b/src/happyTickets.c @@ -1,9 +1,11 @@ #include -int main() { +int main() +{ int count = 0; int sums[28] = { 0 }; // в массив будем заносить сколькими способами можно получить суммы от 0 до 27 for (int a = 0; a <= 9; a++) { + for (int b = 0; b <= 9; b++) { for (int c = 0; c <= 9; c++) { int sum = a + b + c; @@ -12,11 +14,10 @@ int main() { } } - for (int i = 0; i <= 27; i++) { + for (int i = 0; i <= 27; i++) count += sums[i] * sums[i]; // считаем сколькими разными способами можно получить одинаковые суммы первых трех и // последних трех цифр - } + printf("%d\n", count); return 0; } - diff --git a/src/oneStringInAnother.c b/src/oneStringInAnother.c new file mode 100644 index 0000000..1254d15 --- /dev/null +++ b/src/oneStringInAnother.c @@ -0,0 +1,27 @@ +#include +#include +#include + +int main() { + char biggerString[] = "hellohellhellolllhello"; + char smallerString[] = "hello"; + size_t lenForBiggerString = sizeof(biggerString) / sizeof(char) - 1; + size_t lenForSmallerString = sizeof(smallerString) / sizeof(char) - 1; + int entryCounter = 0; + // i - индекс эл-та с которого будем рассматривать большую строку + for (unsigned i = 0; i <= lenForBiggerString - lenForSmallerString; i++) { + bool flag = true; + for (unsigned j = 0; j < lenForSmallerString; j++) { + if (biggerString[i + j] != smallerString[j]) { + flag = false; + break; + } + } + if (flag) { + ++entryCounter; + } + } + printf("%d\n", entryCounter); + return 0; +} +// Должно вывести 3 diff --git a/src/zerosInMassive.c b/src/zerosInMassive.c new file mode 100644 index 0000000..6a8b24b --- /dev/null +++ b/src/zerosInMassive.c @@ -0,0 +1,19 @@ +#include + +int main() +{ + // пусть массив задан в программе + int arrayWithNumbers[] = { 0, 1, 3, 0, 6, 0, 7, 4, 6, 2, 0, 0 }; + int zeroCounter = 0; + size_t lengthOfArray = sizeof(arrayWithNumbers) / sizeof(int); + + for (int i = 0; i < lengthOfArray; i++) { + if (arrayWithNumbers[i] == 0) { + ++zeroCounter; + } + } + printf("%d\n", zeroCounter); + return 0; +} + +// выводит 5 - кол-во нулей