├── .gitignore ├── 30DaysOfCode ├── Day00_HelloWorld.cpp ├── Day01_DataTypes.cpp ├── Day02_Operators.cpp ├── Day03_ConditionalStatements.cpp ├── Day04_ClassVSInstance.cpp ├── Day05_Loops.cpp ├── Day06_LetsReview.cpp ├── Day07_Arrays.cpp ├── Day08_DictionariesAndMaps.cpp ├── Day09_Recursion.cpp ├── Day10_BinaryNumbers.cpp ├── Day11_2DArrays.cpp ├── Day12_Inheritance.cpp ├── Day13_AbstractClasses.cpp ├── Day14_Scope.cpp ├── Day15_LinkedList.cpp ├── Day16_ExceptionsStringtoInteger.cpp ├── Day17_MoreExceptions.cpp ├── Day18_QueuesAndStacks.cpp ├── Day19_Interfaces.cpp ├── Day20_Sorting.cpp ├── Day21_Generics.cpp ├── Day22_BinarySearchTrees.cpp ├── Day23_BSTLevelOrderTraversal.cpp ├── Day24_MoreLinkedLists.cpp ├── Day25_RunningTimeAndComplexity.cpp ├── Day26_NestedLogic.cpp ├── Day27_Testing.cpp ├── Day28_RegExPatternsAndIntroToDatabase.cpp └── Day29_BitwiseAND.cpp ├── Algorithms ├── Implementation │ ├── AppleAndOrange │ │ └── main.go │ ├── BirthDayChocolate │ │ └── main.go │ ├── BreakingTheRecords │ │ └── main.go │ ├── DivisibleSumPairs │ │ └── main.go │ ├── GradingStudents │ │ └── main.go │ └── Kangaroo │ │ └── main.go ├── Sorting │ ├── BigSorting │ │ └── main.py │ ├── CorrectnessInvariant │ │ └── main.py │ ├── InsertionSort1 │ │ └── main.py │ ├── InsertionSort2 │ │ └── main.py │ └── TutorialIntro │ │ └── main.py └── Warmup │ ├── AVeryBigSum │ └── main.go │ ├── BirthdayCakeCandles │ └── main.go │ ├── CompareTheTriplets │ └── main.go │ ├── DiagonalDifference │ └── main.go │ ├── MinMaxSum │ └── main.go │ ├── PlusMinus │ └── main.go │ ├── SimpleArraySum │ └── main.go │ ├── SolveMeFirst │ └── main.go │ ├── Staircase │ └── main.go │ └── TimeConversion │ └── main.go ├── C++ ├── 1_Introduction │ ├── 1_HelloWorld.cpp │ ├── 2_InputAndOutput.cpp │ ├── 3_BasicDataTypes.cpp │ ├── 4_ConditionalStatements.cpp │ ├── 5_ForLoop.cpp │ ├── 6_Functions.cpp │ ├── 7_Pointer.cpp │ ├── 8_ArrayIntroduction.cpp │ └── 9_VariableSizedArray.cpp ├── 2_Strings │ ├── 10_Strings.cpp │ ├── 11_StringStream.cpp │ └── 12_AttributeParser.cpp ├── 3_Classes │ ├── 13_Structs.cpp │ ├── 14_Class.cpp │ ├── 15_ClassesAndObjects.cpp │ └── 16_BoxIt.cpp ├── 4_STL │ ├── 21_VectorSort.cpp │ ├── 22_VectorErase.cpp │ ├── 23_LowerBound.cpp │ ├── 24_Sets.cpp │ ├── 25_Maps.cpp │ └── 26_PrettyPrint.cpp └── 5_Inheritance │ └── 28_InheritanceIntroduction.cpp ├── C ├── 1_Introduction │ ├── 1_HelloWorld.c │ ├── 2_PlayingWithCharacters.c │ ├── 3_SumAndDifferenceOfTwoNumbers.c │ ├── 4_FunctionsInC.c │ └── 5_PointersInC.c ├── 2_ConditionalsAndLoops │ ├── 10_PrintingPattern.c │ ├── 6_ConditionalStatementsInC.c │ ├── 7_ForLoopInC.c │ ├── 8_SumOfDigitsOfAFiveDigitNumber.c │ └── 9_BitwiseOperators.c ├── 3_ArraysAndStrings │ ├── 11_1DArraysInC.c │ ├── 12_ArrayReversal.c │ ├── 13_PrintingTokens.c │ ├── 14_DigitFrequency.c │ └── 15_DynamicArrayInC.c ├── 4_Functions │ ├── 16_CalculateTheNthTerm.c │ ├── 17_StudentsMarksSum.c │ ├── 18_SortingArrayOfStrings.c │ ├── 19_PermutationsOfStrings.c │ ├── 20_VariadicFunctionsinC.c │ └── 21_QueryingTheDocument.c └── 5_StuctsAndEnums │ ├── 22_BoxesThroughATunnel.c │ ├── 23_SmallTrianglesLargeTriangles.c │ ├── 24_PostTransition.c │ └── 25_StructuringTheDocument.c ├── DataStructures ├── Arrays │ ├── 1_ArraysDS.cpp │ ├── 2DArrayDS.cpp │ ├── DynamicArray.cpp │ └── LeftRotation.cpp └── LinkedList │ └── PrintElements.cpp └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /30DaysOfCode/Day00_HelloWorld.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | string str; 7 | getline(cin, str); 8 | cout << "Hello, World." << endl; 9 | cout << str << endl; 10 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day01_DataTypes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int i = 4; 8 | double d = 4.0; 9 | string s = "HackerRank"; 10 | 11 | int ui; 12 | double ud; 13 | string us; 14 | 15 | cin >> ui; 16 | cin >> ud; 17 | cin.ignore(numeric_limits::max(), '\n'); 18 | getline(cin, us); 19 | 20 | cout << i + ui << endl; 21 | cout << fixed << setprecision(1) << d + ud << endl; 22 | cout << s + us << endl; 23 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day02_Operators.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // Complete the solve function below. 6 | void solve(double meal_cost, int tip_percent, int tax_percent) { 7 | double result = 0.0; 8 | double tip_cost = meal_cost * ((double)tip_percent/100); 9 | double tax_cost = meal_cost * ((double)tax_percent/100); 10 | result = meal_cost + tip_cost + tax_cost; 11 | cout << round(result) << endl; 12 | } 13 | 14 | int main() 15 | { 16 | double meal_cost; 17 | cin >> meal_cost; 18 | cin.ignore(numeric_limits::max(), '\n'); 19 | 20 | int tip_percent; 21 | cin >> tip_percent; 22 | cin.ignore(numeric_limits::max(), '\n'); 23 | 24 | int tax_percent; 25 | cin >> tax_percent; 26 | cin.ignore(numeric_limits::max(), '\n'); 27 | 28 | solve(meal_cost, tip_percent, tax_percent); 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /30DaysOfCode/Day03_ConditionalStatements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cin >> n; 8 | cin.ignore(numeric_limits::max(), '\n'); 9 | 10 | if (n % 2 != 0) { 11 | cout << "Weird" << endl; 12 | } else if (n >= 2 && n <= 5) { 13 | cout << "Not Weird" << endl; 14 | } else if (n >= 6 && n <= 20) { 15 | cout << "Weird" << endl; 16 | } else if (n > 20){ 17 | cout << "Not Weird" << endl; 18 | } 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day04_ClassVSInstance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Person 5 | { 6 | public: 7 | int age; 8 | Person(int initialAge); 9 | void amIOld(); 10 | void yearPasses(); 11 | }; 12 | 13 | Person::Person(int initialAge) 14 | { 15 | // Add some more code to run some checks on initialAge 16 | if (initialAge < 0) { 17 | cout << "Age is not valid, setting age to 0." << endl; 18 | age = 0; 19 | } else { 20 | age = initialAge; 21 | } 22 | } 23 | 24 | void Person::amIOld() 25 | { 26 | // Do some computations in here and print out the correct statement to the console 27 | if (age < 13) { 28 | cout << "You are young." << endl; 29 | } else if (age >= 13 && age < 18) { 30 | cout << "You are a teenager." << endl; 31 | } else { 32 | cout << "You are old." << endl; 33 | } 34 | } 35 | 36 | void Person::yearPasses(){ 37 | // Increment the age of the person in here 38 | age++; 39 | } 40 | 41 | int main() 42 | { 43 | int t; 44 | int age; 45 | cin >> t; 46 | for(int i=0; i < t; i++) { 47 | cin >> age; 48 | Person p(age); 49 | p.amIOld(); 50 | for(int j=0; j < 3; j++) { 51 | p.yearPasses(); 52 | } 53 | p.amIOld(); 54 | cout << '\n'; 55 | } 56 | return 0; 57 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day05_Loops.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n; 8 | cin >> n; 9 | cin.ignore(numeric_limits::max(), '\n'); 10 | 11 | for (int i = 1; i < 11; i++) { 12 | cout << n << " x " << i << " = " << n * i << endl; 13 | } 14 | 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /30DaysOfCode/Day06_LetsReview.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int t; 7 | std::string str; 8 | std::cin >> t; 9 | for(int i=0; i < t; i++) { 10 | std::cin >> str; 11 | std::string even, old; 12 | for (int i = 0; i < str.length(); i++) { 13 | if (i % 2 == 0) { 14 | even += str[i]; 15 | } else { 16 | old += str[i]; 17 | } 18 | } 19 | std::cout << even << " " << old << std::endl; 20 | } 21 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day07_Arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main() 8 | { 9 | int n; 10 | std::cin >> n; 11 | std::cin.ignore(std::numeric_limits::max(), '\n'); 12 | 13 | std::string arr_temp; 14 | getline(std::cin, arr_temp); 15 | 16 | std::stringstream ss(arr_temp); 17 | std::vector v; 18 | int temp; 19 | 20 | while (ss >> temp) { 21 | v.push_back(temp); 22 | } 23 | 24 | for (int i = n-1; i >= 0; i--) 25 | std::cout << v[i] << " "; 26 | } 27 | -------------------------------------------------------------------------------- /30DaysOfCode/Day08_DictionariesAndMaps.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | map phonebook; 10 | int n; 11 | cin >> n; 12 | 13 | int number; 14 | string name; 15 | 16 | for (int i = 0; i < n; i++) { 17 | cin >> name >> number; 18 | phonebook[name] = number; 19 | } 20 | cin.ignore(numeric_limits::max(), '\n'); 21 | while(getline(cin, name)) { 22 | if (name.empty()) 23 | break; 24 | if (phonebook.find(name) == phonebook.end()) { 25 | cout << "Not found\n"; 26 | } else { 27 | cout << name << "=" << phonebook[name] << endl; 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day09_Recursion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int factorial(int n) { 5 | if (n < 2) { 6 | return 1; 7 | } 8 | return n * factorial(n-1); 9 | } 10 | 11 | int main() 12 | { 13 | int n; 14 | cin >> n; 15 | 16 | int result = factorial(n); 17 | cout << result << endl; 18 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day10_BinaryNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int number; 8 | cin >> number; 9 | 10 | int max = 0; 11 | int count = 0; 12 | 13 | int bit; 14 | while (number) { 15 | bit = number % 2; 16 | if (bit == 1){ 17 | count++; 18 | } else { 19 | count = 0; 20 | } 21 | if (max < count) { 22 | max = count; 23 | } 24 | number = number / 2; 25 | } 26 | 27 | cout << max << endl; 28 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day11_2DArrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int A[6][6]; 6 | for (int i = 0; i < 6; i++) { 7 | for (int j = 0; j < 6; j++) { 8 | cin >> A[i][j]; 9 | } 10 | } 11 | 12 | int max = INT_MIN; 13 | for (int i = 1; i < 5; i++) { 14 | for (int j = 1; j < 5; j++) { 15 | int sum = 0; 16 | sum += A[i-1][j-1]; 17 | sum += A[i-1][j]; 18 | sum += A[i-1][j+1]; 19 | sum += A[i][j]; 20 | sum += A[i+1][j-1]; 21 | sum += A[i+1][j]; 22 | sum += A[i+1][j+1]; 23 | if (max < sum) { 24 | max = sum; 25 | } 26 | } 27 | } 28 | cout << max << endl; 29 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day12_Inheritance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | class Person{ 8 | protected: 9 | string firstName; 10 | string lastName; 11 | int id; 12 | public: 13 | Person(string firstName, string lastName, int identification){ 14 | this->firstName = firstName; 15 | this->lastName = lastName; 16 | this->id = identification; 17 | } 18 | void printPerson(){ 19 | cout<< "Name: "<< lastName << ", "<< firstName <<"\nID: "<< id << "\n"; 20 | } 21 | 22 | }; 23 | 24 | class Student : public Person{ 25 | private: 26 | vector testScores; 27 | public: 28 | /* 29 | * Class Constructor 30 | * 31 | * Parameters: 32 | * firstName - A string denoting the Person's first name. 33 | * lastName - A string denoting the Person's last name. 34 | * id - An integer denoting the Person's ID number. 35 | * scores - An array of integers denoting the Person's test scores. 36 | */ 37 | // Write your constructor here 38 | Student(string first, string last, int id, vector scores): 39 | Person(first, last, id), testScores(scores) {}; 40 | 41 | /* 42 | * Function Name: calculate 43 | * Return: A character denoting the grade. 44 | */ 45 | // Write your function here 46 | char calculate() { 47 | int sum = 0; 48 | for (auto a: testScores) sum += a; 49 | int average = sum / testScores.size(); 50 | 51 | if (90 <= average && average <= 100) return 'O'; 52 | else if (80 <= average && average < 90) return 'E'; 53 | else if (70 <= average && average < 80) return 'A'; 54 | else if (55 <= average && average < 70) return 'P'; 55 | else if (40 <= average && average < 55) return 'D'; 56 | else return 'T'; 57 | } 58 | }; 59 | 60 | int main() { 61 | string firstName; 62 | string lastName; 63 | int id; 64 | int numScores; 65 | cin >> firstName >> lastName >> id >> numScores; 66 | vector scores; 67 | for(int i = 0; i < numScores; i++){ 68 | int tmpScore; 69 | cin >> tmpScore; 70 | scores.push_back(tmpScore); 71 | } 72 | Student* s = new Student(firstName, lastName, id, scores); 73 | s->printPerson(); 74 | cout << "Grade: " << s->calculate() << "\n"; 75 | return 0; 76 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day13_AbstractClasses.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Book 6 | { 7 | protected: 8 | string title; 9 | string author; 10 | public: 11 | Book(string t,string a) 12 | { 13 | title=t; 14 | author=a; 15 | } 16 | virtual void display()=0; 17 | 18 | }; 19 | 20 | // Write your MyBook class here 21 | 22 | // Class Constructor 23 | // 24 | // Parameters: 25 | // title - The book's title. 26 | // author - The book's author. 27 | // price - The book's price. 28 | // 29 | // Write your constructor here 30 | 31 | 32 | // Function Name: display 33 | // Print the title, author, and price in the specified format. 34 | // 35 | // Write your method here 36 | 37 | // End class 38 | 39 | class MyBook: public Book 40 | { 41 | int price; 42 | public: 43 | MyBook(string t, string a, int p): Book(t, a), price(p) {}; 44 | void display() { 45 | cout << "Title: " << title << endl; 46 | cout << "Author: " << author << endl; 47 | cout << "Price: " << price << endl; 48 | } 49 | }; 50 | 51 | int main() 52 | { 53 | string title,author; 54 | int price; 55 | getline(cin,title); 56 | getline(cin,author); 57 | cin>>price; 58 | MyBook novel(title,author,price); 59 | novel.display(); 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /30DaysOfCode/Day14_Scope.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Difference 6 | { 7 | private: 8 | vector elements; 9 | 10 | public: 11 | int maximumDifference; 12 | Difference(vector e): elements(e) {} 13 | 14 | void computeDifference() 15 | { 16 | auto minimum = min_element(elements.begin(), elements.end()); 17 | auto maximum = max_element(elements.begin(), elements.end()); 18 | maximumDifference = *maximum - *minimum; 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | int N; 25 | cin >> N; 26 | 27 | vector a; 28 | for (int i = 0; i < N; i++) { 29 | int e; 30 | cin >> e; 31 | 32 | a.push_back(e); 33 | } 34 | 35 | Difference d(a); 36 | d.computeDifference(); 37 | cout << d.maximumDifference; 38 | return 0; 39 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day15_LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | Node(int d){ 11 | data=d; 12 | next=NULL; 13 | } 14 | }; 15 | 16 | class Solution 17 | { 18 | public: 19 | Node* insert(Node *head,int data) { 20 | if (head == NULL) 21 | return new Node(data); 22 | Node *temp = head; 23 | while(temp->next) { 24 | temp = temp->next; 25 | } 26 | temp->next = new Node(data); 27 | return head; 28 | } 29 | 30 | void display(Node *head) { 31 | Node *start=head; 32 | while(start) { 33 | cout << start->data<< " "; 34 | start = start->next; 35 | } 36 | } 37 | }; 38 | 39 | int main() 40 | { 41 | Node* head=NULL; 42 | Solution mylist; 43 | int T,data; 44 | cin >> T; 45 | while(T-- > 0){ 46 | cin >> data; 47 | head = mylist.insert(head,data); 48 | } 49 | mylist.display(head); 50 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day16_ExceptionsStringtoInteger.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | string s; 8 | cin >> s; 9 | 10 | try { 11 | int i = stoi(s); 12 | cout << i << '\n'; 13 | } 14 | catch (invalid_argument const &e) { 15 | cout << "Bad String\n"; 16 | } 17 | catch (out_of_range const &e) { 18 | cout << "Bad String\n"; 19 | } 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day17_MoreExceptions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | //Write your code here 8 | class NonNegative: public exception { 9 | virtual const char* what() const throw() { 10 | return "n and p should be non-negative"; 11 | } 12 | }; 13 | 14 | class Calculator 15 | { 16 | public: 17 | int power(int n, int p) 18 | { 19 | if (n < 0 || p < 0) 20 | throw NonNegative(); 21 | return pow(n, p); 22 | } 23 | }; 24 | 25 | int main() 26 | { 27 | Calculator myCalculator = Calculator(); 28 | 29 | int T, n, p; 30 | cin >> T; 31 | 32 | while (T-- > 0) { 33 | if (scanf("%d %d", &n, &p) == 2) { 34 | try { 35 | int ans = myCalculator.power(n,p); 36 | cout << ans << endl; 37 | } 38 | catch(exception& e) { 39 | cout << e.what() << endl; 40 | } 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day18_QueuesAndStacks.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | stack _stack; 9 | queue _queue; 10 | 11 | public: 12 | void pushCharacter(char character) { 13 | _stack.push(character); 14 | } 15 | 16 | char popCharacter() { 17 | char c = _stack.top(); 18 | _stack.pop(); 19 | return c; 20 | } 21 | 22 | void enqueueCharacter(char character) { 23 | _queue.push(character); 24 | } 25 | 26 | char dequeueCharacter() { 27 | char c = _queue.front(); 28 | _queue.pop(); 29 | return c; 30 | } 31 | }; 32 | 33 | int main() { 34 | // read the string s. 35 | string s; 36 | getline(cin, s); 37 | 38 | // create the Solution class object p. 39 | Solution obj; 40 | 41 | // push/enqueue all the characters of string s to stack. 42 | for (int i = 0; i < s.length(); i++) { 43 | obj.pushCharacter(s[i]); 44 | obj.enqueueCharacter(s[i]); 45 | } 46 | 47 | bool isPalindrome = true; 48 | 49 | // pop the top character from stack. 50 | // dequeue the first character from queue. 51 | // compare both the characters. 52 | for (int i = 0; i < s.length() / 2; i++) { 53 | if (obj.popCharacter() != obj.dequeueCharacter()) { 54 | isPalindrome = false; 55 | 56 | break; 57 | } 58 | } 59 | 60 | // finally print whether string s is palindrome or not. 61 | if (isPalindrome) { 62 | cout << "The word, " << s << ", is a palindrome."; 63 | } else { 64 | cout << "The word, " << s << ", is not a palindrome."; 65 | } 66 | 67 | return 0; 68 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day19_Interfaces.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | 10 | class AdvancedArithmetic{ 11 | public: 12 | virtual int divisorSum(int n)=0; 13 | }; 14 | 15 | class Calculator : public AdvancedArithmetic { 16 | public: 17 | int divisorSum(int n) { 18 | int sum = 0; 19 | for (int i = 1; i < n+1; i++) { 20 | if ((n % i) == 0) { 21 | sum += i; 22 | } 23 | } 24 | return sum; 25 | } 26 | }; 27 | 28 | int main(){ 29 | int n; 30 | cin >> n; 31 | AdvancedArithmetic *myCalculator = new Calculator(); 32 | int sum = myCalculator->divisorSum(n); 33 | cout << "I implemented: AdvancedArithmetic\n" << sum; 34 | return 0; 35 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day20_Sorting.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int BubbleSort(vector& vec); 8 | 9 | int main() 10 | { 11 | int n; 12 | cin >> n; 13 | cin.ignore(numeric_limits::max(), '\n'); 14 | 15 | string arr; 16 | getline(cin, arr); 17 | 18 | stringstream ss(arr); 19 | vector v; 20 | 21 | int temp; 22 | while (ss >> temp) { 23 | v.push_back(temp); 24 | } 25 | 26 | int numSwaps = BubbleSort(v); 27 | cout << "Array is sorted in " << numSwaps << " swaps." << endl; 28 | cout << "First Element: " << v[0] << endl; 29 | cout << "Last Element: " << v[v.size()-1] << endl; 30 | 31 | return 0; 32 | } 33 | 34 | int BubbleSort(vector& vec) 35 | { 36 | int numSwaps = 0; 37 | int n = vec.size(); 38 | for (int i = 0; i < n; i++) { 39 | int numberOfSwaps = 0; 40 | for (int j = 0; j < n-1; j++) { 41 | if (vec[j] > vec[j+1]) { 42 | int temp = vec[j]; 43 | vec[j] = vec[j+1]; 44 | vec[j+1] = temp; 45 | numberOfSwaps++; 46 | } 47 | } 48 | numSwaps += numberOfSwaps; 49 | if (numberOfSwaps == 0) break; 50 | } 51 | return numSwaps; 52 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day21_Generics.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | /** 8 | * Name: printArray 9 | * Print each element of the generic vector on a new line. Do not return anything. 10 | * @param A generic vector 11 | **/ 12 | 13 | // Write your code here 14 | template 15 | void printArray(const vector& vec) { 16 | for (int i = 0; i < vec.size(); i++) { 17 | cout << vec[i] << endl; 18 | } 19 | } 20 | 21 | int main() { 22 | int n; 23 | 24 | cin >> n; 25 | vector int_vector(n); 26 | for (int i = 0; i < n; i++) { 27 | int value; 28 | cin >> value; 29 | int_vector[i] = value; 30 | } 31 | 32 | cin >> n; 33 | vector string_vector(n); 34 | for (int i = 0; i < n; i++) { 35 | string value; 36 | cin >> value; 37 | string_vector[i] = value; 38 | } 39 | 40 | printArray(int_vector); 41 | printArray(string_vector); 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day22_BinarySearchTrees.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node *left; 11 | Node *right; 12 | Node(int d){ 13 | data = d; 14 | left = NULL; 15 | right = NULL; 16 | } 17 | }; 18 | 19 | class Solution 20 | { 21 | public: 22 | Node* insert(Node* root, int data) 23 | { 24 | if(root == NULL) { 25 | return new Node(data); 26 | } 27 | else { 28 | Node* cur; 29 | if(data <= root->data) { 30 | cur = insert(root->left, data); 31 | root->left = cur; 32 | } else { 33 | cur = insert(root->right, data); 34 | root->right = cur; 35 | } 36 | return root; 37 | } 38 | } 39 | 40 | int getHeight(Node* root) 41 | { 42 | if(root == NULL) return -1; 43 | int leftHeight = getHeight(root->left); 44 | int rightHeight = getHeight(root->right); 45 | if (leftHeight > rightHeight) 46 | return leftHeight + 1; 47 | return rightHeight + 1; 48 | } 49 | }; 50 | 51 | int main() 52 | { 53 | Solution myTree; 54 | Node* root = NULL; 55 | int t; 56 | int data; 57 | 58 | cin >> t; 59 | 60 | while(t-- > 0) { 61 | cin >> data; 62 | root = myTree.insert(root, data); 63 | } 64 | int height = myTree.getHeight(root); 65 | cout << height; 66 | return 0; 67 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day23_BSTLevelOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | class Node 9 | { 10 | public: 11 | int data; 12 | Node *left, *right; 13 | Node(int d) { 14 | data=d; 15 | left=right=NULL; 16 | } 17 | }; 18 | 19 | class Solution 20 | { 21 | public: 22 | Node* insert(Node* root, int data) 23 | { 24 | if(root == NULL) { 25 | return new Node(data); 26 | } 27 | else { 28 | Node* cur; 29 | if(data <= root->data){ 30 | cur = insert(root->left, data); 31 | root->left = cur; 32 | } 33 | else { 34 | cur = insert(root->right, data); 35 | root->right = cur; 36 | } 37 | return root; 38 | } 39 | } 40 | 41 | void levelOrder(Node * root) { 42 | if (root == NULL) return; 43 | queue q; 44 | q.push(root); 45 | while (!q.empty()) { 46 | Node* current = q.front(); 47 | cout << current->data << " "; 48 | q.pop(); 49 | if (current->left != NULL) 50 | q.push(current->left); 51 | if (current->right != NULL) 52 | q.push(current->right); 53 | } 54 | } 55 | }; //End of Solution 56 | 57 | int main() 58 | { 59 | Solution myTree; 60 | Node* root = NULL; 61 | int T, data; 62 | cin >> T; 63 | while(T-- > 0) { 64 | cin >> data; 65 | root = myTree.insert(root, data); 66 | } 67 | myTree.levelOrder(root); 68 | return 0; 69 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day24_MoreLinkedLists.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | class Node 10 | { 11 | public: 12 | int data; 13 | Node *next; 14 | Node(int d){ 15 | data = d; 16 | next = NULL; 17 | } 18 | }; 19 | 20 | class Solution 21 | { 22 | public: 23 | Node* removeDuplicates(Node *head) 24 | { 25 | //Write your code here 26 | if (head == NULL) 27 | return head; 28 | Node* temp1 = head; 29 | Node* temp2 = NULL; 30 | if (head->next != NULL) 31 | temp2 = head->next; 32 | else 33 | return head; 34 | 35 | while (temp1->next != NULL && temp2 != NULL) { 36 | if (temp1->data != temp2->data) { 37 | if (temp1->next != temp2) { 38 | temp1->next = temp2; 39 | temp1 = temp2; 40 | temp2 = temp1->next; 41 | } else { 42 | temp1 = temp1->next; 43 | temp2 = temp2->next; 44 | } 45 | } else { 46 | temp2 = temp2->next; 47 | } 48 | } 49 | if (temp2 == NULL) 50 | temp1->next = NULL; 51 | return head; 52 | } 53 | 54 | Node* insert(Node *head, int data) 55 | { 56 | Node* p = new Node(data); 57 | if(head == NULL) { 58 | head = p; 59 | } else if (head->next == NULL) { 60 | head->next = p; 61 | } else { 62 | Node *start = head; 63 | while(start->next != NULL) { 64 | start = start->next; 65 | } 66 | start->next = p; 67 | } 68 | return head; 69 | } 70 | 71 | void display(Node *head) 72 | { 73 | Node *start = head; 74 | while(start) { 75 | cout << start->data << " "; 76 | start = start->next; 77 | } 78 | } 79 | }; 80 | 81 | int main() 82 | { 83 | Node* head = NULL; 84 | Solution mylist; 85 | int T, data; 86 | cin >> T; 87 | while (T-- > 0) { 88 | cin >> data; 89 | head = mylist.insert(head, data); 90 | } 91 | head = mylist.removeDuplicates(head); 92 | 93 | mylist.display(head); 94 | } 95 | -------------------------------------------------------------------------------- /30DaysOfCode/Day25_RunningTimeAndComplexity.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool isPrime(int n) 5 | { 6 | // Corner cases 7 | if (n <= 1) return false; 8 | if (n <= 3) return true; 9 | 10 | // This is checked so that we can skip 11 | // middle five numbers in below loop 12 | if (n % 2 == 0 || n % 3 == 0) return false; 13 | 14 | for (int i = 5; i * i <= n; i = i + 6) 15 | if (n % i == 0 || n % (i + 2) == 0) 16 | return false; 17 | return true; 18 | } 19 | 20 | int main() 21 | { 22 | 23 | int testCases; 24 | cin >> testCases; 25 | 26 | while (testCases-- > 0) { 27 | int number; 28 | cin >> number; 29 | cout << (isPrime(number) ? "Prime" : "Not prime") << endl; 30 | } 31 | return 0; 32 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day26_NestedLogic.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int return_date, return_month, return_year; 7 | int expected_return_date, expected_return_month, expected_return_year; 8 | 9 | cin >> return_date >> return_month >> return_year; 10 | cin >> expected_return_date >> expected_return_month >> expected_return_year; 11 | 12 | if (return_year < expected_return_year) { 13 | cout << 0 << endl; 14 | } else if (return_year == expected_return_year) { 15 | if (return_month <= expected_return_month) { 16 | if (return_date <= expected_return_date) { 17 | cout << 0 << endl; 18 | } else { 19 | cout << 15 * (return_date - expected_return_date) << endl; 20 | } 21 | } else { 22 | cout << 500 * (return_month - expected_return_month) << endl; 23 | } 24 | } else { 25 | cout << 10000 << endl; 26 | } 27 | } -------------------------------------------------------------------------------- /30DaysOfCode/Day27_Testing.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | int minimum_index(vector seq) { 11 | if (seq.empty()) { 12 | throw invalid_argument("Cannot get the minimum value index from an empty sequence"); 13 | } 14 | int min_idx = 0; 15 | for (int i = 1; i < seq.size(); ++i) { 16 | if (seq[i] < seq[min_idx]) { 17 | min_idx = i; 18 | } 19 | } 20 | return min_idx; 21 | } 22 | 23 | class TestDataEmptyArray { 24 | public: 25 | static vector get_array() { 26 | vector v; 27 | return v; 28 | } 29 | 30 | }; 31 | 32 | class TestDataUniqueValues { 33 | public: 34 | static vector get_array() { 35 | vector v{4, 3, 5}; 36 | return v; 37 | } 38 | 39 | static int get_expected_result() { 40 | return 1; 41 | } 42 | 43 | }; 44 | 45 | class TestDataExactlyTwoDifferentMinimums { 46 | public: 47 | static vector get_array() { 48 | static vector v {2, 2}; 49 | return v; 50 | } 51 | 52 | static int get_expected_result() { 53 | return 0; 54 | } 55 | 56 | }; 57 | 58 | 59 | void TestWithEmptyArray() { 60 | try { 61 | auto seq = TestDataEmptyArray::get_array(); 62 | auto result = minimum_index(seq); 63 | } catch (invalid_argument& e) { 64 | return; 65 | } 66 | assert(false); 67 | } 68 | 69 | void TestWithUniqueValues() { 70 | auto seq = TestDataUniqueValues::get_array(); 71 | assert(seq.size() >= 2); 72 | 73 | assert(set(seq.begin(), seq.end()).size() == seq.size()); 74 | 75 | auto expected_result = TestDataUniqueValues::get_expected_result(); 76 | auto result = minimum_index(seq); 77 | assert(result == expected_result); 78 | } 79 | 80 | void TestWithExactlyTwoDifferentMinimums() { 81 | auto seq = TestDataExactlyTwoDifferentMinimums::get_array(); 82 | assert(seq.size() >= 2); 83 | 84 | auto tmp = seq; 85 | sort(tmp.begin(), tmp.end()); 86 | assert(tmp[0] == tmp[1] and (tmp.size() == 2 or tmp[1] < tmp[2])); 87 | 88 | auto expected_result = TestDataExactlyTwoDifferentMinimums::get_expected_result(); 89 | auto result = minimum_index(seq); 90 | assert(result == expected_result); 91 | } 92 | 93 | int main() { 94 | TestWithEmptyArray(); 95 | TestWithUniqueValues(); 96 | TestWithExactlyTwoDifferentMinimums(); 97 | cout << "OK" << endl; 98 | return 0; 99 | } 100 | -------------------------------------------------------------------------------- /30DaysOfCode/Day28_RegExPatternsAndIntroToDatabase.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | vector split_string(string); 6 | 7 | bool endsWith(const std::string &mainStr, const std::string &toMatch) 8 | { 9 | if (mainStr.size() >= toMatch.size() && 10 | mainStr.compare(mainStr.size() - toMatch.size(), 11 | toMatch.size(), toMatch) == 0) 12 | return true; 13 | else 14 | return false; 15 | } 16 | 17 | int main() 18 | { 19 | int N; 20 | cin >> N; 21 | cin.ignore(numeric_limits::max(), '\n'); 22 | 23 | vector fName; 24 | for (int N_itr = 0; N_itr < N; N_itr++) { 25 | string firstNameEmailID_temp; 26 | getline(cin, firstNameEmailID_temp); 27 | vector firstNameEmailID = split_string(firstNameEmailID_temp); 28 | string firstName = firstNameEmailID[0]; 29 | string emailID = firstNameEmailID[1]; 30 | 31 | if (endsWith(emailID, "@gmail.com")) { 32 | fName.push_back(firstName); 33 | } 34 | } 35 | sort(fName.begin(), fName.end()); 36 | for (auto i: fName) { 37 | cout << i << endl; 38 | } 39 | 40 | return 0; 41 | } 42 | 43 | vector split_string(string input_string) { 44 | string::iterator new_end = unique(input_string.begin(), 45 | input_string.end(), 46 | [] (const char &x, const char &y) { 47 | return x == y and x == ' '; 48 | }); 49 | 50 | input_string.erase(new_end, input_string.end()); 51 | 52 | while (input_string[input_string.length() - 1] == ' ') { 53 | input_string.pop_back(); 54 | } 55 | 56 | vector splits; 57 | char delimiter = ' '; 58 | 59 | size_t i = 0; 60 | size_t pos = input_string.find(delimiter); 61 | 62 | while (pos != string::npos) { 63 | splits.push_back(input_string.substr(i, pos - i)); 64 | i = pos + 1; 65 | pos = input_string.find(delimiter, i); 66 | } 67 | splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); 68 | return splits; 69 | } 70 | -------------------------------------------------------------------------------- /30DaysOfCode/Day29_BitwiseAND.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | vector split_string(string); 7 | 8 | 9 | 10 | int main() 11 | { 12 | int t; 13 | cin >> t; 14 | cin.ignore(numeric_limits::max(), '\n'); 15 | 16 | for (int t_itr = 0; t_itr < t; t_itr++) { 17 | string nk_temp; 18 | getline(cin, nk_temp); 19 | vector nk = split_string(nk_temp); 20 | int n = stoi(nk[0]); 21 | int k = stoi(nk[1]); 22 | 23 | int mAnd = 0; 24 | int r; 25 | for (int i = 1; i < n + 1; i++) { 26 | for (int j = i + 1; j < n + 1 && j>i; j++) { 27 | r = i & j; 28 | if (mAnd < r && r < k) 29 | mAnd = r; 30 | } 31 | } 32 | cout << mAnd << endl; 33 | } 34 | 35 | return 0; 36 | } 37 | 38 | vector split_string(string input_string) { 39 | string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { 40 | return x == y and x == ' '; 41 | }); 42 | 43 | input_string.erase(new_end, input_string.end()); 44 | 45 | while (input_string[input_string.length() - 1] == ' ') { 46 | input_string.pop_back(); 47 | } 48 | 49 | vector splits; 50 | char delimiter = ' '; 51 | 52 | size_t i = 0; 53 | size_t pos = input_string.find(delimiter); 54 | 55 | while (pos != string::npos) { 56 | splits.push_back(input_string.substr(i, pos - i)); 57 | 58 | i = pos + 1; 59 | pos = input_string.find(delimiter, i); 60 | } 61 | 62 | splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); 63 | 64 | return splits; 65 | } 66 | -------------------------------------------------------------------------------- /Algorithms/Implementation/AppleAndOrange/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "strconv" 9 | "strings" 10 | ) 11 | 12 | func countApplesAndOranges(s, t, a, b int, apples, oranges []int) { 13 | var appleCount int 14 | for _, apple := range apples { 15 | distance := apple + a 16 | if distance >= s && distance <= t { 17 | appleCount++ 18 | } 19 | } 20 | 21 | var orangeCount int 22 | for _, orange := range oranges { 23 | distance := orange + b 24 | if distance >= s && distance <= t { 25 | orangeCount++ 26 | } 27 | } 28 | fmt.Println(appleCount) 29 | fmt.Println(orangeCount) 30 | } 31 | 32 | func readline(reader *bufio.Reader) []string { 33 | line, _, err := reader.ReadLine() 34 | if err != nil { 35 | log.Fatalln(err) 36 | } 37 | return strings.Split(string(line), " ") 38 | } 39 | 40 | func main() { 41 | var a, b, s, t, m, n int 42 | fmt.Scanln(&s, &t) 43 | fmt.Scanln(&a, &b) 44 | fmt.Scanln(&m, &n) 45 | 46 | reader := bufio.NewReaderSize(os.Stdin, 1024*1024) 47 | 48 | var apples []int 49 | appleStr := readline(reader) 50 | for i := 0; i < m; i++ { 51 | d, _ := strconv.Atoi(appleStr[i]) 52 | apples = append(apples, d) 53 | } 54 | 55 | var oranges []int 56 | orangeStr := readline(reader) 57 | for i := 0; i < n; i++ { 58 | d, _ := strconv.Atoi(orangeStr[i]) 59 | oranges = append(oranges, d) 60 | } 61 | 62 | countApplesAndOranges(s, t, a, b, apples, oranges) 63 | } 64 | -------------------------------------------------------------------------------- /Algorithms/Implementation/BirthDayChocolate/main.go: -------------------------------------------------------------------------------- 1 | // HackerRank Algorithm - Birthday Chocolate 2 | // https://www.hackerrank.com/challenges/the-birthday-bar/problem 3 | package main 4 | 5 | import ( 6 | "bufio" 7 | "fmt" 8 | "os" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | func birthday(s []int, d, m int) int { 14 | var count int 15 | chocoSquare := len(s) 16 | for i := 0; i < chocoSquare; i++ { 17 | sum := 0 18 | for j := i; j < i+m && j < chocoSquare; j++ { 19 | sum += s[j] 20 | } 21 | if sum == d { 22 | count++ 23 | } 24 | } 25 | return count 26 | } 27 | 28 | func main() { 29 | var n int 30 | fmt.Scanln(&n) 31 | 32 | scanner := bufio.NewScanner(os.Stdin) 33 | 34 | scanner.Scan() 35 | sStr := strings.Fields(scanner.Text()) 36 | 37 | var s []int 38 | for i := 0; i < n; i++ { 39 | d, _ := strconv.Atoi(sStr[i]) 40 | s = append(s, d) 41 | } 42 | 43 | scanner.Scan() 44 | dmStr := strings.Fields(scanner.Text()) 45 | d, _ := strconv.Atoi(dmStr[0]) 46 | m, _ := strconv.Atoi(dmStr[1]) 47 | 48 | fmt.Println(birthday(s, d, m)) 49 | } 50 | -------------------------------------------------------------------------------- /Algorithms/Implementation/BreakingTheRecords/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "strconv" 9 | "strings" 10 | ) 11 | 12 | func breakingTheRecords(scores []int) (int, int) { 13 | var minCount, maxCount int 14 | min := scores[0] 15 | max := scores[0] 16 | 17 | for _, score := range scores { 18 | if score > max { 19 | max = score 20 | maxCount++ 21 | } else if score < min { 22 | min = score 23 | minCount++ 24 | } 25 | } 26 | return maxCount, minCount 27 | } 28 | 29 | func readline(reader *bufio.Reader) []string { 30 | line, _, err := reader.ReadLine() 31 | if err != nil { 32 | log.Fatalln(err) 33 | } 34 | return strings.Split(string(line), " ") 35 | } 36 | 37 | func main() { 38 | var n int 39 | fmt.Scanln(&n) 40 | 41 | reader := bufio.NewReaderSize(os.Stdin, 1024*1024) 42 | var scores []int 43 | scoreStr := readline(reader) 44 | for i := 0; i < n; i++ { 45 | d, _ := strconv.Atoi(scoreStr[i]) 46 | scores = append(scores, d) 47 | } 48 | 49 | maxCount, minCount := breakingTheRecords(scores) 50 | fmt.Printf("%d %d", maxCount, minCount) 51 | } 52 | -------------------------------------------------------------------------------- /Algorithms/Implementation/DivisibleSumPairs/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | func divisibleSumPairs(n, k int, arr []int) int { 12 | var count int 13 | for i := 0; i < n; i++ { 14 | for j := i + 1; j < n; j++ { 15 | if (arr[i]+arr[j])%k == 0 { 16 | count++ 17 | } 18 | } 19 | } 20 | return count 21 | } 22 | 23 | func main() { 24 | var n, k int 25 | fmt.Scanln(&n, &k) 26 | 27 | scanner := bufio.NewScanner(os.Stdin) 28 | scanner.Scan() 29 | arrStr := strings.Fields(scanner.Text()) 30 | 31 | var arr []int 32 | for i := 0; i < n; i++ { 33 | d, _ := strconv.Atoi(arrStr[i]) 34 | arr = append(arr, d) 35 | } 36 | fmt.Println(divisibleSumPairs(n, k, arr)) 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/Implementation/GradingStudents/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func gradingStudents(grades []int) []int { 6 | var result []int 7 | for _, d := range grades { 8 | if d < 38 { 9 | result = append(result, d) 10 | continue 11 | } 12 | difference := 0 13 | value := d 14 | for value%5 != 0 { 15 | value++ 16 | difference++ 17 | } 18 | 19 | if difference < 3 { 20 | result = append(result, value) 21 | } else { 22 | result = append(result, d) 23 | } 24 | } 25 | return result 26 | } 27 | 28 | func main() { 29 | var length int 30 | fmt.Scanln(&length) 31 | 32 | var grades []int 33 | for i := 0; i < length; i++ { 34 | var temp int 35 | fmt.Scanln(&temp) 36 | grades = append(grades, temp) 37 | } 38 | for _, d := range gradingStudents(grades) { 39 | fmt.Println(d) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Implementation/Kangaroo/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func kangaroo(x1, v1, x2, v2 int) string { 6 | if v2 > v1 { 7 | return "NO" 8 | } else if v2 == v1 && x1 != x2 { 9 | return "NO" 10 | } 11 | 12 | for !(((x1 > x2) && (v1 > v2)) || ((x1 < x2) && (v1 < v2))) { 13 | x1 = x1 + v1 14 | x2 = x2 + v2 15 | if x1 == x2 { 16 | return "YES" 17 | } 18 | } 19 | return "NO" 20 | } 21 | 22 | func main() { 23 | var x1, v1, x2, v2 int 24 | fmt.Scanln(&x1, &v1, &x2, &v2) 25 | fmt.Println(kangaroo(x1, v1, x2, v2)) 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/Sorting/BigSorting/main.py: -------------------------------------------------------------------------------- 1 | def comparator(x, y): 2 | x_len = len(x) 3 | y_len = len(y) 4 | if x_len == y_len: 5 | return x < y 6 | return x_len < y_len 7 | 8 | def big_sorting(length, array): 9 | for s in sorted(array, cmp=comparator): 10 | print(s) 11 | 12 | def main(): 13 | n = int(input()) 14 | arr = [] 15 | for _ in range(n): 16 | arr.append(input()) 17 | big_sorting(n, arr) 18 | 19 | 20 | if __name__ == "__main__": 21 | main() 22 | -------------------------------------------------------------------------------- /Algorithms/Sorting/CorrectnessInvariant/main.py: -------------------------------------------------------------------------------- 1 | def insertion_sort(l): 2 | for i in range(1, len(l)): 3 | j = i 4 | key = l[i] 5 | while (j > 0) and (l[j-1] > key): 6 | l[j] = l[j-1] 7 | j -= 1 8 | l[j] = key 9 | 10 | m = int(input().strip()) 11 | ar = [int(i) for i in input().strip().split()] 12 | insertion_sort(ar) 13 | print(" ".join(map(str,ar))) 14 | 15 | -------------------------------------------------------------------------------- /Algorithms/Sorting/InsertionSort1/main.py: -------------------------------------------------------------------------------- 1 | def insertion_sort_1(n, arr): 2 | value = arr[-1] 3 | i = n-1 4 | while i > 0 and arr[i-1] > value: 5 | arr[i] = arr[i-1] 6 | print(' '.join([str(i) for i in arr])) 7 | i = i - 1 8 | arr[i] = value 9 | print(' '.join([str(i) for i in arr])) 10 | 11 | 12 | def main(): 13 | n = int(input()) 14 | arr = list(map(int, input().strip().split())) 15 | insertion_sort_1(n, arr) 16 | 17 | 18 | if __name__ == "__main__": 19 | main() 20 | -------------------------------------------------------------------------------- /Algorithms/Sorting/InsertionSort2/main.py: -------------------------------------------------------------------------------- 1 | def insertion_sort_2(length, array): 2 | for i in range(1, length): 3 | index = i 4 | value = array[i] 5 | 6 | while index > 0 and array[index-1] > value: 7 | array[index] = array[index-1] 8 | index -= 1 9 | 10 | array[index] = value 11 | print(' '.join([str(i) for i in array])) 12 | 13 | 14 | def main(): 15 | n = int(input()) 16 | arr = list(map(int, input().strip().split())) 17 | insertion_sort_2(n, arr) 18 | 19 | 20 | if __name__ == "__main__": 21 | main() 22 | -------------------------------------------------------------------------------- /Algorithms/Sorting/TutorialIntro/main.py: -------------------------------------------------------------------------------- 1 | def intro_tutorial(arr, value): 2 | for i, item in enumerate(arr): 3 | if value == item: 4 | return i 5 | 6 | 7 | def main(): 8 | value = int(input()) 9 | n = int(input()) 10 | arr = list(map(int, input().strip().split())) 11 | result = intro_tutorial(arr, value) 12 | print(result) 13 | 14 | 15 | if __name__ == "__main__": 16 | main() 17 | -------------------------------------------------------------------------------- /Algorithms/Warmup/AVeryBigSum/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | func aVeryBigSum(ar []int64) int64 { 12 | var result int64 13 | for _, d := range ar { 14 | result += d 15 | } 16 | return result 17 | } 18 | 19 | func main() { 20 | var length int 21 | fmt.Scanln(&length) 22 | 23 | scanner := bufio.NewScanner(os.Stdin) 24 | scanner.Scan() 25 | numStr := strings.Fields(scanner.Text()) 26 | var num []int64 27 | for i := 0; i < length; i++ { 28 | d, _ := strconv.ParseInt(numStr[i], 10, 64) 29 | num = append(num, d) 30 | } 31 | fmt.Println(aVeryBigSum(num)) 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/Warmup/BirthdayCakeCandles/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "strconv" 9 | "strings" 10 | ) 11 | 12 | func birthdayCakeCandles(arr []int) int { 13 | max := -999999 14 | count := 0 15 | for _, d := range arr { 16 | if max == d { 17 | count++ 18 | } else if max < d { 19 | max = d 20 | count = 1 21 | } 22 | } 23 | return count 24 | } 25 | 26 | func main() { 27 | var length int 28 | fmt.Scanln(&length) 29 | 30 | reader := bufio.NewReader(os.Stdin) 31 | 32 | var lineStr string 33 | line, isPrefix, err := reader.ReadLine() 34 | if err != nil { 35 | log.Fatalln(err) 36 | } 37 | lineStr += string(line) 38 | for isPrefix { 39 | line, isPrefix, err = reader.ReadLine() 40 | if err != nil { 41 | log.Fatalln(err) 42 | } 43 | lineStr += string(line) 44 | } 45 | 46 | var num []int 47 | numStr := strings.Split(lineStr, " ") 48 | for i := 0; i < length; i++ { 49 | d, _ := strconv.Atoi(numStr[i]) 50 | num = append(num, d) 51 | } 52 | 53 | fmt.Println(birthdayCakeCandles(num)) 54 | } 55 | -------------------------------------------------------------------------------- /Algorithms/Warmup/CompareTheTriplets/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | func compareTriplets(a, b []int) []int { 12 | result := make([]int, 2) 13 | for i := 0; i < 3; i++ { 14 | if a[i] > b[i] { 15 | result[0]++ 16 | } else if a[i] < b[i] { 17 | result[1]++ 18 | } 19 | } 20 | return result 21 | } 22 | 23 | func main() { 24 | scanner := bufio.NewScanner(os.Stdin) 25 | scanner.Scan() 26 | numStr1 := strings.Fields(scanner.Text()) 27 | var num1 []int 28 | for i := 0; i < 3; i++ { 29 | d, _ := strconv.Atoi(numStr1[i]) 30 | num1 = append(num1, d) 31 | } 32 | 33 | scanner.Scan() 34 | numStr2 := strings.Fields(scanner.Text()) 35 | var num2 []int 36 | for i := 0; i < 3; i++ { 37 | d, _ := strconv.Atoi(numStr2[i]) 38 | num2 = append(num2, d) 39 | } 40 | result := compareTriplets(num1, num2) 41 | fmt.Printf("%d %d", result[0], result[1]) 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/Warmup/DiagonalDifference/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | func main() { 12 | var length int 13 | fmt.Scanln(&length) 14 | scanner := bufio.NewScanner(os.Stdin) 15 | 16 | matrix := make([][]int, length) 17 | for i := 0; i < length; i++ { 18 | scanner.Scan() 19 | numStr := strings.Fields(scanner.Text()) 20 | 21 | var num []int 22 | for j := 0; j < length; j++ { 23 | d, _ := strconv.Atoi(numStr[j]) 24 | num = append(num, d) 25 | } 26 | matrix[i] = num 27 | } 28 | 29 | diagonal1 := 0 30 | for i := 0; i < length; i++ { 31 | diagonal1 += matrix[i][i] 32 | } 33 | 34 | diagonal2 := 0 35 | for i := 0; i < length; i++ { 36 | diagonal2 += matrix[i][length-1-i] 37 | } 38 | 39 | result := diagonal2 - diagonal1 40 | if result < 0 { 41 | result *= -1 42 | } 43 | 44 | fmt.Println(result) 45 | } 46 | -------------------------------------------------------------------------------- /Algorithms/Warmup/MinMaxSum/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | func minMaxSum(arr []int) { 12 | min := arr[0] 13 | max := arr[0] 14 | sum := 0 15 | for _, d := range arr { 16 | if min > d { 17 | min = d 18 | } 19 | if max < d { 20 | max = d 21 | } 22 | sum += d 23 | } 24 | fmt.Printf("%d %d", sum-max, sum-min) 25 | } 26 | 27 | func main() { 28 | scanner := bufio.NewScanner(os.Stdin) 29 | scanner.Scan() 30 | numStr := strings.Fields(scanner.Text()) 31 | 32 | var num []int 33 | for i := 0; i < 5; i++ { 34 | d, _ := strconv.Atoi(numStr[i]) 35 | num = append(num, d) 36 | } 37 | minMaxSum(num) 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/Warmup/PlusMinus/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | func plusMinus(arr []int) { 12 | length := float32(len(arr)) 13 | var positive, negative, zero float32 14 | for _, d := range arr { 15 | if d > 0 { 16 | positive++ 17 | } else if d < 0 { 18 | negative++ 19 | } else { 20 | zero++ 21 | } 22 | } 23 | fmt.Printf("%.6f\n", positive/length) 24 | fmt.Printf("%.6f\n", negative/length) 25 | fmt.Printf("%.6f\n", zero/length) 26 | } 27 | 28 | func main() { 29 | var length int 30 | fmt.Scanln(&length) 31 | 32 | scanner := bufio.NewScanner(os.Stdin) 33 | scanner.Scan() 34 | numStr := strings.Fields(scanner.Text()) 35 | 36 | var num []int 37 | for i := 0; i < length; i++ { 38 | d, _ := strconv.Atoi(numStr[i]) 39 | num = append(num, d) 40 | } 41 | plusMinus(num) 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/Warmup/SimpleArraySum/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | func simpleArraySum(ar []int) int { 12 | sum := 0 13 | for _, d := range ar { 14 | sum += d 15 | } 16 | return sum 17 | } 18 | 19 | func main() { 20 | var length int 21 | fmt.Scanln(&length) 22 | 23 | scanner := bufio.NewScanner(os.Stdin) 24 | scanner.Scan() 25 | numStr := strings.Fields(scanner.Text()) 26 | 27 | var num []int 28 | for i := 0; i < length; i++ { 29 | d, _ := strconv.Atoi(numStr[i]) 30 | num = append(num, d) 31 | } 32 | fmt.Println(simpleArraySum(num)) 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/Warmup/SolveMeFirst/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func solveMeFirst(a, b int) int { 6 | return a + b 7 | } 8 | 9 | func main() { 10 | var a, b int 11 | fmt.Scanf("%v\n%v", &a, &b) 12 | fmt.Println(solveMeFirst(a, b)) 13 | } 14 | -------------------------------------------------------------------------------- /Algorithms/Warmup/Staircase/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func staircase(size int) { 6 | for i := size; i > 0; i-- { 7 | spaceLen := i - 1 8 | for j := 0; j < size; j++ { 9 | if spaceLen > 0 { 10 | fmt.Printf(" ") 11 | spaceLen-- 12 | } else { 13 | fmt.Printf("#") 14 | } 15 | } 16 | fmt.Println() 17 | } 18 | } 19 | 20 | func main() { 21 | var size int 22 | fmt.Scanln(&size) 23 | 24 | staircase(size) 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/Warmup/TimeConversion/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | func timeConversion(s string) string { 12 | suffix := s[len(s)-2:] 13 | t := strings.Split(s, ":") 14 | t[2] = t[2][:2] 15 | 16 | if suffix == "PM" { 17 | if t[0] != "12" { 18 | a, _ := strconv.Atoi(t[0]) 19 | t[0] = strconv.Itoa(a + 12) 20 | } 21 | } else if suffix == "AM" && t[0] == "12" { 22 | t[0] = "00" 23 | } 24 | 25 | return strings.Join(t, ":") 26 | } 27 | 28 | func main() { 29 | scanner := bufio.NewScanner(os.Stdin) 30 | scanner.Scan() 31 | fmt.Println(timeConversion(scanner.Text())) 32 | } 33 | -------------------------------------------------------------------------------- /C++/1_Introduction/1_HelloWorld.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | std::cout << "Hello, World!"; 5 | return 0; 6 | } 7 | 8 | -------------------------------------------------------------------------------- /C++/1_Introduction/2_InputAndOutput.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int a, b, c; 6 | std::cin >> a >> b >> c; 7 | int sum = 0; 8 | sum = a + b + c; 9 | std::cout << sum << std::endl; 10 | } -------------------------------------------------------------------------------- /C++/1_Introduction/3_BasicDataTypes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int a; 6 | long b; 7 | char c; 8 | float d; 9 | double e; 10 | 11 | scanf("%d %ld %c %f %lf", &a, &b, &c, &d, &e); 12 | 13 | printf("%d\n", a); 14 | printf("%ld\n", b); 15 | printf("%c\n", c); 16 | printf("%f\n", d); 17 | printf("%lf", e); 18 | } -------------------------------------------------------------------------------- /C++/1_Introduction/4_ConditionalStatements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int n; 7 | std::cin >> n; 8 | 9 | std::string dataSet[] = { 10 | "Greater than 9", "one", "two", "three", "four", 11 | "five", "six", "seven", "eight", "nine"}; 12 | 13 | if (n > 9) { 14 | std::cout << dataSet[0]; 15 | } else { 16 | std::cout << dataSet[n]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /C++/1_Introduction/5_ForLoop.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int a, b; 7 | scanf("%d", &a); 8 | scanf("%d", &b); 9 | 10 | std::string dataSet[] = { 11 | "zero", "one", "two", "three", "four", 12 | "five", "six", "seven", "eight", "nine"}; 13 | 14 | for (int i = a; i <= b; i++) { 15 | if (i <= 9) { 16 | printf("%s\n", dataSet[i].c_str()); 17 | } else { 18 | if (i % 2) { 19 | printf("odd\n"); 20 | } else { 21 | printf("even\n"); 22 | } 23 | } 24 | } 25 | 26 | return 0; 27 | } -------------------------------------------------------------------------------- /C++/1_Introduction/6_Functions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int max_of_four(int a, int b, int c, int d) 4 | { 5 | int max = a; 6 | if (max < b) { max = b; } 7 | if (max < c) { max = c; } 8 | if (max < d) { max = d; } 9 | return max; 10 | } 11 | 12 | 13 | int main() 14 | { 15 | int a, b, c, d; 16 | scanf("%d %d %d %d", &a, &b, &c, &d); 17 | int ans = max_of_four(a, b, c, d); 18 | printf("%d", ans); 19 | return 0; 20 | } -------------------------------------------------------------------------------- /C++/1_Introduction/7_Pointer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void update(int *a,int *b) { 4 | int sum = *a + *b; 5 | int diff = *a - *b; 6 | if (diff < 0) diff *= -1; 7 | *a = sum; 8 | *b = diff; 9 | } 10 | 11 | int main() { 12 | int a, b; 13 | int *pa = &a, *pb = &b; 14 | 15 | scanf("%d %d", &a, &b); 16 | update(pa, pb); 17 | printf("%d\n%d", a, b); 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /C++/1_Introduction/8_ArrayIntroduction.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int n; 6 | std::cin >> n; 7 | int arr[n]; 8 | for (int i = 0; i < n; i++) { 9 | std::cin >> arr[i]; 10 | } 11 | 12 | for (int j = n-1; j >= 0; j--) { 13 | std::cout << arr[j] << " "; 14 | } 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /C++/1_Introduction/9_VariableSizedArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | int userSize, queries; 8 | std::cin >> userSize >> queries; 9 | std::cin.ignore(std::numeric_limits::max(), '\n'); 10 | 11 | int arraySize; 12 | std::vector< std::vector > a(userSize); 13 | for (int i = 0; i < userSize; i++) { 14 | std::cin >> arraySize; 15 | a[i] = std::vector(arraySize); 16 | for (int j = 0; j < arraySize; j++) { 17 | std::cin >> a[i][j]; 18 | } 19 | std::cin.ignore(std::numeric_limits::max(), '\n'); 20 | } 21 | 22 | for (int i = 0; i < queries; i++) { 23 | int m, n; 24 | std::cin >> m >> n; 25 | std::cin.ignore(std::numeric_limits::max(), '\n'); 26 | std::cout << a[m][n] << std::endl; 27 | } 28 | } -------------------------------------------------------------------------------- /C++/2_Strings/10_Strings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | std::string a, b; 7 | getline(std::cin, a); 8 | getline(std::cin, b); 9 | 10 | std::cout << a.size() << " " << b.size() << std::endl; 11 | std::cout << a + b << std::endl; 12 | char _a = a[0]; 13 | a[0] = b[0]; 14 | b[0] = _a; 15 | std::cout << a << " " << b << std::endl; 16 | } -------------------------------------------------------------------------------- /C++/2_Strings/11_StringStream.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | std::vector parseInts(std::string str) { 7 | std::vector number; 8 | std::stringstream ss(str); 9 | int num; 10 | while(ss >> num) { 11 | number.push_back(num); 12 | if (ss.peek() == ',') 13 | ss.ignore(); 14 | } 15 | return number; 16 | } 17 | 18 | int main() 19 | { 20 | std::string str; 21 | std::cin >> str; 22 | std::vector integers = parseInts(str); 23 | for(int i = 0; i < integers.size(); i++) { 24 | std::cout << integers[i] << "\n"; 25 | } 26 | return 0; 27 | } -------------------------------------------------------------------------------- /C++/2_Strings/12_AttributeParser.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/priyankchheda/cppalgo/995bc10bdbcd7187001243a1ddb1d80e3805871a/C++/2_Strings/12_AttributeParser.cpp -------------------------------------------------------------------------------- /C++/3_Classes/13_Structs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct Student 6 | { 7 | int age; 8 | string first_name; 9 | string last_name; 10 | int standard; 11 | }; 12 | 13 | int main() { 14 | Student st; 15 | 16 | cin >> st.age >> st.first_name >> st.last_name >> st.standard; 17 | cout << st.age << " " << st.first_name << " " << st.last_name << " " 18 | << st.standard; 19 | 20 | return 0; 21 | } 22 | 23 | -------------------------------------------------------------------------------- /C++/3_Classes/14_Class.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | /* 6 | Enter code for class Student here. 7 | Read statement for specification. 8 | */ 9 | class Student { 10 | private: 11 | int age; 12 | string first_name; 13 | string last_name; 14 | int standard; 15 | public: 16 | void set_age(int age) { this->age = age; } 17 | void set_standard(int standard) { this->standard = standard; } 18 | void set_first_name(string first_name) { this->first_name = first_name; } 19 | void set_last_name(string last_name) { this->last_name = last_name; } 20 | int get_age() { return this->age; } 21 | int get_standard() { return this->standard; } 22 | string get_first_name() { return this->first_name; } 23 | string get_last_name() { return this->last_name; } 24 | string to_string() { 25 | stringstream ss; 26 | ss << this->age << "," << this->first_name << "," << this->last_name << 27 | "," << this->standard; 28 | return ss.str(); 29 | } 30 | }; 31 | 32 | int main() { 33 | int age, standard; 34 | string first_name, last_name; 35 | 36 | cin >> age >> first_name >> last_name >> standard; 37 | 38 | Student st; 39 | st.set_age(age); 40 | st.set_standard(standard); 41 | st.set_first_name(first_name); 42 | st.set_last_name(last_name); 43 | 44 | cout << st.get_age() << "\n"; 45 | cout << st.get_last_name() << ", " << st.get_first_name() << "\n"; 46 | cout << st.get_standard() << "\n"; 47 | cout << "\n"; 48 | cout << st.to_string(); 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /C++/3_Classes/15_ClassesAndObjects.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | // Write your Student class here 10 | class Student { 11 | private: 12 | int scores[5]; 13 | public: 14 | void input(); 15 | int calculateTotalScore(); 16 | }; 17 | 18 | void Student::input() { 19 | for (int i = 0; i < 5; i++) 20 | cin >> scores[i]; 21 | } 22 | 23 | int Student::calculateTotalScore() { 24 | int totalScore = 0; 25 | for(int i = 0; i < 5; i++) 26 | totalScore += scores[i]; 27 | return totalScore; 28 | } 29 | 30 | int main() { 31 | int n; // number of students 32 | cin >> n; 33 | Student *s = new Student[n]; // an array of n students 34 | 35 | for(int i = 0; i < n; i++){ 36 | s[i].input(); 37 | } 38 | 39 | // calculate kristen's score 40 | int kristen_score = s[0].calculateTotalScore(); 41 | 42 | // determine how many students scored higher than kristen 43 | int count = 0; 44 | for(int i = 1; i < n; i++){ 45 | int total = s[i].calculateTotalScore(); 46 | if(total > kristen_score){ 47 | count++; 48 | } 49 | } 50 | 51 | // print result 52 | cout << count; 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /C++/3_Classes/16_BoxIt.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | //Implement the class Box 6 | //l,b,h are integers representing the dimensions of the box 7 | 8 | // The class should have the following functions : 9 | 10 | // Constructors: 11 | // Box(); 12 | // Box(int,int,int); 13 | // Box(Box); 14 | 15 | // int getLength(); // Return box's length 16 | // int getBreadth (); // Return box's breadth 17 | // int getHeight (); //Return box's height 18 | // long long CalculateVolume(); // Return the volume of the box 19 | 20 | //Overload operator < as specified 21 | //bool operator<(Box& b) 22 | 23 | //Overload operator << as specified 24 | //ostream& operator<<(ostream& out, Box& B) 25 | 26 | class Box { 27 | int l, b, h; 28 | public: 29 | // constructors 30 | Box() {l = 0; b = 0; h = 0; } 31 | Box(int _l, int _b, int _h) {l = _l; b = _b; h = _h; } 32 | Box(Box &box) { l = box.l; b = box.b; h = box.h; } 33 | 34 | // getters 35 | int getLength() { return l; } 36 | int getBreadth() { return b; } 37 | int getHeight() { return h; } 38 | 39 | long long CalculateVolume() { return (long long) l * b * h; } 40 | 41 | bool operator<(Box& b); 42 | friend ostream& operator << (ostream& out, Box& B); 43 | }; 44 | 45 | bool Box::operator < (Box &box) { 46 | if (l < box.l) return true; 47 | else if (b < box.b && l == box.l) return true; 48 | else if (h < box.h && b == box.b && l == box.l) return true; 49 | else return false; 50 | } 51 | 52 | ostream & operator << (ostream & out, Box& B) { 53 | out << B.l << " " << B.b << " " << B.h; 54 | return out; 55 | } 56 | 57 | void check2() { 58 | int n; 59 | cin >> n; 60 | Box temp; 61 | for (int i = 0; i < n; i++) 62 | { 63 | int type; 64 | cin >> type; 65 | if (type == 1) 66 | cout << temp << endl; 67 | 68 | if (type == 2) { 69 | int l, b, h; 70 | cin >> l >> b >> h; 71 | Box NewBox(l, b, h); 72 | temp = NewBox; 73 | cout << temp << endl; 74 | } 75 | 76 | if (type == 3) { 77 | int l, b, h; 78 | cin >> l >> b >> h; 79 | Box NewBox(l, b, h); 80 | if (NewBox < temp) 81 | cout << "Lesser\n"; 82 | else cout << "Greater\n"; 83 | } 84 | 85 | if (type == 4) 86 | cout << temp.CalculateVolume() << endl; 87 | 88 | if (type == 5) { 89 | Box NewBox(temp); 90 | cout << NewBox << endl; 91 | } 92 | } 93 | } 94 | 95 | int main() { 96 | check2(); 97 | } -------------------------------------------------------------------------------- /C++/4_STL/21_VectorSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | int n; 8 | std::cin >> n; 9 | std::vector v(n); 10 | for (int i = 0; i < n; i++) { 11 | std::cin >> v[i]; 12 | } 13 | sort(v.begin(), v.end()); 14 | for (int a: v) 15 | std::cout << a << " "; 16 | return 0; 17 | } -------------------------------------------------------------------------------- /C++/4_STL/22_VectorErase.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int n; 7 | std::cin >> n; 8 | std::vector vec(n); 9 | for (int i = 0; i < n; i++) 10 | std::cin >> vec[i]; 11 | 12 | int index_to_remove; 13 | std::cin >> index_to_remove; 14 | vec.erase(vec.begin()+index_to_remove-1); 15 | 16 | int start_index, end_index; 17 | std::cin >> start_index >> end_index; 18 | vec.erase(vec.begin()+start_index-1, vec.begin()+end_index-1); 19 | 20 | std::cout << vec.size() << "\n"; 21 | for (int a: vec) 22 | std::cout << a << " "; 23 | } -------------------------------------------------------------------------------- /C++/4_STL/23_LowerBound.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int n; 7 | std::cin >> n; 8 | std::vector vec(n); 9 | for (int i = 0; i < n; i++) 10 | std::cin >> vec[i]; 11 | 12 | int queries; 13 | std::cin >> queries; 14 | 15 | for (int i = 0; i < queries; i++) { 16 | int value; 17 | std::cin >> value; 18 | std::vector::iterator it; 19 | it = lower_bound(vec.begin(), vec.end(), value); 20 | if (*it == value) 21 | std::cout << "Yes "; 22 | else std::cout << "No "; 23 | std::cout << it - vec.begin() + 1 << "\n"; 24 | } 25 | } -------------------------------------------------------------------------------- /C++/4_STL/24_Sets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | std::set s; 7 | int queries; 8 | std::cin >> queries; 9 | for (int i = 0; i < queries; i++) { 10 | int condition, value; 11 | std::cin >> condition >> value; 12 | switch(condition) { 13 | case 1: 14 | s.insert(value); 15 | break; 16 | case 2: 17 | s.erase(value); 18 | break; 19 | case 3: 20 | std::set::iterator it = s.find(value); 21 | if (it == s.end()) std::cout << "No\n"; 22 | else std::cout << "Yes\n"; 23 | break; 24 | } 25 | } 26 | return 0; 27 | } -------------------------------------------------------------------------------- /C++/4_STL/25_Maps.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | std::map records; 7 | int queries; 8 | std::cin >> queries; 9 | for (int i = 0; i < queries; i++) { 10 | int condition, mark; 11 | std::string name; 12 | std::cin >> condition; 13 | switch (condition) { 14 | case 1: 15 | std::cin >> name >> mark; 16 | records[name] += mark; 17 | break; 18 | case 2: 19 | std::cin >> name; 20 | records.erase(name); 21 | break; 22 | case 3: 23 | std::cin >> name; 24 | std::cout << records[name] << "\n"; 25 | break; 26 | } 27 | } 28 | return 0; 29 | } -------------------------------------------------------------------------------- /C++/4_STL/26_PrettyPrint.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | int T; cin >> T; 7 | cout << setiosflags(ios::uppercase); 8 | cout << setw(0xf) << internal; 9 | while(T--) { 10 | double A; cin >> A; 11 | double B; cin >> B; 12 | double C; cin >> C; 13 | 14 | cout << hex << left << showbase << nouppercase; 15 | cout <<(long long)A << endl; 16 | 17 | cout << right << fixed << setprecision(2) << showpos << setfill('_') 18 | << setw(15); 19 | cout << B << endl; 20 | 21 | cout << scientific << uppercase << setprecision(9) << noshowpos; 22 | cout << C << endl; 23 | 24 | } 25 | return 0; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /C++/5_Inheritance/28_InheritanceIntroduction.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Triangle { 4 | public: 5 | void triangle() { 6 | std::cout << "I am a triangle\n"; 7 | } 8 | }; 9 | 10 | class Isosceles : public Triangle { 11 | public: 12 | void isosceles() { 13 | std::cout << "I am an isosceles triangle\n"; 14 | } 15 | //Write your code here. 16 | void description() { 17 | std::cout << "In an isosceles triangle two sides are equal\n"; 18 | } 19 | }; 20 | 21 | int main() { 22 | Isosceles isc; 23 | isc.isosceles(); 24 | isc.description(); 25 | isc.triangle(); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /C/1_Introduction/1_HelloWorld.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAX_LIMIT 100 4 | 5 | int main() 6 | { 7 | char str[MAX_LIMIT]; 8 | scanf("%[^\n]%*c", str); 9 | printf("Hello, World!\n"); 10 | printf("%s\n", str); 11 | return 0; 12 | } -------------------------------------------------------------------------------- /C/1_Introduction/2_PlayingWithCharacters.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAX_INT 100 4 | 5 | int main() 6 | { 7 | char ch; 8 | char word[MAX_INT]; 9 | char sentence[MAX_INT]; 10 | 11 | scanf("%c", &ch); 12 | scanf("%s", word); 13 | 14 | scanf("\n"); 15 | scanf("%[^\n]%*c", sentence); 16 | 17 | printf("%c\n", ch); 18 | printf("%s\n", word); 19 | printf("%s\n", sentence); 20 | return 0; 21 | } -------------------------------------------------------------------------------- /C/1_Introduction/3_SumAndDifferenceOfTwoNumbers.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int a, b; 6 | float c, d; 7 | 8 | scanf("%d %d", &a, &b); 9 | scanf("%f %f", &c, &d); 10 | 11 | printf("%d %d\n", a + b, a - b); 12 | printf("%.1f %.1f\n", c + d, c - d); 13 | 14 | return 0; 15 | } -------------------------------------------------------------------------------- /C/1_Introduction/4_FunctionsInC.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int maxOfFour(int a, int b, int c, int d) 4 | { 5 | int max = a; 6 | if (max < b) max = b; 7 | if (max < c) max = c; 8 | if (max < d) max = d; 9 | return max; 10 | } 11 | 12 | int main() 13 | { 14 | int a, b, c, d; 15 | scanf("%d %d %d %d", &a, &b, &c, &d); 16 | int ans = maxOfFour(a, b, c, d); 17 | printf("%d", ans); 18 | return 0; 19 | } 20 | 21 | -------------------------------------------------------------------------------- /C/1_Introduction/5_PointersInC.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void update(int *a, int *b) 4 | { 5 | int aTmp = *a; 6 | int bTmp = *b; 7 | 8 | *a = aTmp + bTmp; 9 | *b = aTmp - bTmp; 10 | if (*b < 0) *b *= -1; 11 | } 12 | 13 | int main() 14 | { 15 | int a, b; 16 | scanf("%d %d", &a, &b); 17 | 18 | update(&a, &b); 19 | printf("%d\n%d\n", a, b); 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /C/2_ConditionalsAndLoops/10_PrintingPattern.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int n; 6 | scanf("%d", &n); 7 | int len = n * 2 - 1; 8 | for (int i = 0; i < len; i++) { 9 | for (int j = 0; j < len; j++) { 10 | int min = i < j ? i : j; 11 | min = min < len-i ? min : len-i-1; 12 | min = min < len-j-1 ? min : len-j-1; 13 | printf("%d ", n-min); 14 | } 15 | printf("\n"); 16 | } 17 | return 0; 18 | } -------------------------------------------------------------------------------- /C/2_ConditionalsAndLoops/6_ConditionalStatementsInC.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int number; 6 | scanf("%d", &number); 7 | 8 | if (number == 1) printf("one\n"); 9 | else if (number == 2) printf("two\n"); 10 | else if (number == 3) printf("three\n"); 11 | else if (number == 4) printf("four\n"); 12 | else if (number == 5) printf("five\n"); 13 | else if (number == 6) printf("six\n"); 14 | else if (number == 7) printf("seven\n"); 15 | else if (number == 8) printf("eight\n"); 16 | else if (number == 9) printf("nine\n"); 17 | else printf("Greater than 9\n"); 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /C/2_ConditionalsAndLoops/7_ForLoopInC.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int a, b; 6 | scanf("%d\n%d", &a, &b); 7 | 8 | for (int i = a; i < b + 1; i++) { 9 | if (i == 1) printf("one\n"); 10 | else if (i == 2) printf("two\n"); 11 | else if (i == 3) printf("three\n"); 12 | else if (i == 4) printf("four\n"); 13 | else if (i == 5) printf("five\n"); 14 | else if (i == 6) printf("six\n"); 15 | else if (i == 7) printf("seven\n"); 16 | else if (i == 8) printf("eight\n"); 17 | else if (i == 9) printf("nine\n"); 18 | else if (i % 2) printf("odd\n"); 19 | else printf("even\n"); 20 | } 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /C/2_ConditionalsAndLoops/8_SumOfDigitsOfAFiveDigitNumber.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int a; 6 | scanf("%d", &a); 7 | 8 | int sum = 0; 9 | while (a) { 10 | sum += a % 10; 11 | a /= 10; 12 | } 13 | 14 | printf("%d\n", sum); 15 | 16 | return 0; 17 | } -------------------------------------------------------------------------------- /C/2_ConditionalsAndLoops/9_BitwiseOperators.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int a, b; 6 | scanf("%d %d", &a, &b); 7 | 8 | int or, and, xor; 9 | int mOr = 0; 10 | int mAnd = 0; 11 | int mXor = 0; 12 | 13 | for (int i = 1; i < a + 1; i++) { 14 | for (int j = i + 1; j < a + 1 && j>i; j++) { 15 | 16 | or = i | j; 17 | if (mOr < or && or < b) mOr = or; 18 | 19 | and = i & j; 20 | if (mAnd < and && and < b) mAnd = and; 21 | 22 | 23 | xor = i ^ j; 24 | if (mXor < xor && xor < b) mXor = xor; 25 | } 26 | } 27 | 28 | printf("%d\n", mAnd); 29 | printf("%d\n", mOr); 30 | printf("%d\n", mXor); 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /C/3_ArraysAndStrings/11_1DArraysInC.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int size; 7 | scanf("%d", &size); 8 | int *arr = (int*)malloc(size * sizeof(int)); 9 | for (int i = 0; i < size; i++) { 10 | scanf("%d", arr + i); 11 | } 12 | 13 | int sum = 0; 14 | for (int i = 0; i < size; i++) { 15 | sum += arr[i]; 16 | } 17 | 18 | printf("%d\n", sum); 19 | free(arr); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /C/3_ArraysAndStrings/12_ArrayReversal.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int num, *arr, i; 7 | scanf("%d", &num); 8 | arr = (int*) malloc(num * sizeof(int)); 9 | for(i = 0; i < num; i++) { 10 | scanf("%d", arr + i); 11 | } 12 | 13 | for (int i = 0; i < num/2; i++) { 14 | int temp = arr[i]; 15 | arr[i] = arr[num - 1 - i]; 16 | arr[num - 1 - i] = temp; 17 | } 18 | 19 | for(i = 0; i < num; i++) 20 | printf("%d ", *(arr + i)); 21 | 22 | free(arr); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /C/3_ArraysAndStrings/13_PrintingTokens.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() { 6 | 7 | char *s; 8 | s = malloc(1024 * sizeof(char)); 9 | scanf("%[^\n]", s); 10 | s = realloc(s, strlen(s) + 1); 11 | 12 | int i = 0; 13 | while (s[i] != '\0') { 14 | printf("%c", s[i]); 15 | if (s[i] == ' ') printf("\n"); 16 | i++; 17 | } 18 | 19 | free(s); 20 | return 0; 21 | } 22 | 23 | -------------------------------------------------------------------------------- /C/3_ArraysAndStrings/14_DigitFrequency.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | char str[1024]; 6 | int count[10]; 7 | for (int i = 0; i < 10; i++) { 8 | count[i] = 0; 9 | } 10 | 11 | scanf("%s", str); 12 | 13 | int i = 0; 14 | while (str[i] != '\0') { 15 | if (str[i] >= '0' && str[i] <= '9') { 16 | int k = str[i] - '0'; 17 | count[k]++; 18 | } 19 | i++; 20 | } 21 | 22 | for (int i = 0; i < 10; i++) { 23 | printf("%d ", count[i]); 24 | } 25 | 26 | return 0; 27 | } -------------------------------------------------------------------------------- /C/3_ArraysAndStrings/15_DynamicArrayInC.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* 5 | * This stores the total number of books in each shelf. 6 | */ 7 | int* total_number_of_books; 8 | 9 | /* 10 | * This stores the total number of pages in each book of each shelf. 11 | * The rows represent the shelves and the columns represent the books. 12 | */ 13 | int** total_number_of_pages; 14 | 15 | int main() 16 | { 17 | int total_number_of_shelves; 18 | scanf("%d", &total_number_of_shelves); 19 | 20 | total_number_of_books=(int*)malloc(sizeof(int)*total_number_of_shelves); 21 | total_number_of_pages=(int**)malloc(sizeof(int*)*total_number_of_shelves); 22 | for(int i = 0; i < total_number_of_shelves; i++){ 23 | total_number_of_books[i] = 0; 24 | total_number_of_pages[i] = (int*)malloc(sizeof(int)); 25 | } 26 | int total_number_of_queries; 27 | scanf("%d", &total_number_of_queries); 28 | 29 | while (total_number_of_queries--) { 30 | int type_of_query; 31 | scanf("%d", &type_of_query); 32 | 33 | if (type_of_query == 1) { 34 | /* 35 | * Process the query of first type here. 36 | */ 37 | int x, y; 38 | scanf("%d %d", &x, &y); 39 | *(total_number_of_books+x) += 1; 40 | *(total_number_of_pages+x) = realloc(*(total_number_of_pages+x), *(total_number_of_books + x) * sizeof(int)); 41 | *(*(total_number_of_pages + x) + *(total_number_of_books + x) - 1) = y; 42 | 43 | } else if (type_of_query == 2) { 44 | int x, y; 45 | scanf("%d %d", &x, &y); 46 | printf("%d\n", *(*(total_number_of_pages + x) + y)); 47 | } else { 48 | int x; 49 | scanf("%d", &x); 50 | printf("%d\n", *(total_number_of_books + x)); 51 | } 52 | } 53 | 54 | if (total_number_of_books) { 55 | free(total_number_of_books); 56 | } 57 | 58 | for (int i = 0; i < total_number_of_shelves; i++) { 59 | if (*(total_number_of_pages + i)) { 60 | free(*(total_number_of_pages + i)); 61 | } 62 | } 63 | 64 | if (total_number_of_pages) { 65 | free(total_number_of_pages); 66 | } 67 | 68 | return 0; 69 | } -------------------------------------------------------------------------------- /C/4_Functions/16_CalculateTheNthTerm.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int find_nth_term(int n, int a, int b, int c) { 4 | if (n == 1) return a; 5 | else if (n == 2) return b; 6 | else if (n == 3) return c; 7 | 8 | return find_nth_term(n-1, a, b, c) + find_nth_term(n-2, a, b, c) + 9 | find_nth_term(n-3, a, b, c); 10 | 11 | } 12 | 13 | int main() { 14 | int n, a, b, c; 15 | 16 | scanf("%d %d %d %d", &n, &a, &b, &c); 17 | int ans = find_nth_term(n, a, b, c); 18 | 19 | printf("%d", ans); 20 | return 0; 21 | } -------------------------------------------------------------------------------- /C/4_Functions/17_StudentsMarksSum.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int marks_summation(int* marks, int number_of_students, char gender) { 5 | int sum = 0; 6 | int i = 0; 7 | if (gender == 'g') i = 1; 8 | for (; i < number_of_students; i += 2) { 9 | sum += marks[i]; 10 | } 11 | return sum; 12 | } 13 | 14 | int main() { 15 | int number_of_students; 16 | char gender; 17 | int sum; 18 | 19 | scanf("%d", &number_of_students); 20 | int *marks = (int *) malloc(number_of_students * sizeof (int)); 21 | 22 | for (int student = 0; student < number_of_students; student++) { 23 | scanf("%d", (marks + student)); 24 | } 25 | 26 | scanf(" %c", &gender); 27 | sum = marks_summation(marks, number_of_students, gender); 28 | printf("%d", sum); 29 | free(marks); 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /C/4_Functions/18_SortingArrayOfStrings.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int lexicographic_sort(const char* a, const char* b) { 6 | return strcmp(a, b); 7 | } 8 | 9 | int lexicographic_sort_reverse(const char* a, const char* b) { 10 | return strcmp(b, a); 11 | } 12 | 13 | int distinct_chars(const char *a) 14 | { 15 | int dist = 0; 16 | 17 | while (*a != '\0') { 18 | if (!strchr(a + 1, *a)) 19 | dist++; 20 | a++; 21 | } 22 | return dist; 23 | } 24 | 25 | int sort_by_number_of_distinct_characters(const char* a, const char* b) { 26 | int res = distinct_chars(a) - distinct_chars(b); 27 | return (res) ? res : lexicographic_sort(a, b); 28 | } 29 | 30 | int sort_by_length(const char* a, const char* b) 31 | { 32 | int res = strlen(a) - strlen(b); 33 | return (res) ? res : strcmp(a, b);; 34 | } 35 | 36 | 37 | void string_sort(char** arr, 38 | const int len, 39 | int (*cmp_func)(const char* a, const char* b)) 40 | { 41 | for (int i = 0; i < len; i++) { 42 | int min_element_index = i; 43 | for (int j = i + 1; j < len; j++) { 44 | if (cmp_func(arr[j], arr[min_element_index]) < 0) 45 | min_element_index = j; 46 | } 47 | char *tmp = arr[i]; 48 | arr[i] = arr[min_element_index]; 49 | arr[min_element_index] = tmp; 50 | } 51 | } 52 | 53 | 54 | int main() 55 | { 56 | 57 | int n; 58 | scanf("%d", &n); 59 | 60 | char** arr; 61 | arr = (char**)malloc(n * sizeof(char*)); 62 | 63 | for(int i = 0; i < n; i++){ 64 | *(arr + i) = malloc(1024 * sizeof(char)); 65 | scanf("%s", *(arr + i)); 66 | *(arr + i) = realloc(*(arr + i), strlen(*(arr + i)) + 1); 67 | } 68 | 69 | string_sort(arr, n, lexicographic_sort); 70 | for(int i = 0; i < n; i++) 71 | printf("%s\n", arr[i]); 72 | printf("\n"); 73 | 74 | string_sort(arr, n, lexicographic_sort_reverse); 75 | for(int i = 0; i < n; i++) 76 | printf("%s\n", arr[i]); 77 | printf("\n"); 78 | 79 | string_sort(arr, n, sort_by_length); 80 | for(int i = 0; i < n; i++) 81 | printf("%s\n", arr[i]); 82 | printf("\n"); 83 | 84 | string_sort(arr, n, sort_by_number_of_distinct_characters); 85 | for(int i = 0; i < n; i++) 86 | printf("%s\n", arr[i]); 87 | printf("\n"); 88 | } -------------------------------------------------------------------------------- /C/4_Functions/19_PermutationsOfStrings.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int next_permutation(int n, char **s) 6 | { 7 | int i = n-1; 8 | while(i > 0 && strcmp(s[i-1], s[i]) >= 0) 9 | i--; 10 | if (i <= 0) return 0; 11 | 12 | int j = n-1; 13 | while(strcmp(s[i-1], s[j]) >= 0) 14 | j--; 15 | char *tmp = s[i-1]; 16 | s[i-1] = s[j]; 17 | s[j] = tmp; 18 | 19 | j = n - 1; 20 | while(i < j) { 21 | tmp = s[i]; 22 | s[i] = s[j]; 23 | s[j] = tmp; 24 | i++; 25 | j--; 26 | } 27 | return 1; 28 | } 29 | 30 | int main() 31 | { 32 | char **s; 33 | int n; 34 | scanf("%d", &n); 35 | s = calloc(n, sizeof(char*)); 36 | for (int i = 0; i < n; i++) 37 | { 38 | s[i] = calloc(11, sizeof(char)); 39 | scanf("%s", s[i]); 40 | } 41 | do 42 | { 43 | for (int i = 0; i < n; i++) 44 | printf("%s%c", s[i], i == n - 1 ? '\n' : ' '); 45 | } while (next_permutation(n, s)); 46 | for (int i = 0; i < n; i++) 47 | free(s[i]); 48 | free(s); 49 | return 0; 50 | } -------------------------------------------------------------------------------- /C/4_Functions/20_VariadicFunctionsinC.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define MIN_ELEMENT 1 7 | #define MAX_ELEMENT 1000000 8 | 9 | int sum (int count,...) { 10 | int sum=0; 11 | va_list values; 12 | va_start(values,count); 13 | for(int i=0;itest){ 27 | min=test; 28 | } 29 | } 30 | va_end(values); 31 | return min; 32 | } 33 | 34 | int max(int count,...) { 35 | int max=MIN_ELEMENT,test; 36 | va_list values; 37 | va_start(values,count); 38 | for(int i=0;i maximum_element) { 78 | return 0; 79 | } 80 | 81 | expected_elements_sum += elements[i]; 82 | } 83 | 84 | return elements_sum == expected_elements_sum; 85 | } 86 | 87 | int test_implementations_by_sending_five_elements() { 88 | srand(time(NULL)); 89 | 90 | int elements[5]; 91 | 92 | elements[0] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 93 | elements[1] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 94 | elements[2] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 95 | elements[3] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 96 | elements[4] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 97 | 98 | fprintf(stderr, "Sending following five elements:\n"); 99 | for (int i = 0; i < 5; i++) { 100 | fprintf(stderr, "%d\n", elements[i]); 101 | } 102 | 103 | int elements_sum = sum(5, elements[0], elements[1], elements[2], elements[3], elements[4]); 104 | int minimum_element = min(5, elements[0], elements[1], elements[2], elements[3], elements[4]); 105 | int maximum_element = max(5, elements[0], elements[1], elements[2], elements[3], elements[4]); 106 | 107 | fprintf(stderr, "Your output is:\n"); 108 | fprintf(stderr, "Elements sum is %d\n", elements_sum); 109 | fprintf(stderr, "Minimum element is %d\n", minimum_element); 110 | fprintf(stderr, "Maximum element is %d\n\n", maximum_element); 111 | 112 | int expected_elements_sum = 0; 113 | for (int i = 0; i < 5; i++) { 114 | if (elements[i] < minimum_element) { 115 | return 0; 116 | } 117 | 118 | if (elements[i] > maximum_element) { 119 | return 0; 120 | } 121 | 122 | expected_elements_sum += elements[i]; 123 | } 124 | 125 | return elements_sum == expected_elements_sum; 126 | } 127 | 128 | int test_implementations_by_sending_ten_elements() { 129 | srand(time(NULL)); 130 | 131 | int elements[10]; 132 | 133 | elements[0] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 134 | elements[1] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 135 | elements[2] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 136 | elements[3] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 137 | elements[4] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 138 | elements[5] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 139 | elements[6] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 140 | elements[7] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 141 | elements[8] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 142 | elements[9] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; 143 | 144 | fprintf(stderr, "Sending following ten elements:\n"); 145 | for (int i = 0; i < 10; i++) { 146 | fprintf(stderr, "%d\n", elements[i]); 147 | } 148 | 149 | int elements_sum = sum(10, elements[0], elements[1], elements[2], elements[3], elements[4], 150 | elements[5], elements[6], elements[7], elements[8], elements[9]); 151 | int minimum_element = min(10, elements[0], elements[1], elements[2], elements[3], elements[4], 152 | elements[5], elements[6], elements[7], elements[8], elements[9]); 153 | int maximum_element = max(10, elements[0], elements[1], elements[2], elements[3], elements[4], 154 | elements[5], elements[6], elements[7], elements[8], elements[9]); 155 | 156 | fprintf(stderr, "Your output is:\n"); 157 | fprintf(stderr, "Elements sum is %d\n", elements_sum); 158 | fprintf(stderr, "Minimum element is %d\n", minimum_element); 159 | fprintf(stderr, "Maximum element is %d\n\n", maximum_element); 160 | 161 | int expected_elements_sum = 0; 162 | for (int i = 0; i < 10; i++) { 163 | if (elements[i] < minimum_element) { 164 | return 0; 165 | } 166 | 167 | if (elements[i] > maximum_element) { 168 | return 0; 169 | } 170 | 171 | expected_elements_sum += elements[i]; 172 | } 173 | 174 | return elements_sum == expected_elements_sum; 175 | } 176 | 177 | int main () 178 | { 179 | int number_of_test_cases; 180 | scanf("%d", &number_of_test_cases); 181 | 182 | while (number_of_test_cases--) { 183 | if (test_implementations_by_sending_three_elements()) { 184 | printf("Correct Answer\n"); 185 | } else { 186 | printf("Wrong Answer\n"); 187 | } 188 | 189 | if (test_implementations_by_sending_five_elements()) { 190 | printf("Correct Answer\n"); 191 | } else { 192 | printf("Wrong Answer\n"); 193 | } 194 | 195 | if (test_implementations_by_sending_ten_elements()) { 196 | printf("Correct Answer\n"); 197 | } else { 198 | printf("Wrong Answer\n"); 199 | } 200 | } 201 | 202 | return 0; 203 | } -------------------------------------------------------------------------------- /C/4_Functions/21_QueryingTheDocument.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #define MAX_CHARACTERS 1005 6 | #define MAX_PARAGRAPHS 5 7 | 8 | char* kth_word_in_mth_sentence_of_nth_paragraph(char**** document, int k, int m, int n) { 9 | return document[n-1][m-1][k-1]; 10 | } 11 | 12 | char** kth_sentence_in_mth_paragraph(char**** document, int k, int m) { 13 | return document[m-1][k-1]; 14 | } 15 | 16 | char*** kth_paragraph(char**** document, int k) { 17 | return document[k-1]; 18 | } 19 | 20 | char** split_string(char* text, char delim) { 21 | assert(text != NULL); 22 | char** result = malloc(1*sizeof(char*)); 23 | int size = 1; 24 | 25 | char* temp = strtok(text, &delim); 26 | *result = temp; 27 | 28 | while(temp != NULL) { 29 | size++; 30 | result = realloc(result,size*sizeof(char*)); 31 | temp = strtok(NULL, &delim); 32 | result[size-1] = temp; 33 | } 34 | return result; 35 | } 36 | 37 | char**** get_document(char* text) { 38 | assert(text != NULL); 39 | 40 | // split text by '\n' and count number of paragraphs 41 | char** paragraphs = split_string(text, '\n'); 42 | int npar = 0; 43 | while (paragraphs[npar] != NULL) { 44 | npar++; 45 | } 46 | 47 | char**** doc = malloc((npar+1)*sizeof(char***)); 48 | // set last position to NULL for the user 49 | // to know when the array ends. 50 | doc[npar] = NULL; 51 | 52 | int i = 0; 53 | while (paragraphs[i] != NULL) { 54 | 55 | // split sentences of paragraph by '.' and count number of sentences 56 | char** sentences = split_string(paragraphs[i], '.'); 57 | int nsen = 0; 58 | while(sentences[nsen] != NULL) { 59 | nsen++; 60 | } 61 | 62 | doc[i] = malloc((nsen+1)*sizeof(char**)); 63 | // set last position to NULL for the user 64 | // to know when the array ends. 65 | doc[i][nsen] = NULL; 66 | 67 | int j = 0; 68 | while (sentences[j] != NULL) { 69 | 70 | // remember that doc[0][0] means: paragraph #0, 71 | // sentence #0 and should act like a pointer to 72 | // the first element of an array of words (strings) 73 | 74 | // split string by ' ' and associate doc[i][j] 75 | // with the array of strings representing words 76 | // that is returned by split_string. 77 | doc[i][j] = split_string(sentences[j], ' '); 78 | j++; 79 | } 80 | i++; 81 | } 82 | 83 | return doc; 84 | } 85 | 86 | 87 | char* get_input_text() { 88 | int paragraph_count; 89 | scanf("%d", ¶graph_count); 90 | 91 | char p[MAX_PARAGRAPHS][MAX_CHARACTERS], doc[MAX_CHARACTERS]; 92 | memset(doc, 0, sizeof(doc)); 93 | getchar(); 94 | for (int i = 0; i < paragraph_count; i++) { 95 | scanf("%[^\n]%*c", p[i]); 96 | strcat(doc, p[i]); 97 | if (i != paragraph_count - 1) 98 | strcat(doc, "\n"); 99 | } 100 | 101 | char* returnDoc = (char*)malloc((strlen (doc)+1) * (sizeof(char))); 102 | strcpy(returnDoc, doc); 103 | return returnDoc; 104 | } 105 | 106 | void print_word(char* word) { 107 | printf("%s", word); 108 | } 109 | 110 | void print_sentence(char** sentence) { 111 | int word_count; 112 | scanf("%d", &word_count); 113 | for(int i = 0; i < word_count; i++){ 114 | printf("%s", sentence[i]); 115 | if( i != word_count - 1) 116 | printf(" "); 117 | } 118 | } 119 | 120 | void print_paragraph(char*** paragraph) { 121 | int sentence_count; 122 | scanf("%d", &sentence_count); 123 | for (int i = 0; i < sentence_count; i++) { 124 | print_sentence(*(paragraph + i)); 125 | printf("."); 126 | } 127 | } 128 | 129 | int main() 130 | { 131 | char* text = get_input_text(); 132 | char**** document = get_document(text); 133 | 134 | int q; 135 | scanf("%d", &q); 136 | 137 | while (q--) { 138 | int type; 139 | scanf("%d", &type); 140 | 141 | if (type == 3){ 142 | int k, m, n; 143 | scanf("%d %d %d", &k, &m, &n); 144 | char* word = kth_word_in_mth_sentence_of_nth_paragraph(document, k, m, n); 145 | print_word(word); 146 | } 147 | 148 | else if (type == 2){ 149 | int k, m; 150 | scanf("%d %d", &k, &m); 151 | char** sentence = kth_sentence_in_mth_paragraph(document, k, m); 152 | print_sentence(sentence); 153 | } 154 | 155 | else{ 156 | int k; 157 | scanf("%d", &k); 158 | char*** paragraph = kth_paragraph(document, k); 159 | print_paragraph(paragraph); 160 | } 161 | printf("\n"); 162 | } 163 | } -------------------------------------------------------------------------------- /C/5_StuctsAndEnums/22_BoxesThroughATunnel.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define MAX_HEIGHT 41 4 | 5 | struct box 6 | { 7 | int length; 8 | int width; 9 | int height; 10 | }; 11 | 12 | typedef struct box box; 13 | 14 | int get_volume(box b) { 15 | return b.length * b.width * b.height; 16 | } 17 | 18 | int is_lower_than_max_height(box b) { 19 | if (b.height < MAX_HEIGHT) return 1; 20 | else return 0; 21 | } 22 | 23 | int main() 24 | { 25 | int n; 26 | scanf("%d", &n); 27 | box *boxes = malloc(n * sizeof(box)); 28 | for (int i = 0; i < n; i++) { 29 | scanf("%d%d%d", &boxes[i].length, &boxes[i].width, &boxes[i].height); 30 | } 31 | for (int i = 0; i < n; i++) { 32 | if (is_lower_than_max_height(boxes[i])) { 33 | printf("%d\n", get_volume(boxes[i])); 34 | } 35 | } 36 | return 0; 37 | } -------------------------------------------------------------------------------- /C/5_StuctsAndEnums/23_SmallTrianglesLargeTriangles.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct triangle 6 | { 7 | int a; 8 | int b; 9 | int c; 10 | }; 11 | 12 | typedef struct triangle triangle; 13 | void sort_by_area(triangle* tr, int n) { 14 | for (int i = 0; i < n; i++) { 15 | int min_index = i; 16 | 17 | } 18 | } 19 | 20 | int main() 21 | { 22 | int n; 23 | scanf("%d", &n); 24 | triangle *tr = malloc(n * sizeof(triangle)); 25 | for (int i = 0; i < n; i++) { 26 | scanf("%d%d%d", &tr[i].a, &tr[i].b, &tr[i].c); 27 | } 28 | sort_by_area(tr, n); 29 | for (int i = 0; i < n; i++) { 30 | printf("%d %d %d\n", tr[i].a, tr[i].b, tr[i].c); 31 | } 32 | return 0; 33 | } -------------------------------------------------------------------------------- /C/5_StuctsAndEnums/24_PostTransition.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define MAX_STRING_LENGTH 6 4 | 5 | struct package 6 | { 7 | char* id; 8 | int weight; 9 | }; 10 | 11 | typedef struct package package; 12 | 13 | struct post_office 14 | { 15 | int min_weight; 16 | int max_weight; 17 | package* packages; 18 | int packages_count; 19 | }; 20 | 21 | typedef struct post_office post_office; 22 | 23 | struct town 24 | { 25 | char* name; 26 | post_office* offices; 27 | int offices_count; 28 | }; 29 | 30 | typedef struct town town; 31 | 32 | 33 | 34 | void print_all_packages(town t) { 35 | printf("%s:\n", t.name); 36 | for(int i=0; ioffices[source_office_index].packages_count; i++){ 48 | mxg=source->offices[source_office_index].packages[i].weight; 49 | min=target->offices[target_office_index].min_weight; 50 | max=target->offices[target_office_index].max_weight; 51 | 52 | if((min<=mxg)&&(mxg<=max)){ 53 | count=target->offices[target_office_index].packages_count; 54 | target->offices[target_office_index].packages=realloc(target->offices[target_office_index].packages, sizeof(package) * (count+1)); 55 | 56 | target->offices[target_office_index].packages[count]=source->offices[source_office_index].packages[i]; 57 | 58 | count=source->offices[source_office_index].packages_count; 59 | k=i; 60 | 61 | while(koffices[source_office_index].packages[k]; 63 | source->offices[source_office_index].packages[k]=source->offices[source_office_index].packages[k+1]; 64 | source->offices[source_office_index].packages[k+1]=temp; 65 | k++; 66 | } 67 | 68 | source->offices[source_office_index].packages= 69 | realloc(source->offices[source_office_index].packages, sizeof(package) * (count-1)); 70 | 71 | target->offices[target_office_index].packages_count++; 72 | source->offices[source_office_index].packages_count--; 73 | i--; 74 | } 75 | } 76 | } 77 | 78 | town town_with_most_packages(town* towns, int towns_count) { 79 | int max=-1, sum, r; 80 | while(--towns_count>-1){ 81 | sum=0; 82 | for(int i=0; imax){max=sum;r=towns_count;} 86 | } 87 | 88 | return towns[r]; 89 | } 90 | 91 | town* find_town(town* towns, int towns_count, char* name) { 92 | int i; 93 | while(--towns_count>-1){ 94 | if(strcmp(name, towns[towns_count].name)==0){ 95 | i=towns_count; 96 | } 97 | } 98 | return towns+i; 99 | } 100 | 101 | int main() 102 | { 103 | int towns_count; 104 | scanf("%d", &towns_count); 105 | town* towns = malloc(sizeof(town)*towns_count); 106 | for (int i = 0; i < towns_count; i++) { 107 | towns[i].name = malloc(sizeof(char) * MAX_STRING_LENGTH); 108 | scanf("%s", towns[i].name); 109 | scanf("%d", &towns[i].offices_count); 110 | towns[i].offices = malloc(sizeof(post_office)*towns[i].offices_count); 111 | for (int j = 0; j < towns[i].offices_count; j++) { 112 | scanf("%d%d%d", &towns[i].offices[j].packages_count, &towns[i].offices[j].min_weight, &towns[i].offices[j].max_weight); 113 | towns[i].offices[j].packages = malloc(sizeof(package)*towns[i].offices[j].packages_count); 114 | for (int k = 0; k < towns[i].offices[j].packages_count; k++) { 115 | towns[i].offices[j].packages[k].id = malloc(sizeof(char) * MAX_STRING_LENGTH); 116 | scanf("%s", towns[i].offices[j].packages[k].id); 117 | scanf("%d", &towns[i].offices[j].packages[k].weight); 118 | } 119 | } 120 | } 121 | int queries; 122 | scanf("%d", &queries); 123 | char town_name[MAX_STRING_LENGTH]; 124 | while (queries--) { 125 | int type; 126 | scanf("%d", &type); 127 | switch (type) { 128 | case 1: 129 | scanf("%s", town_name); 130 | town* t = find_town(towns, towns_count, town_name); 131 | print_all_packages(*t); 132 | break; 133 | case 2: 134 | scanf("%s", town_name); 135 | town* source = find_town(towns, towns_count, town_name); 136 | int source_index; 137 | scanf("%d", &source_index); 138 | scanf("%s", town_name); 139 | town* target = find_town(towns, towns_count, town_name); 140 | int target_index; 141 | scanf("%d", &target_index); 142 | send_all_acceptable_packages(source, source_index, target, target_index); 143 | break; 144 | case 3: 145 | printf("Town with the most number of packages is %s\n", town_with_most_packages(towns, towns_count).name); 146 | break; 147 | } 148 | } 149 | return 0; 150 | } 151 | 152 | -------------------------------------------------------------------------------- /C/5_StuctsAndEnums/25_StructuringTheDocument.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #define MAX_CHARACTERS 1005 6 | #define MAX_PARAGRAPHS 5 7 | 8 | struct word { 9 | char* data; 10 | }; 11 | 12 | struct sentence { 13 | struct word* data; 14 | int word_count;//denotes number of words in a sentence 15 | }; 16 | 17 | struct paragraph { 18 | struct sentence* data ; 19 | int sentence_count;//denotes number of sentences in a paragraph 20 | }; 21 | 22 | struct document { 23 | struct paragraph* data; 24 | int paragraph_count;//denotes number of paragraphs in a document 25 | }; 26 | typedef struct word word; 27 | typedef struct sentence sentence; 28 | typedef struct paragraph paragraph; 29 | typedef struct document document; 30 | 31 | void add_char(word *_word, char character) { 32 | static int size; 33 | 34 | if (_word->data == NULL) { 35 | _word->data = (char *)malloc(0); 36 | size = 2; 37 | } 38 | 39 | _word->data = (char *)realloc(_word->data, size * sizeof(char)); 40 | _word->data[size - 2] = character; 41 | _word->data[size - 1] = 0; 42 | 43 | size++; 44 | } 45 | 46 | void add_word(sentence *_sentence, word *_word) { 47 | if (_sentence->data == NULL) { 48 | _sentence->data = (word *)malloc(0); 49 | _sentence->word_count = 0; 50 | } 51 | 52 | _sentence->word_count++; 53 | _sentence->data = 54 | (word *)realloc(_sentence->data, _sentence->word_count * sizeof(word)); 55 | _sentence->data[_sentence->word_count - 1] = *_word; 56 | _word->data = NULL; 57 | } 58 | 59 | void add_sentence(paragraph *_paragraph, sentence *_sentence) { 60 | if (_paragraph->data == NULL) { 61 | _paragraph->data = (sentence *)malloc(0); 62 | _paragraph->sentence_count = 0; 63 | } 64 | 65 | _paragraph->sentence_count++; 66 | _paragraph->data = (sentence *)realloc( 67 | _paragraph->data, _paragraph->sentence_count * sizeof(sentence)); 68 | _paragraph->data[_paragraph->sentence_count - 1] = *_sentence; 69 | _sentence->data = NULL; 70 | } 71 | 72 | void add_paragraph(document *_document, paragraph *_paragraph) { 73 | if (_document->data == NULL) { 74 | _document->data = (paragraph *)malloc(0); 75 | _document->paragraph_count = 0; 76 | } 77 | 78 | _document->paragraph_count++; 79 | _document->data = (paragraph *)realloc( 80 | _document->data, _document->paragraph_count * sizeof(paragraph)); 81 | _document->data[_document->paragraph_count - 1] = *_paragraph; 82 | _paragraph->data = NULL; 83 | } 84 | 85 | struct document get_document(char *text) { 86 | document _document; 87 | paragraph _paragraph; 88 | sentence _sentence; 89 | word _word; 90 | 91 | _document.data = NULL; 92 | _paragraph.data = NULL; 93 | _sentence.data = NULL; 94 | _word.data = NULL; 95 | 96 | for (unsigned int i = 0; i <= strlen(text); i++) { 97 | switch (text[i]) { 98 | case ' ': 99 | add_word(&_sentence, &_word); 100 | break; 101 | 102 | case '.': 103 | add_word(&_sentence, &_word); 104 | add_sentence(&_paragraph, &_sentence); 105 | break; 106 | 107 | case '\n': 108 | case '\0': 109 | add_paragraph(&_document, &_paragraph); 110 | break; 111 | 112 | default: 113 | add_char(&_word, text[i]); 114 | break; 115 | } 116 | } 117 | 118 | return _document; 119 | } 120 | 121 | struct word kth_word_in_mth_sentence_of_nth_paragraph(struct document Doc, 122 | int k, int m, int n) { 123 | return Doc.data[n - 1].data[m - 1].data[k - 1]; 124 | } 125 | 126 | struct sentence kth_sentence_in_mth_paragraph(struct document Doc, int k, 127 | int m) { 128 | return Doc.data[m - 1].data[k - 1]; 129 | } 130 | 131 | struct paragraph kth_paragraph(struct document Doc, int k) { 132 | return Doc.data[k - 1]; 133 | } 134 | 135 | void print_word(struct word w) { 136 | printf("%s", w.data); 137 | } 138 | 139 | void print_sentence(struct sentence sen) { 140 | for(int i = 0; i < sen.word_count; i++) { 141 | print_word(sen.data[i]); 142 | if (i != sen.word_count - 1) { 143 | printf(" "); 144 | } 145 | } 146 | } 147 | 148 | void print_paragraph(struct paragraph para) { 149 | for(int i = 0; i < para.sentence_count; i++){ 150 | print_sentence(para.data[i]); 151 | printf("."); 152 | } 153 | } 154 | 155 | void print_document(struct document doc) { 156 | for(int i = 0; i < doc.paragraph_count; i++) { 157 | print_paragraph(doc.data[i]); 158 | if (i != doc.paragraph_count - 1) 159 | printf("\n"); 160 | } 161 | } 162 | 163 | char* get_input_text() { 164 | int paragraph_count; 165 | scanf("%d", ¶graph_count); 166 | 167 | char p[MAX_PARAGRAPHS][MAX_CHARACTERS], doc[MAX_CHARACTERS]; 168 | memset(doc, 0, sizeof(doc)); 169 | getchar(); 170 | for (int i = 0; i < paragraph_count; i++) { 171 | scanf("%[^\n]%*c", p[i]); 172 | strcat(doc, p[i]); 173 | if (i != paragraph_count - 1) 174 | strcat(doc, "\n"); 175 | } 176 | 177 | char* returnDoc = (char*)malloc((strlen (doc)+1) * (sizeof(char))); 178 | strcpy(returnDoc, doc); 179 | return returnDoc; 180 | } 181 | 182 | int main() 183 | { 184 | char* text = get_input_text(); 185 | struct document Doc = get_document(text); 186 | 187 | int q; 188 | scanf("%d", &q); 189 | 190 | while (q--) { 191 | int type; 192 | scanf("%d", &type); 193 | 194 | if (type == 3){ 195 | int k, m, n; 196 | scanf("%d %d %d", &k, &m, &n); 197 | struct word w = kth_word_in_mth_sentence_of_nth_paragraph(Doc, k, m, n); 198 | print_word(w); 199 | } 200 | 201 | else if (type == 2) { 202 | int k, m; 203 | scanf("%d %d", &k, &m); 204 | struct sentence sen= kth_sentence_in_mth_paragraph(Doc, k, m); 205 | print_sentence(sen); 206 | } 207 | 208 | else{ 209 | int k; 210 | scanf("%d", &k); 211 | struct paragraph para = kth_paragraph(Doc, k); 212 | print_paragraph(para); 213 | } 214 | printf("\n"); 215 | } 216 | } -------------------------------------------------------------------------------- /DataStructures/Arrays/1_ArraysDS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int n; 6 | std::cin >> n; 7 | 8 | int arr[n]; 9 | for (int i = 0; i < n; i++) 10 | std::cin >> arr[i]; 11 | 12 | for (int i = n-1; i >= 0; i--) 13 | std::cout << arr[i] << " "; 14 | } 15 | -------------------------------------------------------------------------------- /DataStructures/Arrays/2DArrayDS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int arr[6][6]; 6 | for (int i = 0; i < 6; i++) 7 | for (int j = 0; j < 6; j++) 8 | std::cin >> arr[i][j]; 9 | 10 | int sum = 0, maxSum = -100; 11 | for (int i = 1; i <= 4; i++) { 12 | for (int j = 1; j <= 4; j++) { 13 | sum = 0; 14 | sum += arr[i-1][j-1]; 15 | sum += arr[i-1][j]; 16 | sum += arr[i-1][j+1]; 17 | sum += arr[i][j]; 18 | sum += arr[i+1][j-1]; 19 | sum += arr[i+1][j]; 20 | sum += arr[i+1][j+1]; 21 | if (maxSum < sum) maxSum = sum; 22 | } 23 | } 24 | std::cout << maxSum << std::endl; 25 | 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /DataStructures/Arrays/DynamicArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | std::vector> arr; 7 | 8 | int lastAnswer = 0; 9 | int n, queries; 10 | std::cin >> n >> queries; 11 | 12 | for (int i = 0; i < n; i++) 13 | { 14 | std::vector v; 15 | arr.push_back(v); 16 | } 17 | 18 | int condition, x, y, seq; 19 | for (int i = 0; i < queries; i++) 20 | { 21 | std::cin >> condition >> x >> y; 22 | seq = (x ^ lastAnswer) % n; 23 | switch (condition) 24 | { 25 | case 1: 26 | arr[seq].push_back(y); 27 | break; 28 | case 2: 29 | lastAnswer = arr[seq][y % arr[seq].size()]; 30 | std::cout << lastAnswer << std::endl; 31 | break; 32 | } 33 | } 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /DataStructures/Arrays/LeftRotation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void leftRotateByOne(int array[], int size); 4 | 5 | int main() 6 | { 7 | int n, d; 8 | std::cin >> n >> d; 9 | 10 | int array[n]; 11 | for (int i = 0; i < n; i++) 12 | std::cin >> array[i]; 13 | 14 | for (; d > 0; d--) 15 | leftRotateByOne(array, n); 16 | 17 | for (int i = 0; i < n; i++) 18 | std::cout << array[i] << " "; 19 | std::cout << std::endl; 20 | return 0; 21 | } 22 | 23 | void leftRotateByOne(int array[], int size) 24 | { 25 | int temp = array[0]; 26 | int i; 27 | for (i = 0; i < size - 1; i++) 28 | { 29 | array[i] = array[i + 1]; 30 | } 31 | array[i] = temp; 32 | } -------------------------------------------------------------------------------- /DataStructures/LinkedList/PrintElements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class SinglyLinkedListNode 6 | { 7 | public: 8 | int data; 9 | SinglyLinkedListNode *next; 10 | 11 | SinglyLinkedListNode(int node_data) 12 | { 13 | this->data = node_data; 14 | this->next = nullptr; 15 | } 16 | }; 17 | 18 | class SinglyLinkedList 19 | { 20 | public: 21 | SinglyLinkedListNode *head; 22 | SinglyLinkedListNode *tail; 23 | 24 | SinglyLinkedList() 25 | { 26 | this->head = nullptr; 27 | this->tail = nullptr; 28 | } 29 | 30 | void insert_node(int node_data) 31 | { 32 | SinglyLinkedListNode *node = new SinglyLinkedListNode(node_data); 33 | 34 | if (!this->head) 35 | { 36 | this->head = node; 37 | } 38 | else 39 | { 40 | this->tail->next = node; 41 | } 42 | 43 | this->tail = node; 44 | } 45 | }; 46 | 47 | void free_singly_linked_list(SinglyLinkedListNode *node) 48 | { 49 | while (node) 50 | { 51 | SinglyLinkedListNode *temp = node; 52 | node = node->next; 53 | 54 | free(temp); 55 | } 56 | } 57 | 58 | // Complete the printLinkedList function below. 59 | 60 | /* 61 | * For your reference: 62 | * 63 | * SinglyLinkedListNode { 64 | * int data; 65 | * SinglyLinkedListNode* next; 66 | * }; 67 | * 68 | */ 69 | void printLinkedList(SinglyLinkedListNode *head) 70 | { 71 | SinglyLinkedListNode *temp = head; 72 | while (temp) 73 | { 74 | cout << temp->data << endl; 75 | temp = temp->next; 76 | } 77 | } 78 | 79 | int main() 80 | { 81 | SinglyLinkedList *llist = new SinglyLinkedList(); 82 | 83 | int llist_count; 84 | cin >> llist_count; 85 | cin.ignore(numeric_limits::max(), '\n'); 86 | 87 | for (int i = 0; i < llist_count; i++) 88 | { 89 | int llist_item; 90 | cin >> llist_item; 91 | cin.ignore(numeric_limits::max(), '\n'); 92 | 93 | llist->insert_node(llist_item); 94 | } 95 | 96 | printLinkedList(llist->head); 97 | 98 | return 0; 99 | } 100 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # hackerrank 2 | HackerRank's Solutions 3 | * [C](https://github.com/x899/hackerrank/tree/master/c) 4 | * [C++](https://github.com/x899/hackerrank/tree/master/cpp) 5 | * [30DaysOfCode](https://github.com/x899/hackerrank/tree/master/30DaysOfCode) 6 | --------------------------------------------------------------------------------