diff --git a/.github/workflows/c-cpp.yml b/.github/workflows/c-cpp.yml new file mode 100644 index 00000000..56a7fd6d --- /dev/null +++ b/.github/workflows/c-cpp.yml @@ -0,0 +1,37 @@ +name: C/C++ CI + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + build-ubuntu: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v1 + - name: configure + run: mkdir build && cd build && cmake -DCMAKE_CXX_FLAGS="-Werror" .. + - name: build + run: cmake --build build + - name: test + run: cd build && ctest + + build-windows: + + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [windows-latest, windows-2016] + + steps: + - uses: actions/checkout@v1 + - name: configure + run: mkdir build && cd build && cmake .. + - name: build + run: cmake --build build --config Debug + - name: test + run: cd build && ctest diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..d1692e30 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.idea/ +Algorithms/Algorithms.iml +DS/DS.iml +Hackerrank/Hackerrank.iml +HacktoberfestForBeginners.iml diff --git a/.mergify.yml b/.mergify.yml new file mode 100644 index 00000000..fac2166e --- /dev/null +++ b/.mergify.yml @@ -0,0 +1,7 @@ +pull_request_rules: + - name: Automatic merge on approval + conditions: + - "#approved-reviews-by>=1" + actions: + merge: + method: merge diff --git a/Algorithms/C#/BinaryInsertionSort.cs b/Algorithms/C#/BinaryInsertionSort.cs new file mode 100644 index 00000000..6cf9d382 --- /dev/null +++ b/Algorithms/C#/BinaryInsertionSort.cs @@ -0,0 +1,38 @@ +// C# Program implementing +// binary insertion sort +using System; + +class GFG { + + public static void Main() + { + int []arr = {37, 23, 0, 17, 12, 72, 31, + 46, 100, 88, 54 }; + + sort(arr); + + for(int i = 0; i < arr.Length; i++) + Console.Write(arr[i] + " "); + } + + public static void sort(int []array) + { + for (int i = 1; i < array.Length; i++) + { + int x = array[i]; + + // Find location to insert using + // binary search + int j = Math.Abs(Array.BinarySearch( + array, 0, i, x) + 1); + + // Shifting array to one location right + System.Array.Copy(array, j, array, + j+1, i-j); + + // Placing element at its correct + // location + array[j] = x; + } + } +} diff --git a/Algorithms/C#/BubbleSort.cs b/Algorithms/C#/BubbleSort.cs new file mode 100644 index 00000000..75c1a653 --- /dev/null +++ b/Algorithms/C#/BubbleSort.cs @@ -0,0 +1,34 @@ +// Bubble Sort with C# +using System; + +namespace BubbleSort +{ + class MainClass + { + public static void Main() + { + // test numbers to sort + int[] toSort = { 5, 2, 6, 8, 3}; + + // perform bubble sort + for (int i = 0; i < 5; i++) + { + for (int j = 0; j < 4; j++) + { + if (toSort[j] > toSort[j + 1]) + { + int temp = toSort[j]; + toSort[j] = toSort[j + 1]; + toSort[j + 1] = temp; + } + } + } + + // print to console results + for (int i = 0; i < 5; i++) + { + Console.WriteLine(toSort[i]); + } + } + } +} diff --git a/Algorithms/C#/HeapSort.cs b/Algorithms/C#/HeapSort.cs new file mode 100644 index 00000000..abf394bd --- /dev/null +++ b/Algorithms/C#/HeapSort.cs @@ -0,0 +1,61 @@ +using System; +class heapsort +{ + int[] r = { 2,5,1,10,6,9,3,7,4,8}; + public void hsort() + { + int i, t; + for (i = 5; i >= 0; i--) + { + adjust(i, 9); + } + for (i = 8; i >= 0; i--) + { + t = r[i + 1]; + r[i + 1] = r[0]; + r[0] = t; + adjust(0, i); + } + } + private void adjust(int i, int n) + { + int t, j; + try + { + t = r[i]; + j = 2 * i; + while (j <= n) + { + if (j < n && r[j] < r[j + 1]) + j++; + if (t >=r[j]) + break; + r[j / 2] = r[j]; + j *= 2; + } + r[j / 2] = t; + } + catch (IndexOutOfRangeException e) + { + Console.WriteLine("Array Out of Bounds ", e); + } + } + public void print() + { + for (int i = 0; i < 10; i++) + { + Console.WriteLine("{0}", r[i]); + } + + } + public static void Main() + { + heap obj = new heap(); + Console.WriteLine("Elements Before sorting : "); + obj.print(); + obj.hsort(); + Console.WriteLine("Elements After sorting : "); + obj.print(); + Console.Read(); + } +} \ No newline at end of file diff --git a/Algorithms/C#/InsertionSort.cs b/Algorithms/C#/InsertionSort.cs new file mode 100644 index 00000000..113940c3 --- /dev/null +++ b/Algorithms/C#/InsertionSort.cs @@ -0,0 +1,48 @@ +/* + * C# Program to Perform Insertion Sort + */ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; +namespace ConsoleApplication1 +{ + class Program + { + static void Main(string[] args) + { + int[] arr = new int[5] { 83, 12, 3, 34, 60 }; + int i; + Console.WriteLine("The Array is :"); + for (i = 0; i < 5; i++) + { + Console.WriteLine(arr[i]); + } + insertsort(arr, 5); + Console.WriteLine("The Sorted Array is :"); + for (i = 0; i < 5; i++) + Console.WriteLine(arr[i]); + Console.ReadLine(); + } + static void insertsort(int[] data, int n) + { + int i, j; + for (i = 1; i < n; i++) + { + int item = data[i]; + int ins = 0; + for (j = i - 1; j >= 0 && ins != 1; ) + { + if (item < data[j]) + { + data[j + 1] = data[j]; + j--; + data[j + 1] = item; + } + else ins = 1; + } + } + } + } +} \ No newline at end of file diff --git a/Algorithms/C#/MergeSort.cs b/Algorithms/C#/MergeSort.cs new file mode 100644 index 00000000..af157100 --- /dev/null +++ b/Algorithms/C#/MergeSort.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace CSharpMergeSort +{ + class Mergesort + { + + static public void DoMerge(int [] numbers, int left, int mid, int right) + { + int [] temp = new int[25]; + int i, left_end, num_elements, tmp_pos; + + left_end = (mid - 1); + tmp_pos = left; + num_elements = (right - left + 1); + + while ((left <= left_end) && (mid <= right)) + { + if (numbers[left] <= numbers[mid]) + temp[tmp_pos++] = numbers[left++]; + else + temp[tmp_pos++] = numbers[mid++]; + } + + while (left <= left_end) + temp[tmp_pos++] = numbers[left++]; + + while (mid <= right) + temp[tmp_pos++] = numbers[mid++]; + + for (i = 0; i < num_elements; i++) + { + numbers[right] = temp[right]; + right--; + } + } + + static public void MergeSort_Recursive(int [] numbers, int left, int right) + { + int mid; + + if (right > left) + { + mid = (right + left) / 2; + MergeSort_Recursive(numbers, left, mid); + MergeSort_Recursive(numbers, (mid + 1), right); + + DoMerge(numbers, left, (mid+1), right); + } + } + + static void Main(string[] args) + { + int[] numbers = { 3, 8, 7, 5, 2, 1, 9, 6, 4 }; + int len = 9; + + Console.WriteLine("MergeSort By Recursive Method"); + MergeSort_Recursive(numbers, 0, len - 1); + for (int i = 0; i < 9; i++) + Console.WriteLine(numbers[i]); + + Console.WriteLine(numbers[i]); + + } + } +} \ No newline at end of file diff --git a/Algorithms/C#/QuickSort.cs b/Algorithms/C#/QuickSort.cs new file mode 100644 index 00000000..12f13f29 --- /dev/null +++ b/Algorithms/C#/QuickSort.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace sortQuickAlgorithm +{ + class quickSortAlgorithm + { + + private int[] array = new int[20]; + private int len; + + public void QuickSortAlgorithm() + { + sort(0, len - 1); + } + + public void sort(int left, int right) + { + int pivot, leftend, rightend; + + leftend = left; + rightend = right; + pivot = array[left]; + + while (left < right) { while ((array[right] >= pivot) && (left < right)) + { + right--; + } + + if (left != right) + { + array[left] = array[right]; + left++; + } + + while ((array[left] >= pivot) && (left < right)) + { + left++; + } + + if (left != right) + { + array[right] = array[left]; + right--; + } + } + + array[left] = pivot; + pivot = left; + left = leftend; + right = rightend; + + if (left < pivot) { sort(left, pivot - 1); } if (right > pivot) + { + sort(pivot + 1, right); + } + } + + public static void Main() + { + quickSortAlgorithm q_Sort = new quickSortAlgorithm(); + + int[] array = { 41, 32, 15, 45, 63, 72, 57, 43, 32, 52, 183}; + q_Sort.array = array; + q_Sort.len = q_Sort.array.Length; + q_Sort.QuickSortAlgorithm(); + + for (int j = 0; j < q_Sort.len; j++) + { + Console.WriteLine(q_Sort.array[j]); + } + Console.ReadKey(); + } + } +} \ No newline at end of file diff --git a/Algorithms/C#/SelectionSort.cs b/Algorithms/C#/SelectionSort.cs new file mode 100644 index 00000000..9c71b5cd --- /dev/null +++ b/Algorithms/C#/SelectionSort.cs @@ -0,0 +1,42 @@ +/* + * C# Program to Perform a Selection Sort + */ +using System; +class Program +{ + static void Main(string[] args) + { + int array_size = 10; + int[] array = new int[10] { 100, 50, 20, 40, 10, 60, 80, 70, 90, 30 }; + Console.WriteLine("The Array Before Selection Sort is: "); + for (int i = 0; i < array_size; i++) + { + Console.WriteLine(array[i]); + } + int tmp, min_key; + + for (int j = 0; j < array_size - 1; j++) + { + min_key = j; + + for (int k = j + 1; k < array_size; k++) + { + if (array[k] < array[min_key]) + { + min_key = k; + } + } + + tmp = array[min_key]; + array[min_key] = array[j]; + array[j] = tmp; + } + + Console.WriteLine("The Array After Selection Sort is: "); + for (int i = 0; i < 10; i++) + { + Console.WriteLine(array[i]); + } + Console.ReadLine(); + } +} \ No newline at end of file diff --git a/Algorithms/C#/ShellSort.cs b/Algorithms/C#/ShellSort.cs new file mode 100644 index 00000000..d785fa51 --- /dev/null +++ b/Algorithms/C#/ShellSort.cs @@ -0,0 +1,32 @@ +private void SortArrayWithShellSort() + { + int[] array = { 297,183, 464 }; + ShellSort(array); + } + + + private void ShellSort(int[] array) + { + int n = array.Length; + int gap = n / 2; + int temp; + + while (gap > 0) + { + for (int i = 0; i + gap < n; i++) + { + int j = i + gap; + temp = array[j]; + + while (j - gap >= 0 && temp < array[j - gap]) + { + array[j] = array[j - gap]; + j = j - gap; + } + + array[j] = temp; + } + + gap = gap / 2; + } + } \ No newline at end of file diff --git a/Algorithms/C++/BozoSort.cpp b/Algorithms/C++/BozoSort.cpp new file mode 100644 index 00000000..f5ce480e --- /dev/null +++ b/Algorithms/C++/BozoSort.cpp @@ -0,0 +1,43 @@ +#include +#include +using namespace std; + +bool ifsorted(int* tab, int size) +{ + bool sorted = false; + for (int i = 1; i < size; i++) + { + if (tab[i - 1] <= tab[i]) sorted = true; + else return false; + } + return sorted; +} + +int main() // bozo sort +{ + srand(time(NULL)); + bool sorted = false; + int size = 0; + //long long int counter = 0; + cin >> size; + + int* tab = new int[size]; + + for (int i = 0; i < size; i++) + cin >> tab[i]; + + cout << endl; + while (!sorted) + { + int x = rand() % size; + int y = rand() % size; + int temp = tab[x]; + tab[x] = tab[y]; + tab[y] = temp; + sorted = ifsorted(tab, size); + //counter++; + } + //for (int i = 0; i < size; i++) + // cout << tab[i] << endl; + //cout << endl << endl << counter; +} \ No newline at end of file diff --git a/Algorithms/C++/Circularlinklist.cpp b/Algorithms/C++/Circularlinklist.cpp new file mode 100644 index 00000000..353d5aa5 --- /dev/null +++ b/Algorithms/C++/Circularlinklist.cpp @@ -0,0 +1,123 @@ +#include +using namespace std; +class node{ + public: + int data; + node* next; + node* previous; +}; +class DLL{ + public: + node* head; + node* tail; + DLL() + { + head=NULL; + tail=NULL; + } + void insert(int d) + { + node* ptr; + ptr=head; + node* nptr=new node; + nptr->data=d; + nptr->next=NULL; + nptr->previous=NULL; + if(head==NULL) + { + head=nptr; + tail=head; + } + else + { + tail->next=nptr; + nptr->previous=tail; + nptr->next=head; + tail=nptr; + } + } + void print() + { + node* ptr; + ptr=head; + while(ptr->next!=head) + { + cout<<"THE VALUE INSERTED IS:"<data<next; + + } + cout<<"THE VALUE INSERTED IS:"<data<next!=head) + { + if(ptr->data==s) + { + cout<<"THE VALUE IS FOUND"<next; + } + if(ptr->data==s) + { + cout<<"THE VALUE IS FOUND"<>pos; + s = head; + if(pos == 1) { + count--; + tail->next = s->next; + s->next->previous = tail; + head = s->next; + delete(s); + cout<<"Element Deleted"<next; + ptr = s->previous; + } + ptr->next = s->next; + s->next->previous = ptr; + if (pos == count) { + tail = ptr; + } + count--; + delete(s); + cout<<"Element Deleted"< +#include +using namespace std; + void addEdge(vector arr[],int a,int b); + void addEdge(vector arr[],int a,int b) +{ + arr[a].push_back(b); + arr[b].push_back(a); +} +void DFSuntil(int i,vector arr[],vector &visited) +{ + cout< arr[],int n) +{ + vector visited(n,false); + for(int i=0;i>n; + int edge; + vector arr[n]; + cin>>edge;int a;int b; + for(int i=0;i>a; + cin>>b; + addEdge(arr,a,b); + } + vector::iterator itr; + for(int i=0;i"; + for(itr=arr[i].begin();itr using namespace std; diff --git a/Algorithms/C++/Frequency_Analysis.cpp b/Algorithms/C++/Frequency_Analysis.cpp new file mode 100644 index 00000000..ca582f12 --- /dev/null +++ b/Algorithms/C++/Frequency_Analysis.cpp @@ -0,0 +1,29 @@ +/*Decrypting caesar cipher with frecuency analysis the principle of the fecuency analysis is knowing which is the most used letter on a a text given +after 'e' er the most common letter on the english language*/ +#include +#include +using namespace std; + +int main(){ + char sentence[30]; + int count = 1; + + cout << "Write a message: "; + cin.getline(sentence, 30); + + for(int i = 1; i < sentence[i]; i++) + { + for(int j = i + 1; j < sentence[i]; j++) + { + if(sentence[i] == sentence[j]){ + count++; + sentence[j] = 0; + } + } + cout << sentence[i] << " appeared: " << count << " Times" << endl; + count = 1; + } +} + +/*Knowing the most common letter on our message we can now count many spaces there are +between e and the most common letter, this number is possibly the key.*/ \ No newline at end of file diff --git a/Algorithms/C++/Huffman_coding.cpp b/Algorithms/C++/Huffman_coding.cpp new file mode 100644 index 00000000..337e1106 --- /dev/null +++ b/Algorithms/C++/Huffman_coding.cpp @@ -0,0 +1,71 @@ + +using namespace std; +struct Node +{ + int data; + char val; + Node *left,*right; + Node(int a,char b) + { + left=NULL; + right=NULL; + this->val=b; + this->data=a; + } + +}; +struct compare +{ +bool operator()(Node *a,Node *b) +{ + return(a->data>b->data); +}}; +void printme(Node *root,string s) +{ + if(root==NULL)return; + if(root->val!='%') + { + cout<left,s+'0'); + printme(root->right,s+'1'); +} +void func(int arr[],int len,string s) +{ + priority_queue,compare>que; + for(int j=0;j1) + { + left=que.top(); + que.pop(); + right=que.top(); + que.pop(); + top=new Node(left->data+right->data,'%'); + que.push(top); + top->left=left; + top->right=right; + } + printme(top,""); +} +int main() { + //code + int n; + cin>>n; + for(int i=0;i>s; + int arr[s.length()]; + for(int j=0;j>arr[j]; + } + func(arr,s.length(),s); + cout<<'\n'; + } + return 0; +} diff --git a/Algorithms/C++/Latine Square/LatinSquare.cpp b/Algorithms/C++/Latine Square/LatinSquare.cpp new file mode 100644 index 00000000..eba3adbc --- /dev/null +++ b/Algorithms/C++/Latine Square/LatinSquare.cpp @@ -0,0 +1,118 @@ +#include "LatinSquare.h" +#include +#include "Path.h" +using namespace std; + + +LatinSquare::LatinSquare(int n){ + this -> n = n; + m = new int*[n]; + for (int i=0;i i and j and x are: "< +#include "LatinSquare.h" +/* run this program using the console pauser or add your own getch, system("pause") or input loop */ + +int main(int argc, char** argv) { + LatinSquare s(3); + s.calculate(); +} diff --git a/Algorithms/C++/Leap Year.cpp b/Algorithms/C++/Leap Year.cpp new file mode 100644 index 00000000..8865c95d --- /dev/null +++ b/Algorithms/C++/Leap Year.cpp @@ -0,0 +1,30 @@ +/* C++ Program - Check Leap Year or Not */ + +#include +#include +using namespace std; +int main() +{ + + int yr; + cout<<"--------Enter year :----------"; + cin>>yr; + if((yr%4==0) && (yr%100!=0)) + { + cout<<"This is a Leap Year"; + } + else if((yr%100==0) && (yr%400==0)) + { + cout<<"This is a Leap Year"; + } + else if(yr%400==0) + { + cout<<"This is a Leap Year"; + } + else + { + cout<<"This is not a Leap Year"; + } + getch(); + return 0; +} diff --git a/Algorithms/C++/Num_to_English.cpp b/Algorithms/C++/Num_to_English.cpp new file mode 100644 index 00000000..da20b4cd --- /dev/null +++ b/Algorithms/C++/Num_to_English.cpp @@ -0,0 +1,341 @@ +//convert the input number into the letters +#include +#include +using namespace std; + + +//Add a string +string addString(string str, string add) +{ + + string s=""; +/* s+=add; + s+=" "; + s+=str;*/ + for(int i=0;add[i]!='\0';i++) + { + s+=add[i]; + } + s+=" "; + for(int i=0;str[i]!='\0';i++) + { + s+=str[i]; + } + return s; + +} + +//Convert the hundredth terms into the corresponding letters +string hunDigToLetter(string str, int num) +{ + int r; + r=num%10; + if(r!=0) + { + str = addString( str, "Hundred"); + switch (r) + { + case 1: + str= addString(str , "One"); + break; + case 2: + str= addString(str , "Two"); + break; + case 3: + str= addString(str , "Three"); + break; + case 4: + str= addString(str , "Four"); + break; + case 5: + str= addString(str , "Five"); + break; + case 6: + str= addString(str , "Six"); + break; + case 7: + str= addString(str , "Seven"); + break; + case 8: + str= addString(str , "Eight"); + break; + case 9: + str= addString(str , "Nine"); + break; + default: + break; + } + } + return str; +} + +//Convert the ones term into corresponding letters +string onesDigToLetter(string str, int num) +{ + int r; + r=num%10; + if((num/10)%10==1) + { + switch (r) + { + case 0: + str= addString(str , "Ten"); + break; + + case 1: + str= addString(str , "Eleven"); + break; + case 2: + str= addString(str , "Twelve"); + break; + case 3: + str= addString(str , "Thirteen"); + break; + case 4: + str= addString(str , "Fourteen"); + break; + case 5: + str= addString(str , "Fifteen"); + break; + case 6: + str= addString(str , "Sixteen"); + break; + case 7: + str= addString(str , "Seventeen"); + break; + case 8: + str= addString(str , "Eighteen"); + break; + case 9: + str= addString(str , "Nineteen"); + break; + default: + break; + } + } + else + { + + switch (r) + { + case 1: + str= addString(str , "One"); + break; + case 2: + str= addString(str , "Two"); + break; + case 3: + str= addString(str , "Three"); + break; + case 4: + str= addString(str , "Four"); + break; + case 5: + str= addString(str , "Five"); + break; + case 6: + str= addString(str , "Six"); + break; + case 7: + str= addString(str , "Seven"); + break; + case 8: + str= addString(str , "Eight"); + break; + case 9: + str= addString(str , "Nine"); + break; + default: + break; + } + } + return str; + +} + +//Convert the tens term into corresponding letters +string tensDigToLetter(string str, int num) +{ + int r; + r=num%10; + switch (r) + { + case 2: + str= addString(str , "Twenty"); + break; + case 3: + str= addString(str , "Thirty"); + break; + case 4: + str= addString(str , "Forty"); + break; + case 5: + str= addString(str , "Fifty"); + break; + case 6: + str= addString(str , "Sixty"); + break; + case 7: + str= addString(str , "Seventy"); + break; + case 8: + str= addString(str , "Eighty"); + break; + case 9: + str= addString(str , "Ninety"); + break; + default: + break; + } + return str; +} + +int main () +{ + long long num ; + string str=""; + cout<<"Enter the number to convert it into English but the number must be less than 1 billion:\n"; + cin>>num; + if(num<1000000000) //convert numbers less than 1 billion + { + + // cout< +#include +using namespace std; +int main() +{ + + int num, rem, orig, rev=0; + cout<<"------Enter The number :--------- "; + cin>>num; + orig=num; + while(num!=0) + { + rem=num%10; + rev=rev*10 + rem; + num=num/10; + } + if(rev==orig) // check if original number is equal to its reverse + { + cout<<"A Palindrome"; + } + else + { + cout<<"Not a Palindrome"; + } + getch(); + return 0; +} diff --git a/Algorithms/C++/QueenProblem.cpp b/Algorithms/C++/QueenProblem.cpp new file mode 100644 index 00000000..ac868808 --- /dev/null +++ b/Algorithms/C++/QueenProblem.cpp @@ -0,0 +1,103 @@ +// Much shorter version is added check out :) +// uses C++11 threads to parallelize the computation; also uses backtracking +// Outputs all solutions for any table size +#include +#include +#include +#include +#include +using namespace std; +// Print table. 'pos' is a vector of positions the index in pos is the row, +// and the number at that index is the column where the queen is placed. +static void print(const std::vector &pos) +{ + // print table header + for (int i = 0; i < pos.size(); i++) { + std::cout << std::setw(3) << char('a' + i); + } + + std::cout << '\n'; + + for (int row = 0; row < pos.size(); row++) { + int col = pos[row]; + std::cout << row + 1 << std::setw(3 * col + 3) << " # "; + std::cout << '\n'; + } + + std::cout << "\n\n"; +} + +static bool threatens(int row_a, int col_a, int row_b, int col_b) +{ + return row_a == row_b // same row + or col_a == col_b // same column + or std::abs(row_a - row_b) == std::abs(col_a - col_b); // diagonal +} + +// the i-th queen is in the i-th row +// we only check rows up to end_idx +// so that the same function can be used for backtracking and checking the final solution +static bool good(const std::vector &pos, int end_idx) +{ + for (int row_a = 0; row_a < end_idx; row_a++) { + for (int row_b = row_a + 1; row_b < end_idx; row_b++) { + int col_a = pos[row_a]; + int col_b = pos[row_b]; + if (threatens(row_a, col_a, row_b, col_b)) { + return false; + } + } + } + + return true; +} + +static std::mutex print_count_mutex; // mutex protecting 'n_sols' +static int n_sols = 0; // number of solutions + +// recursive DFS backtracking solver +static void n_queens(std::vector &pos, int index) +{ + // if we have placed a queen in each row (i. e. we are at a leaf of the search tree), check solution and return + if (index >= pos.size()) { + if (good(pos, index)) { + std::lock_guard lock(print_count_mutex); + print(pos); + n_sols++; + } + + return; + } + + // backtracking step + if (not good(pos, index)) { + return; + } + + // optimization: the first level of the search tree is parallelized + if (index == 0) { + std::vector> fts; + for (int col = 0; col < pos.size(); col++) { + pos[index] = col; + auto ft = std::async(std::launch::async, [=]{ auto cpos(pos); n_queens(cpos, index + 1); }); + fts.push_back(std::move(ft)); + } + + for (const auto &ft : fts) { + ft.wait(); + } + } else { // deeper levels are not + for (int col = 0; col < pos.size(); col++) { + pos[index] = col; + n_queens(pos, index + 1); + } + } +} + +int main() +{ + std::vector start(12); // 12: table size + n_queens(start, 0); + std::cout << n_sols << " solutions found.\n"; + return 0; +} \ No newline at end of file diff --git a/Algorithms/C++/Queue.cpp b/Algorithms/C++/Queue.cpp new file mode 100644 index 00000000..711c4040 --- /dev/null +++ b/Algorithms/C++/Queue.cpp @@ -0,0 +1,68 @@ +#include +using namespace std; + +class node{ + public: + node *next; + int value; +}; + +class que{ + node *head; + node *tail; + public: + que(){ + head=NULL; + tail=NULL; + } + void push(int data){ + node *ptr=new node; + ptr->value=data; + ptr->next=NULL; + if(head==NULL){ + head=ptr; + tail=ptr; + } + else{ + tail->next=ptr; + tail=ptr; + } + } +// pop function started from here + + + void pop(){ + node *prev,*forward; + prev=head; + forward=head->next; + if(head!=NULL){ + head=head->next; + delete(prev); + + } + else{ + cout<<"list is empty"<value<next; + } + cout< +using namespace std; +void selection_sort(int a[], int n) +{ + int i, j, min, temp ; + for(i = 0; i < n-1 ; i++) + { + min = i; + for (j = i+1; j < n; j++) + { + if (a[j] < a[min]) + { + min = j; + } + } + temp = a[i]; + a[i] = a[min]; + a[min] = temp; + } +} +int main () +{ + int n , i, ch; + cout<<"\nEnter the number of elements: "; + cin>>n; + int a[n]; + cout<<"\nEnter "<> a[i]; + selection_sort( a, n ); + cout<<"Sorted Array:\n"; + for(int i = 0 ; i < n; i++ ) + cout< + +using namespace std; +//Defining function for arithmetic operations +float operation(float num1, float num2, char oper) +{ + while (true) + { + if (oper == '+') return num1 + num2; + if (oper == '-') return num1 - num2; + if (oper == '*') return num1 * num2; + if (oper == '/') return num1 / num2; + cout << "!!wrong operator!!\nSelect one from the following (+,-,*,/) : "; + cin >> oper; + } +} + +int main() +{ + float op1, op2, result; + char oper; + cout << "The program is calculator of basic calculations "; + cout << "Enter '+' for Addition\n"; + cout << "Enter '-' for Subtraction\n"; + cout << "Enter '*' for Multiplication\n"; + cout << "Enter '/' for Division\n"; + + cout << "\nEnter 1st Operand : "; + cin >> op1; + cout << "\nEnter 2nd Operand : "; + cin >> op2; + cout << "\nEnter operator : "; + cin >> oper; + result = operation(op1, op2, oper); + + cout << "This result of integer expression is : " << result << endl; + system("pause"); + return 0; +} \ No newline at end of file diff --git a/Algorithms/C++/addnumbers b/Algorithms/C++/addnumbers new file mode 100644 index 00000000..385559fc --- /dev/null +++ b/Algorithms/C++/addnumbers @@ -0,0 +1,11 @@ +#include + +using namespace spr + +int main(){ + int a,b; + cout<<"Write two numbers to add"<>a>>b; + int r=a+b; + cout<<"The add is "< +#include "cNode.h" + +using namespace std; + +cNode::cNode() :data(0),priority(0) +{ +} + +cNode::cNode(int d):data(d), priority(0){ +} + +cNode::cNode(int d, int p):data(d), priority(p) +{} + +int cNode::getData(){ + return data; + } + +cNode* cNode::setData(int data){ + this->data=data; + } + +void cNode::print()const{ + cout<priority=Prior; +} + +cNode::~cNode() +{ +} diff --git a/Algorithms/C++/cNode.h b/Algorithms/C++/cNode.h new file mode 100644 index 00000000..454e83c7 --- /dev/null +++ b/Algorithms/C++/cNode.h @@ -0,0 +1,17 @@ +class cNode +{ + int data; + int priority; +public: + cNode *next; + cNode(); + cNode(int d); + cNode(int d, int p); + int getData(); + cNode* setData(int data); + void print()const; + int getPriority() const; + void setPriority(int prior); + ~cNode(); +}; + diff --git a/Algorithms/C++/cQue.cpp b/Algorithms/C++/cQue.cpp new file mode 100644 index 00000000..a49487b0 --- /dev/null +++ b/Algorithms/C++/cQue.cpp @@ -0,0 +1,92 @@ +#include +#include "cQue.h" + +using namespace std; + +cQue::cQue():tail(NULL) +{ +} + +cQue::cQue(cNode* &ptr):cStack(ptr),tail(top){ + } + +bool cQue::isNotEmpty()const{ + return cStack::isNotEmpty(); + } + +bool cQue::isEmpty()const{ + return cStack::isEmpty(); + } + +cNode* cQue::remove(){ + if(!top->next) + tail=NULL; + return cStack::pop(); + } + +cQue& cQue::add(cNode* &ptr){ + if(tail){ + tail->next=ptr; + tail=tail->next; + } + else + { + tail=ptr; + top=ptr; + } + tail->next=NULL; + ptr=NULL; + return *this; + } + +void cQue::print()const{ // + cStack::print(); + } + +cQue::cQue(const cQue &src){ /// + this->top=src.top; + this->tail=src.tail; + if(src.top){ + cNode *sptr,*dptr; + dptr=top=new cNode(*src.top); + sptr=top->next; + while(sptr){ + dptr->next=new cNode(*sptr); + dptr=dptr->next; + sptr=sptr->next; + } + tail=dptr; + } + } + +cQue& cQue::operator=(const cQue& obj){ + if(this==&obj) + return *this; + if(true){ + cQue temp; + temp.top=top; + temp.tail=tail; + } + if(true){ + cQue temp=obj; + top=temp.top; + tail=temp.tail; + temp.top=NULL; + temp.tail=NULL; + } + return *this; + } + +cQue::~cQue() +{ + cNode *ptr = top; + + tail = NULL; + + while (ptr) + { + ptr = ptr -> next; + delete top; + top = ptr; + } +} diff --git a/Algorithms/C++/cQue.h b/Algorithms/C++/cQue.h new file mode 100644 index 00000000..91639c1f --- /dev/null +++ b/Algorithms/C++/cQue.h @@ -0,0 +1,18 @@ +#pragma once +#include"cStack.h" +class cQue:protected cStack{ +protected: + cNode *tail; +public: + cQue(); + cQue(cNode* &ptr); + bool isNotEmpty()const; + bool isEmpty()const; + cNode* remove(); + cQue& add(cNode* &ptr); + void print()const; + cQue(const cQue &src); + cQue& operator=(const cQue& obj); + ~cQue(); +}; + diff --git a/Algorithms/C++/currency_changer.cpp b/Algorithms/C++/currency_changer.cpp new file mode 100644 index 00000000..4452fee0 --- /dev/null +++ b/Algorithms/C++/currency_changer.cpp @@ -0,0 +1,57 @@ +#include +#include +using namespace std; + +int currency(int *coins,int n,int amount){ + if(amount==0){ + return 0; + } + + int ans=INT_MAX; + for(int i=0;i=0){ + int smallerans=currency(coins,n,amount-coins[i]); + if(smallerans!=INT_MAX){ + ans=min(ans,smallerans+1); + } + } + } + return ans; +} + +/*int topdown(int *coins,int n,int amount,int *dp){ + if(amount==0){ + dp[amount]=0; + return dp[amount]; + } + if(dp(dp[amount])) +}*/ + +int bottomup(int *coins,int n,int amount){ + int dp[1000]; + for(int i=0;i<1000;i++){ + dp[i]=INT_MAX; + } + dp[0]=0; + + for(int rupay=1;rupay<=amount;rupay++){ + for(int i=0;i=0){ + dp[rupay]=min(dp[rupay],dp[rupay-coins[i]]+1); + } + } + } + return dp[amount]; +} + +int main(){ + int coins[]={1,7,10}; + int n=sizeof(coins)/sizeof(int); + + int amount; + cin>>amount; + + cout<val < B->val){ + head = A; + A = A->next; + } + else{ + head = B; + B = B->next; + } + + ListNode* temp = head; + + while(A != NULL && B != NULL){ + if(A->val < B->val){ + temp->next = A; + A = A->next; + } + else{ + temp->next = B; + B = B->next; + } + temp = temp->next; + } + + if(A != NULL){ + temp->next = A; + } + else{ + temp->next = B; + } + + return head; +} + +ListNode* Solution::sortList(ListNode* A) { + // Do not write main() function. + // Do not read input, instead use the arguments to the function. + // Do not print the output, instead return values as specified + // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details + + ListNode* head = A; + + if(head == NULL || head->next == NULL){ + return head; + } + + ListNode* start = A; + ListNode* end = A->next; + + while(end != NULL && end->next != NULL){ + start = start->next; + end = (end->next)->next; + } + + end = start->next; + start->next = NULL; + + return merge(sortList(head), sortList(end)); +} diff --git a/Algorithms/C++/queue.h b/Algorithms/C++/queue.h new file mode 100644 index 00000000..a35af4a4 --- /dev/null +++ b/Algorithms/C++/queue.h @@ -0,0 +1,116 @@ + #include + #include + #include + using namespace std; + + class Queue { + private: + + struct Node + { + string name; //stores name of group + int people; //stores position of each group memebers + Node *next; + }; + + Node *front; + Node *rear; + int count; + + public: + Queue(); + void enqueue(string, int); + string dequeue(); //removes queue item + bool isEmpty(); //tests if queue is empty + void clear(); //clears entire queue + int size(); //returns the counter + }; + + Queue::Queue() + { //Constructor + front = NULL; + rear = NULL; + count = 0; + } + + + void Queue::enqueue(string x, int y) + { // inserts value + Node *temp = new Node; //at the rear + temp->name = x; + temp->people = y; + temp->next = NULL; + + if(isEmpty()) + { + front = temp; + rear = temp; + } + + else + { + rear->next = temp; + rear = temp; + } + + count++; + } + + string Queue::dequeue() + { // removes value at the front teturns it + + assert(!isEmpty()); + + string groupName; + int members; + + Node *temp = new Node; + temp->name = front->name; + temp->people = front->people; + front = front->next; + + groupName = temp->name; + + members = temp->people; + delete temp; + + count--; + + string convert = to_string(members); + string total = groupName + " " + convert; + return total; + } + + bool Queue::isEmpty() + { // tests if queue is empty using bool + + bool flag; + + if(count > 0) + flag = false; + + else + flag = true; + + return flag; + } + + + int Queue::size() + { // returns counter + + return count; + } + + void Queue::clear() + { // clears the queue + + string x; + + while(!isEmpty()) + { + x = dequeue(); + cout << x << endl; + } + } + diff --git a/Algorithms/C++/stack.cpp b/Algorithms/C++/stack.cpp new file mode 100644 index 00000000..7f123603 --- /dev/null +++ b/Algorithms/C++/stack.cpp @@ -0,0 +1,72 @@ +#include +using namespace std; + +class node{ + public: + node *next; + int value; +}; + +class stack{ + node *head; + node *tail; + public: + stack(){ + head=NULL; + tail=NULL; + } + void push(int data){ + node *ptr=new node; + ptr->value=data; + ptr->next=NULL; + if(head==NULL){ + head=ptr; + tail=ptr; + } + else{ + tail->next=ptr; + tail=ptr; + } + } +// pop function started from here + + + void pop(){ + node *prev,*forward; + prev=head; + forward=head->next; + + if(head!=NULL){ + while(forward->next!=NULL){ + prev=prev->next; + forward=forward->next; + } + tail=prev; + prev->next=NULL; + + delete(forward); + } + else{ + cout<<"list is empty"<value<next; + } + } +}; +int main() +{ + stack st; + st.push(23); + st.push(25); + st.push(35); + + st.display(); + return 0; +} + diff --git a/Algorithms/C/Numper pair or odd b/Algorithms/C/Numper pair or odd new file mode 100644 index 00000000..53b4d722 --- /dev/null +++ b/Algorithms/C/Numper pair or odd @@ -0,0 +1,13 @@ +#include +#include + +int main(){ + int num; + print("Write a number\n"); + scanf("%d",&num); + if(num%2){ + printf("Is pair"); + }else{ + printf("Is odd"); + } +} diff --git a/Algorithms/C/Tower-Of-Hanoi.c b/Algorithms/C/Tower-Of-Hanoi.c new file mode 100644 index 00000000..83eafd16 --- /dev/null +++ b/Algorithms/C/Tower-Of-Hanoi.c @@ -0,0 +1,40 @@ +// Name: Bhupendra Chauhan +//Email: chauhanbhupendra145@gmail.com +/*This is a program for Tower of Hanoi using recursion. + * Number of Disks are taken as input from User. +*/ + +#include + +void TOH(int, char, char, char); + +// Driver Code +int main(){ + int n; //Number of Disks + flag: + printf("Enter the number of disks : "); + scanf("%d",&n); + if(n>0){ + printf("The sequence of moves involved in the Tower of Hanoi are :\n"); + TOH(n, 'A', 'C', 'B'); + } + else{ + printf("Number of Disks should be a Natural Number\n"); + goto flag; + } + + return 0; +} + + +//Program Of Tower Of Hanoi +void TOH(int n,char From,char To,char Aux){ + if(n==1){ + printf("Move disk %d from Tower %c to Tower %c \n",n,From,To); + return; + } + TOH(n-1,From,Aux,To); + printf("Move disk %d from Tower %c to Tower %c \n",n,From,To); + TOH(n-1,Aux,To,From); +} + diff --git a/Algorithms/C/fibonacci.c b/Algorithms/C/fibonacci.c new file mode 100644 index 00000000..f2af0a6e --- /dev/null +++ b/Algorithms/C/fibonacci.c @@ -0,0 +1,41 @@ +#include +#include //openmp library + +long fib(long n) +{ + long i, j; + + if (n < 2) + return n; + else if (n < z) + { + return fib(n-1) + fib (n-2); + } + else + { + #pragma omp parallel sections + { + #pragma omp section + i = fib(n-1); + #pragma omp section + j = fib(n-2); + } + return i + j; + } +} + + + +int main() { + int i, n, t = 0, t1 = 1, nextTerm; + printf("Enter the number of terms: "); + scanf("%d", &n); + printf("Fibonacci Series: "); + for (i = 1; i <= n; ++i) { + printf("%d, ", t); + nextTerm = t + t1; + t = t1; + t1 = nextTerm; + } + return 0; +} diff --git a/Algorithms/C/infixtopostfixconvertion.c b/Algorithms/C/infixtopostfixconvertion.c new file mode 100644 index 00000000..3fa9528d --- /dev/null +++ b/Algorithms/C/infixtopostfixconvertion.c @@ -0,0 +1,110 @@ +/* This Program converts infix expression to postfix expression */ +#include +#include + +#define MAX_SIZE 100 +// Top of the stack +int top = -1; +// Array representing stack +char stack[MAX_SIZE]; +// Checks whether stack is empty or not +int isStackEmpty(void){ + return (top < 0) ? 1 : 0; +} +// Checks whether stack is full or not +int isStackFull(void){ + return (top == MAX_SIZE) ? 1 : 0; +} +// Push elements in the stack +void pushStack(char item){ + if(isStackFull()){ + printf("Stack Overflow!\n"); + return; + } + top++; + stack[top] = item; +} +// Pop elements in the stack +char popStack(void){ + if(isStackEmpty()){ + printf("Stack Underflow!\n"); + return -1; + } + char item = stack[top]; + top--; + return item; +} +// Function to input the infix expression +void scanExp(char *str){ + char ch,i; + for(i=0; (ch=getchar()) != '\n'; i++){ + str[i] = ch; + } + str[i] = '\0'; +} + +// Function to check whether the character is an operator +int isOperator(char ch){ + switch(ch){ + case '^': + case '/': + case '*': + case '+': + case '-': + return 1; + default: + return 0; + } +} + +// Function converts the infix expression to postfix expression +void infix2postfix(char *infix, char *postfix){ + // Operator Predecence + int operators[256]; + operators['^'] = 0; + operators['*'] = 1; + operators['/'] = 1; + operators['+'] = 2; + operators['-'] = 2; + + infix[strlen(infix)] = ')'; + + int i, j; + pushStack('('); + for(i=0,j=0;!isStackEmpty();){ + if(!isOperator(infix[i]) && infix[i] != '(' && infix[i] != ')'){ + postfix[j]=infix[i]; + i++; + j++; + }else if(infix[i] == '('){ + pushStack(infix[i]); + i++; + }else if(isOperator(infix[i])){ + while(isOperator(stack[top]) && operators[stack[top]] <= operators[infix[i]]){ + char operator = popStack(); + postfix[j]=operator; + j++; + } + pushStack(infix[i]); + i++; + }else if(infix[i] == ')'){ + char item; + while((item=popStack()) != '('){ + postfix[j] = item; + j++; + } + i++; + } + } + postfix[j] = '\0'; +} + +int main(void){ + char infix[100], postfix[100]; + printf("Enter the infix expression : "); + scanExp(infix); + printf("Infix Expression : %s\n", infix); + infix2postfix(infix, postfix); + printf("Postfix Expression : %s\n", postfix); + return 0; +} diff --git a/Algorithms/C/pass1.c b/Algorithms/C/pass1.c new file mode 100644 index 00000000..9ebf346f --- /dev/null +++ b/Algorithms/C/pass1.c @@ -0,0 +1,93 @@ +#include +#include + +main() +{ + char opcode[10],operand[10],label[10],code[10][10],ch,op[10],ml_equ[2]; + int locctr,start,len,i=0,j=0,f; + + FILE *fp1,*fp2,*fp3,*fp4; + fp1=fopen("INPUT.DAT","r");//mnemonic code + fp2=fopen("SYMTAB.DAT","wb+");//SYMTAB + fp3=fopen("INERMEDIATE.DAT","wb+");//intermediate file + fp4=fopen("OPTAB.DAT","r");//OPTAB + + fscanf(fp1,"%s%s%s",label,opcode,operand);//read the first input line + + if(strcmp(opcode,"START")==0) + { + start = atoi(operand);//save starting_address <- #[OPERAND] + locctr = start;//LOCCTR <- starting_address + fprintf(fp3,"%s\t%s\t%s\n",label,opcode,operand);//write line to intermediate file + fscanf(fp1,"%s%s%s",label,opcode,operand);//read next input line + } + else + locctr=0;//LOCCTR <- 0 + + while(strcmp(opcode,"END")!=0) + { + fprintf(fp3,"%d",locctr); + if(strcmp(label,"**")!=0)//label exists + { + //search SYMTAB for LABEL + //if found error = 1 + //else + fprintf(fp2,"%s\t%d\n",label,locctr);//insert{LABEL, LOCCTR} into SYMTAB + } + //search optab for opcode + f = 0; + fseek(fp4,0,SEEK_SET); + while(!feof(fp4)) + { + fscanf(fp4,"%s%s",op,ml_equ); + if(strcmp(opcode,op)==0)//opcode found + { + locctr+=3; + f=1; + break; + } + } + //check if opcode is an assembler directive + if(f==0) + { + if(strcmp(opcode,"WORD")==0) + locctr+=3; + else if(strcmp(opcode,"RESW")==0) + locctr+=(3*(atoi(operand))); + else if(strcmp(opcode,"RESB")==0) + locctr+=(atoi(operand)); + else if(strcmp(opcode,"BYTE")==0) + locctr+=strlen(operand)-3; //since C'' or X'' has to be removed from the string length + //else + // set error + } + + fprintf(fp3,"\t%s\t%s\t%s\n",label,opcode,operand);//write line to intermediate file + fscanf(fp1,"%s%s%s",label,opcode,operand);//read next input line + + } + + fprintf(fp3,"%d\t%s\t%s\t%s\n",locctr,label,opcode,operand);//write last line to intermediate file + +//displaying the output in console + + printf("\n\nThe mnemonic code:\n\n"); + fseek(fp1,0,SEEK_SET); + while((ch=fgetc(fp1))!=EOF) + printf("%c",ch); + + printf("\n\nThe contents of intermediate file :\n\n\t"); + fseek(fp3,0,SEEK_SET); + while((ch = fgetc(fp3))!=EOF) + printf("%c",ch); + + len=locctr-start;//pgm_len = LOCCTR - starting_address + printf("\nThe length of the program is %d.\n\n",len); + + printf("\n\nThe contents of SYMTAB:\n\n"); + fseek(fp2,0,SEEK_SET); + while((ch = fgetc(fp2))!=EOF) + printf("%c",ch); + + fcloseall(); +} diff --git a/Algorithms/C/quick_sort.c b/Algorithms/C/quick_sort.c new file mode 100644 index 00000000..e6e64463 --- /dev/null +++ b/Algorithms/C/quick_sort.c @@ -0,0 +1,83 @@ +//Name : Ayus Das +//Email: ayusdas2000@gmail.com +/* + *This code implementation of Quick sort in C + *language. This program takes the size of the array + *and array elements from the user. +*/ +#include + +// A utility function to swap two elements +void swap(int* a, int* b) +{ + int t = *a; + *a = *b; + *b = t; +} + +/* This function takes last element as pivot, places + the pivot element at its correct position in sorted + array, and places all smaller (smaller than pivot) + to left of pivot and all greater elements to right + of pivot */ +int partition (int arr[], int low, int high) +{ + int pivot = arr[high]; // pivot + int i = (low - 1); // Index of smaller element + + for (int j = low; j <= high- 1; j++) + { + // If current element is smaller than the pivot + if (arr[j] < pivot) + { + i++; // increment index of smaller element + swap(&arr[i], &arr[j]); + } + } + swap(&arr[i + 1], &arr[high]); + return (i + 1); +} + +/* The main function that implements QuickSort + arr[] --> Array to be sorted, + low --> Starting index, + high --> Ending index */ +void quickSort(int arr[], int low, int high) +{ + if (low < high) + { + /* pi is partitioning index, arr[p] is now + at right place */ + int pi = partition(arr, low, high); + + // Separately sort elements before + // partition and after partition + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } +} + +/* Function to print an array */ +void printArray(int arr[], int size) +{ + int i; + for (i=0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +// Driver program to test above functions +int main() +{ + printf("Enter the size of the array: "); + int n; + scanf("%d",&n); + int arr[n]; + printf("Enter the elements: \n"); + for(int i=0;i +#include +#include +#include + +typedef struct linked_list{ + int data; + struct linked_list *prev; + struct linked_list *next; +} linked_list_t; + +typedef struct ctrl_list{ + int size; + linked_list_t *first; +} ctrl_list_t; + +int my_getnbr(char const *str); +int get_nbr_bit(int nbits, int data); +int get_nbr_of_negs(int ac, char * const *av); +linked_list_t *create_list(int first); +linked_list_t *put_in_list(int ac, char * const*av, ctrl_list_t *ctrl); +int radix_sort(int negs, int nbits, ctrl_list_t *ctrl_a, ctrl_list_t *ctrl_b); +void swap_list(ctrl_list_t *list); +void rotate_list(ctrl_list_t *list); +void rev_rotate_list(ctrl_list_t *list); +void kick_first_of_list(ctrl_list_t *ctrl_a, linked_list_t *tmp); +void add_new_first_list(ctrl_list_t *ctrl_b, linked_list_t *tmp); +void push_list(ctrl_list_t *ctrl_a, ctrl_list_t *ctrl_b); + +void test_neg(char const *str, int *neg, int *i, int *signe) +{ + while (str[*i] == '-' || str[*i] == '+') { + if (str[*i] == '-') { + *neg = *neg + 1; + } + *i = *i + 1; + } + *neg = *neg % 2; + if (*neg == 1) { + *signe = 1; + } +} + +int my_getnbr(char const *str) +{ + int i = 0; + int neg = 0; + int signe = -1; + int to_return = 0; + int inter = 0; + + test_neg(str, &neg, &i, &signe); + while (str[i] >= '0' && str[i] <= '9' && str[i] != '\0') { + inter = str[i] - 48; + to_return = to_return * 10; + to_return = to_return - inter; + if (to_return == -2147483648 && signe == -1 || to_return > 0) { + return (0); + } + i = i + 1; + } + to_return = to_return * signe; + return (to_return); +} + +void rotate_list(ctrl_list_t *list) +{ + list->first = list->first->next; +} + +void rev_rotate_list(ctrl_list_t *list) +{ + list->first = list->first->prev; +} + +void kick_first_of_list(ctrl_list_t *ctrl_a, linked_list_t *tmp) +{ + ctrl_a->first = ctrl_a->first->prev; + ctrl_a->first->next = tmp->next; + ctrl_a->first = ctrl_a->first->next; + ctrl_a->first->prev = tmp->prev; +} + +void add_new_first_list(ctrl_list_t *ctrl_b, linked_list_t *tmp) +{ + tmp->next = ctrl_b->first; + tmp->prev = ctrl_b->first->prev; + ctrl_b->first = ctrl_b->first->prev; + ctrl_b->first->next = tmp; + ctrl_b->first = ctrl_b->first->next; + ctrl_b->first = ctrl_b->first->next; + ctrl_b->first->prev = tmp; + ctrl_b->first = ctrl_b->first->prev; +} + +void push_list(ctrl_list_t *ctrl_a, ctrl_list_t *ctrl_b) +{ + linked_list_t *tmp = ctrl_a->first; + + ctrl_a->size = (ctrl_a->size <= 0) ? 0 : ctrl_a->size - 1; + ctrl_b->size += 1; + if (ctrl_a->first == NULL) + return; + if (ctrl_a->size >= 1){ + kick_first_of_list(ctrl_a, tmp); + }else + ctrl_a->first = NULL; + if (ctrl_b->first == NULL){ + tmp->prev = tmp; + tmp->next = tmp; + ctrl_b->first = tmp; + } else { + add_new_first_list(ctrl_b, tmp); + } +} + +linked_list_t *create_list(int first) +{ + linked_list_t *list_init = malloc(sizeof(linked_list_t)); + + list_init->data = first; + list_init->prev = list_init; + list_init->next = list_init; + return(list_init); +} + +int get_nbr_bit(int nbits, int data) +{ + nbits = 0; + for (; data != 0; data >>= 1, nbits += 1); + return (nbits); +} + +int get_nbr_of_negs(int ac, char * const *av) +{ + int compt = 0; + + if (ac < 2) + return (0); + for (int i = 1; i < ac; i += 1){ + compt = (my_getnbr(av[i]) < 0) ? compt += 1 : compt; + } + return (compt); +} + +linked_list_t *put_in_list(int ac, char * const*av, ctrl_list_t *ctrl) +{ + int i = 2; + linked_list_t *elem; + linked_list_t *last = ctrl->first; + + while (i < ac){ + elem = malloc(sizeof(linked_list_t)); + elem->data = my_getnbr(av[i]); + elem->next = ctrl->first; + elem->prev = last; + last->next = elem; + ctrl->first->prev = elem; + last = elem; + i = i + 1; + } + return(ctrl->first); +} + +void swap_list(ctrl_list_t *list) +{ + linked_list_t *tmp = list->first; + linked_list_t *tmp2 = list->first->next; + + list->first = tmp2; + list->first->prev = tmp2->prev; + tmp = tmp2->next; + list->first->next = tmp; +} + +void put_negs_first(ctrl_list_t *ctrl_a, ctrl_list_t *ctrl_b, int negs) +{ + while (ctrl_b->first != NULL){ + push_list(ctrl_b, ctrl_a); + } + for (int i = 0; i < negs; i += 1){ + rev_rotate_list(ctrl_a); + } +} + +int radix_sort(int negs, int nbits, ctrl_list_t *ctrl_a, ctrl_list_t *ctrl_b) +{ + for (int i = 0; i != 32; i += 1){ + for (int size_a = ctrl_a->size; size_a > 0; size_a -= 1){ + if (((ctrl_a->first->data >> i) & 1) == 0){ + push_list(ctrl_a, ctrl_b); + } else if (ctrl_a->first != NULL){ + rotate_list(ctrl_a); + } + } + for (int size_b = ctrl_b->size; size_b > 0; size_b -= 1){ + if (((ctrl_b->first->data >> i) & 1) == 1){ + push_list(ctrl_b, ctrl_a); + } else if (ctrl_b->first != NULL){ + rotate_list(ctrl_b); + } + } + } + put_negs_first(ctrl_a, ctrl_b, negs); +} + +int check_sorted(int ac, char *const *av) +{ + for (int i = 1; i < ac; i += 1){ + if (i > 1 && my_getnbr(av[i - 1]) > my_getnbr(av[i])) + return (1); + } + return (0); +} + +int main(int ac, char * const *av) +{ + linked_list_t *list_a = NULL; + linked_list_t *list_b = NULL; + ctrl_list_t ctrl_a = {ac - 1, list_a}; + ctrl_list_t ctrl_b = {0, list_b}; + int nbits = 0; + int nb_neg = get_nbr_of_negs(ac, av); + + if (ac < 2) + return (84); + list_a = create_list(my_getnbr(av[1])); + ctrl_a.first = list_a; + list_a = put_in_list(ac, av, &ctrl_a); + if (check_sorted(ac, av) == 1){ + radix_sort(nb_neg, nbits, &ctrl_a, &ctrl_b); + } + for (int i = 0; i < ctrl_a.size ; i++, ctrl_a.first=ctrl_a.first->next) + printf("%d ", ctrl_a.first->data); + return (0); +} \ No newline at end of file diff --git a/Algorithms/C/resize.c b/Algorithms/C/resize.c new file mode 100644 index 00000000..7ccd5697 --- /dev/null +++ b/Algorithms/C/resize.c @@ -0,0 +1,99 @@ +// Copies a BMP file + +#include +#include + +#include "bmp.h" //name of your file for resizing purpose. file should be .h + +int main(int argc, char *argv[]) +{ + // ensure proper usage + if (argc != 3) + { + fprintf(stderr, "Usage: copy infile outfile\n"); + return 1; + } + + // remember filenames + char *infile = argv[1]; + char *outfile = argv[2]; + + // open input file + FILE *inptr = fopen(infile, "r"); + if (inptr == NULL) + { + fprintf(stderr, "Could not open %s.\n", infile); + return 2; + } + + // open output file + FILE *outptr = fopen(outfile, "w"); + if (outptr == NULL) + { + fclose(inptr); + fprintf(stderr, "Could not create %s.\n", outfile); + return 3; + } + + // read infile's BITMAPFILEHEADER + BITMAPFILEHEADER bf; + fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr); + + // read infile's BITMAPINFOHEADER + BITMAPINFOHEADER bi; + fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr); + + // ensure infile is (likely) a 24-bit uncompressed BMP 4.0 + if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 || + bi.biBitCount != 24 || bi.biCompression != 0) + { + fclose(outptr); + fclose(inptr); + fprintf(stderr, "Unsupported file format.\n"); + return 4; + } + + // write outfile's BITMAPFILEHEADER + fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr); + + // write outfile's BITMAPINFOHEADER + fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, outptr); + + // determine padding for scanlines + int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4; + + // iterate over infile's scanlines + for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++) + { + // iterate over pixels in scanline + for (int j = 0; j < bi.biWidth; j++) + { + // temporary storage + RGBTRIPLE triple; + + // read RGB triple from infile + fread(&triple, sizeof(RGBTRIPLE), 1, inptr); + + // write RGB triple to outfile + fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr); + } + + // skip over padding, if any + fseek(inptr, padding, SEEK_CUR); + + // then add it back (to demonstrate how) + for (int k = 0; k < padding; k++) + { + fputc(0x00, outptr); + } + } + + // close infile + fclose(inptr); + + // close outfile + fclose(outptr); + + // success + return 0; +} diff --git a/Algorithms/Elixir/selectionSort.exs b/Algorithms/Elixir/selectionSort.exs new file mode 100644 index 00000000..e9fc96d0 --- /dev/null +++ b/Algorithms/Elixir/selectionSort.exs @@ -0,0 +1,30 @@ +defmodule Selection do + def sort(list) when is_list(list) do + do_selection(list, []) + end + + def do_selection([head|[]], acc) do + acc ++ [head] + end + + def do_selection(list, acc) do + min = min(list) + do_selection(:list.delete(min, list), acc ++ [min]) + end + + defp min([first|[second|[]]]) do + smaller(first, second) + end + + defp min([first|[second|tail]]) do + min([smaller(first, second)|tail]) + end + + defp smaller(e1, e2) do + if e1 <= e2 do + e1 + else + e2 + end + end +end \ No newline at end of file diff --git a/Algorithms/Haskell/BubbleSort.hs b/Algorithms/Haskell/BubbleSort.hs new file mode 100644 index 00000000..35a2c6d8 --- /dev/null +++ b/Algorithms/Haskell/BubbleSort.hs @@ -0,0 +1,9 @@ +bubblesort' :: (Ord a) => [a] -> [a] +bubblesort' [] = [] +bubblesort' [x] = [x] +bubblesort' (x:xs) + | x <= head xs = x : bubblesort' xs + | x > head xs = head xs : bubblesort' (x: tail xs) + +bubblesort :: (Ord a) => [a] -> [a] +bubblesort xs = foldl (\acc _ -> bubblesort' acc) xs xs \ No newline at end of file diff --git a/Algorithms/Haskell/binsearch.hs b/Algorithms/Haskell/binsearch.hs new file mode 100644 index 00000000..1aca40b3 --- /dev/null +++ b/Algorithms/Haskell/binsearch.hs @@ -0,0 +1,9 @@ +-- Function which will perform binary search in haskell +binsearch :: [Int] -> Int -> Int -> Int -> Int -- list, value, low, high, return int +binsearch xs value low high + | high < low = -1 + | xs!!mid > value = binsearch xs value low (mid-1) + | xs!!mid < value = binsearch xs value (mid+1) high + | otherwise = mid + where + mid = low + ((high - low) `div` 2) \ No newline at end of file diff --git a/Algorithms/Haskell/dfs.hs b/Algorithms/Haskell/dfs.hs new file mode 100644 index 00000000..256150e3 --- /dev/null +++ b/Algorithms/Haskell/dfs.hs @@ -0,0 +1,19 @@ +data Tree a = Node a (Tree a) (Tree a) | Leaf a | Empty deriving(Show, Read, Eq) + +-- Travel In Order +dfs :: Tree a -> [a] +dfs Empty = [] +dfs (Leaf a) = [a] +dfs (Node a l r) = dfs l ++ [a] ++ dfs r + +-- Travel Pre Order +dfsPreOrder :: Tree a -> [a] +dfsPreOrder Empty = [] +dfsPreOrder (Leaf a) = [a] +dfsPreOrder (Node a l r) = [a] ++ dfsPreOrder l ++ dfsPreOrder r + +-- Travel Post Order +dfsPostOrder :: Tree a -> [a] +dfsPostOrder Empty = [] +dfsPostOrder (Leaf a) = [a] +dfsPostOrder (Node a l r) = dfsPostOrder l ++ dfsPostOrder r ++ [a] \ No newline at end of file diff --git a/Algorithms/Haskell/quicksort.hs b/Algorithms/Haskell/quicksort.hs new file mode 100644 index 00000000..a0789bb4 --- /dev/null +++ b/Algorithms/Haskell/quicksort.hs @@ -0,0 +1,7 @@ +-- Quicksort program in haskell +quicksort :: (Ord a) => [a] -> [a] +quicksort [] = [] +quicksort (x:xs) = + let smallerSorted = quicksort [a | a <- xs, a <= x] + biggerSorted = quicksort [a | a <- xs, a > x] + in smallerSorted ++ [x] ++ biggerSorted \ No newline at end of file diff --git a/Algorithms/Java/HeapSort.java b/Algorithms/Java/HeapSort.java new file mode 100644 index 00000000..b25ce896 --- /dev/null +++ b/Algorithms/Java/HeapSort.java @@ -0,0 +1,67 @@ +public class HeapSort +{ + + public void sort(int arr[]) + { + int n = arr.length; + + // Build max heap + for (int i = n / 2 - 1; i >= 0; i--) { + heapify(arr, n, i); + } + + + // Heap sort + for (int i=n-1; i>=0; i--) + { + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // Heapify root element + heapify(arr, i, 0); + } + } + + void heapify(int arr[], int n, int i) + { + // Find largest among root, left child and right child + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + + if (l < n && arr[l] > arr[largest]) + largest = l; + + if (r < n && arr[r] > arr[largest]) + largest = r; + + // Swap and continue heapifying if root is not largest + if (largest != i) + { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + heapify(arr, n, largest); + } + } + + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i < n; ++i) + System.out.print(arr[i]+" "); + System.out.println(); + } + + public static void main(String args[]) + { + int arr[] = {1,12,9,5,6,10}; + HeapSort hs = new HeapSort(); + hs.sort(arr); + + System.out.println("Sorted array is"); + printArray(arr); + } +} \ No newline at end of file diff --git a/Algorithms/Java/Linear_search.java b/Algorithms/Java/Linear_search.java new file mode 100644 index 00000000..ee8abc9d --- /dev/null +++ b/Algorithms/Java/Linear_search.java @@ -0,0 +1,36 @@ +import java.util.Scanner; + + +public class Linear_search { + static int linear_Search(int arr[],int total_elements,int item_required) + { + for(int i=0;ipivot){ + j--; + } + if(i<=j){ + temp=array[i]; + array[i]=array[j]; + array[j]=temp; + i++; + j--; + } + } + if(lowi){ + quickSort(array,i,high); + } + } + +} + +/***************************************************************************************** + +Time Complexity : O(n^2) + +*****************************************************************************************/ diff --git a/Algorithms/Java/sjf.java b/Algorithms/Java/sjf.java new file mode 100644 index 00000000..4b2d8e45 --- /dev/null +++ b/Algorithms/Java/sjf.java @@ -0,0 +1,243 @@ +import java.util.*; +import java.util.Scanner; +import java.io.*; + +class Process /*implements Comparable*/ +{ + int arr_t, bur_t, comp_t, tat, wait_t, flag, bur_t2, st_t; + int pro_id; + + public Process(int pro_id , int arr_t, int bur_t){ + this.pro_id = pro_id; + this.arr_t = arr_t; + this.bur_t = bur_t; + this.flag=0; + this.bur_t2 = this.bur_t; + } + + /*public int compareTo(Process m) + { + return this.arr_t - m.arr_t; + } */ + + public int getArrTime() { return arr_t; } + + public int getStartTime() { return st_t; } +} + +class Order +{ + int pro_id, st_t, end_t; + + public Order(int pro_id , int st_t, int end_t){ + this.pro_id = pro_id; + this.st_t = st_t; + this.end_t = end_t; + } +} + +class ArrTimeCompare implements Comparator +{ + public int compare(Process p1, Process p2) + { + if (p1.getArrTime() < p2.getArrTime()) return -1; + if (p1.getArrTime() > p2.getArrTime()) return 1; + else return 0; + } +} + +class StartTimeCompare implements Comparator +{ + public int compare(Process p1, Process p2) + { + if (p1.getStartTime() < p2.getStartTime()) return -1; + if (p1.getStartTime() > p2.getStartTime()) return 1; + else return 0; + } +} + +public class sjf +{ + static void nonPreEmptive(List p, int n){ + System.out.println("Non-preemptive version"); + //boolean a = true; + int st=0, tot=0; + float avgwt=0, avgta=0; + while(true) + { + int c=n, min=999; + if (tot == n) // total no of process = completed process loop will be terminated + break; + + for (int i=0; i p, int n){ + System.out.println("Preemptive version"); + List o = new ArrayList(); + int i, st=0, tot=0; + float avgwt=0, avgta=0; + int pre_c = n; + int idle = 0; + while(true){ + int min = 999, c = n; + if (tot == n) + break; + + for (i=0; i p = new ArrayList(); + //Process p[] = new Process[n]; + System.out.print("\nEnter the arrival time and burst time of each process::\n"); + for(int i=0;i 0){ + swap(arr, end--, 0); + DownHeapify(arr, 0, end); + } + return arr; +} + +function heapify(arr, len){ + // breaking the array into root + two sides, to create tree (heap) + var mid = Math.floor((len-2)/2); + while(mid >= 0){ + DownHeapify(arr, mid--, len-1); + } +} + +function DownHeapify(arr, start, end){ + var root = start, + child = root*2 + 1, + toSwap = root; + while(child <= end){ + if(arr[toSwap] < arr[child]){ + swap(arr, toSwap, child); + } + if(child+1 <= end && arr[toSwap] < arr[child+1]){ + swap(arr, toSwap, child+1) + } + if(toSwap != root){ + swap(arr, root, toSwap); + root = toSwap; + } + else{ + return; + } + toSwap = root; + child = root*2+1 + } +} + + +function swap(arr, i, j){ + var temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; +} \ No newline at end of file diff --git a/Algorithms/JavaScript/Insertionsort.js b/Algorithms/JavaScript/Insertionsort.js new file mode 100644 index 00000000..cba0266c --- /dev/null +++ b/Algorithms/JavaScript/Insertionsort.js @@ -0,0 +1,13 @@ +const insertionSort = arr => { + const len = arr.length; + for (let i = 0; i < len; i++) { + let el = arr[i]; + let j; + + for (j = i - 1; j >= 0 && arr[j] > el; j--) { + arr[j + 1] = arr[j]; + } + arr[j + 1] = el; + } + return arr; + }; \ No newline at end of file diff --git a/Algorithms/JavaScript/Quicksort.js b/Algorithms/JavaScript/Quicksort.js new file mode 100644 index 00000000..4a63031c --- /dev/null +++ b/Algorithms/JavaScript/Quicksort.js @@ -0,0 +1,37 @@ +function quickSort(arr, left, right){ + var len = arr.length, + pivot, + partitionIndex; + + + if(left < right){ + pivot = right; + partitionIndex = partition(arr, pivot, left, right); + + //sort left and right + quickSort(arr, left, partitionIndex - 1); + quickSort(arr, partitionIndex + 1, right); + } + return arr; +} + +function partition(arr, pivot, left, right){ + var pivotValue = arr[pivot], + partitionIndex = left; + + for(var i = left; i < right; i++){ + if(arr[i] < pivotValue){ + swap(arr, i, partitionIndex); + partitionIndex++; + } + } + swap(arr, right, partitionIndex); + return partitionIndex; +} + +function swap(arr, i, j){ + var temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; +} + \ No newline at end of file diff --git a/Algorithms/JavaScript/RadixSort.js b/Algorithms/JavaScript/RadixSort.js new file mode 100644 index 00000000..7706595d --- /dev/null +++ b/Algorithms/JavaScript/RadixSort.js @@ -0,0 +1,63 @@ +var testArray = [ 31, 654, 222, 74, 689, 45, 89, 223, 345, 145, 8 ]; + + function radixBucketSort (arr) { + var idx1, idx2, idx3, len1, len2, radix, radixKey; + var radices = {}, buckets = {}, num, curr; + var currLen, radixStr, currBucket; + + len1 = arr.length; + len2 = 10; // radix sort uses ten buckets + + // find the relevant radices to process for efficiency + for (idx1 = 0;idx1 < len1;idx1++) { + radices[arr[idx1].toString().length] = 0; + } + + // loop for each radix. For each radix we put all the items + // in buckets, and then pull them out of the buckets. + for (radix in radices) { + // put each array item in a bucket based on its radix value + len1 = arr.length; + for (idx1 = 0;idx1 < len1;idx1++) { + curr = arr[idx1]; + // item length is used to find its current radix value + currLen = curr.toString().length; + // only put the item in a radix bucket if the item + // key is as long as the radix + if (currLen >= radix) { + // radix starts from beginning of key, so need to + // adjust to get redix values from start of stringified key + radixKey = curr.toString()[currLen - radix]; + // create the bucket if it does not already exist + if (!buckets.hasOwnProperty(radixKey)) { + buckets[radixKey] = []; + } + // put the array value in the bucket + buckets[radixKey].push(curr); + } else { + if (!buckets.hasOwnProperty('0')) { + buckets['0'] = []; + } + buckets['0'].push(curr); + } + } + // for current radix, items are in buckets, now put them + // back in the array based on their buckets + // this index moves us through the array as we insert items + idx1 = 0; + // go through all the buckets + for (idx2 = 0;idx2 < len2;idx2++) { + // only process buckets with items + if (buckets[idx2] != null) { + currBucket = buckets[idx2]; + // insert all bucket items into array + len1 = currBucket.length; + for (idx3 = 0;idx3 < len1;idx3++) { + arr[idx1++] = currBucket[idx3]; + } + } + } + buckets = {}; + } + } + radixBucketSort(testArray); \ No newline at end of file diff --git a/Algorithms/JavaScript/bogoSort.js b/Algorithms/JavaScript/bogoSort.js new file mode 100644 index 00000000..84270705 --- /dev/null +++ b/Algorithms/JavaScript/bogoSort.js @@ -0,0 +1,28 @@ +function isSorted(arr) { + if (arr.length == 0 || arr.length == 1) { + return true; + } + + for (let i=0;i arr[i+1]) { + return false; + } + } + + return true; +} + +function shuffleArray(array) { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [array[i], array[j]] = [array[j], array[i]]; + } + return array; +} + +function bogoSort(data) { + while (!isSorted(data)) { + data = shuffleArray(data); + }; + return data; +} \ No newline at end of file diff --git a/Algorithms/JavaScript/bubbleSort.js b/Algorithms/JavaScript/bubbleSort.js new file mode 100644 index 00000000..09588d27 --- /dev/null +++ b/Algorithms/JavaScript/bubbleSort.js @@ -0,0 +1,15 @@ +const bubbleSort = (numArray) => { + let rotated; + do { + rotated = false; + for (let i = 0; i < numArray.length-1; i++) { + if (numArray[i] > numArray[i+1]) { + store = numArray[i]; + numArray[i] = numArray[i+1]; + numArray[i+1] = store; + rotated = true; + } + } + } while (rotated === true) + return numArray + } diff --git a/Algorithms/JavaScript/countingSort.js b/Algorithms/JavaScript/countingSort.js new file mode 100644 index 00000000..f254168e --- /dev/null +++ b/Algorithms/JavaScript/countingSort.js @@ -0,0 +1,24 @@ +function counntingSort(arr, min, max) { + let i = min, + j = 0, + len = arr.length, + count = []; + + for (i; i <= max; i++) { + count[i] = 0; + } + + for (i = 0; i < len; i++) { + count[arr[i]] += 1; + } + + for (i = min; i <= max; i++) { + while (count[i] > 0) { + arr[j] = i; + j++; + count[i]--; + } + } + + return arr; +} \ No newline at end of file diff --git a/Algorithms/JavaScript/fibonacci-position.js b/Algorithms/JavaScript/fibonacci-position.js new file mode 100644 index 00000000..c3f41fdf --- /dev/null +++ b/Algorithms/JavaScript/fibonacci-position.js @@ -0,0 +1,14 @@ +function fibonacci(position) { + if(position < 3) return 1; + else { + return fibonacci(position - 1) + fibonacci(position - 2); + } +} + +console.log(fibonacci(1)); // 1 +console.log(fibonacci(2)); // 1 +console.log(fibonacci(3)); // 2 +console.log(fibonacci(4)); // 3 +console.log(fibonacci(5)); // 5 +console.log(fibonacci(6)); // 8 +console.log(fibonacci(7)); // 13 diff --git a/Algorithms/JavaScript/fibonnacci.js b/Algorithms/JavaScript/fibonnacci.js new file mode 100644 index 00000000..afff9f8a --- /dev/null +++ b/Algorithms/JavaScript/fibonnacci.js @@ -0,0 +1,16 @@ +function fibonacci (num, cache) { + cache = cache || {}; + if (cache[num]) return cache[num]; + if (num <= 1) return 1; + return cache[num] = fibonacci(num - 1, cache) + fibonacci(num - 2, cache); +} + + +console.log(fibonacci(6)) // 13 +console.log(fibonacci(5)) // 8 +console.log(fibonacci(4)) // 5 +console.log(fibonacci(3)) // 3 +console.log(fibonacci(2)) // 2 +console.log(fibonacci(1)) // 1 +console.log(fibonacci(0)) // 1 + diff --git a/Algorithms/JavaScript/fizzBuzz.js b/Algorithms/JavaScript/fizzBuzz.js new file mode 100644 index 00000000..8f28f513 --- /dev/null +++ b/Algorithms/JavaScript/fizzBuzz.js @@ -0,0 +1,18 @@ +function fizzbuzz(num) { + for(let i=1; i<=num; i++) { + if(i%3 === 0 && i%5 === 0) { + console.log("FizzBuzz"); + } else if(i%3 === 0) { + console.log("Fizz"); + } else if(i%5 === 0) { + console.log("Buzz"); + } else { + console.log(i); + } + } +} + +fizzbuzz(20); +fizzbuzz(30); +fizzbuzz(40); +fizzbuzz(50); diff --git a/Algorithms/JavaScript/leastCommonMultiple.js b/Algorithms/JavaScript/leastCommonMultiple.js new file mode 100644 index 00000000..9c4f0dea --- /dev/null +++ b/Algorithms/JavaScript/leastCommonMultiple.js @@ -0,0 +1,17 @@ +const leastCommonMultiple = (a,b) => { + let x = a; + let y = b + while(x !== y) { + if(x>y){ + x = x - y; + } + else { + y = y - x; + } + } + return (a * b) / x; +} + +//examples +// leastCommonMultiple(2,3); +// leastCommonMultiple(192,348); \ No newline at end of file diff --git a/Algorithms/JavaScript/mergeSort.js b/Algorithms/JavaScript/mergeSort.js new file mode 100644 index 00000000..99afae46 --- /dev/null +++ b/Algorithms/JavaScript/mergeSort.js @@ -0,0 +1,44 @@ + +// Merge the two arrays: left and right +function merge (left, right) { + let resultArray = [], leftIndex = 0, rightIndex = 0; + + // We will concatenate values into the resultArray in order + while (leftIndex < left.length && rightIndex < right.length) { + if (left[leftIndex] < right[rightIndex]) { + resultArray.push(left[leftIndex]); + leftIndex++; // move left array cursor + } else { + resultArray.push(right[rightIndex]); + rightIndex++; // move right array cursor + } + } + + // We need to concat here because there will be one element remaining + // from either left OR the right + return resultArray + .concat(left.slice(leftIndex)) + .concat(right.slice(rightIndex)); +} + +// Merge Sort Implentation (Recursion) +function mergeSort (unsortedArray) { + // No need to sort the array if the array only has one element or empty + if (unsortedArray.length <= 1) { + return unsortedArray; + } + // In order to divide the array in half, we need to figure out the middle + const middle = Math.floor(unsortedArray.length / 2); + + // This is where we will be dividing the array into left and right + const left = unsortedArray.slice(0, middle); + const right = unsortedArray.slice(middle); + + // Using recursion to combine the left and right + return merge( + mergeSort(left), mergeSort(right) + ); +} + +let a = [10,233,14,1675,85,653,809,85] +console.log(mergeSort(a)); diff --git a/Algorithms/JavaScript/palindrome.js b/Algorithms/JavaScript/palindrome.js new file mode 100644 index 00000000..f0f21aae --- /dev/null +++ b/Algorithms/JavaScript/palindrome.js @@ -0,0 +1,15 @@ +function isPalindrome(str) { + str = str.toLowerCase(); + let strArr = str.split(/\W/); + let newStr = strArr.join(''); + + if(newStr === newStr.split('').reverse().join('')) { + console.log(true); + } else { + console.log(false); + } +} + +isPalindrome("Madam, I'm Adam"); // true +isPalindrome("racecar"); // true +isPalindrome("hacktoberfest"); // false diff --git a/Algorithms/JavaScript/selectionSort.js b/Algorithms/JavaScript/selectionSort.js new file mode 100644 index 00000000..4397c43e --- /dev/null +++ b/Algorithms/JavaScript/selectionSort.js @@ -0,0 +1,20 @@ +function selectionSort(A) { + var len = array_length(A); + for (var i = 0; i < len - 1; i = i + 1) { + var j_min = i; + for (var j = i + 1; j < len; j = j + 1) { + if (A[j] < A[j_min]) { + j_min = j; + } else {} + } + if (j_min !== i) { + swap(A, i, j_min); + } else {} + } +} + +function swap(A, x, y) { + var temp = A[x]; + A[x] = A[y]; + A[y] = temp; +} \ No newline at end of file diff --git a/Algorithms/Kotlin/BubbleSort.kt b/Algorithms/Kotlin/BubbleSort.kt new file mode 100644 index 00000000..1527ee3d --- /dev/null +++ b/Algorithms/Kotlin/BubbleSort.kt @@ -0,0 +1,53 @@ +import java.util.* + +fun input(): Array{ + //instance of Scanner class + val reader: Scanner = Scanner(System.`in`) + + //creating the array + println("enter size of array : ") + var size:Int=reader.nextInt() + var myArray=Array(size){0} + + //initializing the array + for (i in 0..(size-1)){ + print("\nEnter element : ") + myArray.set(i,reader.nextInt()) + } + + return myArray +} + +fun display(myArray: Array){ + for (element in myArray) + print(" "+ element) +} + +fun main(args: Array){ + var array=input() + println("array before sorting : ") + display(array) + array=bubbleSort(array) + println("\narray after sorting : ") + display(array) + +} + +fun bubbleSort(array: Array): Array { + + for(i in 0..(array.size-2)) + for (j in 0..(array.size-2-i)){ + if(array.get(j+1) arr[largest]) + largest = l + + // If right child is larger than largest so far + if (r < n && arr[r] > arr[largest]) + largest = r + + // If largest is not root + if (largest != i) { + val swap = arr[i] + arr[i] = arr[largest] + arr[largest] = swap + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest) + } + } + + companion object { + + /* A utility function to print array of size n */ + internal fun printArray(arr: IntArray) { + val n = arr.size + for (i in 0 until n) + print(arr[i].toString() + " ") + println() + } + + // Driver program + @JvmStatic + fun main(args: Array) { + val arr = intArrayOf(12, 11, 13, 5, 6, 7) + val n = arr.size + + val ob = HeapSort() + ob.sort(arr) + + println("Sorted array is") + printArray(arr) + } + } +} \ No newline at end of file diff --git a/Algorithms/Kotlin/MergeSort.kt b/Algorithms/Kotlin/MergeSort.kt new file mode 100644 index 00000000..cbc488fb --- /dev/null +++ b/Algorithms/Kotlin/MergeSort.kt @@ -0,0 +1,51 @@ +/** + * Created by jens on 3/8/17. + */ + +fun mergeSort(list: List): List { + if (list.size <= 1) { + return list + } + + val middle = list.size / 2 + var left = list.subList(0,middle); + var right = list.subList(middle,list.size); + + return merge(mergeSort(left), mergeSort(right)) +} + + +fun merge(left: List, right: List): List { + var indexLeft = 0 + var indexRight = 0 + var newList : MutableList = mutableListOf() + + while (indexLeft < left.count() && indexRight < right.count()) { + if (left[indexLeft] <= right[indexRight]) { + newList.add(left[indexLeft]) + indexLeft++ + } else { + newList.add(right[indexRight]) + indexRight++ + } + } + + while (indexLeft < left.size) { + newList.add(left[indexLeft]) + indexLeft++ + } + + while (indexRight < right.size) { + newList.add(right[indexRight]) + indexRight++ + } + + return newList; +} + +fun main(args: Array) { + val numbers = mutableListOf(38,27,43,3,9,82,10) + val sortedList = mergeSort(numbers) + println("Unsorted: $numbers") + println("Sorted: $sortedList") +} \ No newline at end of file diff --git a/Algorithms/Kotlin/QuickSort.kt b/Algorithms/Kotlin/QuickSort.kt new file mode 100644 index 00000000..a2522d1b --- /dev/null +++ b/Algorithms/Kotlin/QuickSort.kt @@ -0,0 +1,39 @@ +fun main(args: Array) { + val array = readLine()!!.split(" ").map { it.toInt() }.toIntArray() + quickSort(array, 0, array.size-1) + for(i in array) println(i) +} + +fun quickSort(array: IntArray, left: Int, right: Int) { + val index = partition (array, left, right) + if(left < index-1) { + quickSort(array, left, index-1) + } + if(index < right) { + quickSort(array,index, right) + } +} + +fun partition(array: IntArray, l: Int, r: Int): Int { + var left = l + var right = r + val pivot = array[(left + right)/2] + while (left <= right) { + while (array[left] < pivot) left++ + + while (array[right] > pivot) right-- + + if (left <= right) { + swapArray(array, left,right) + left++ + right-- + } + } + return left +} + +fun swapArray(a: IntArray, b: Int, c: Int) { + val temp = a[b] + a[b] = a[c] + a[c] = temp +} diff --git a/Algorithms/Kotlin/insertionSort.kt b/Algorithms/Kotlin/insertionSort.kt new file mode 100644 index 00000000..31e3c62f --- /dev/null +++ b/Algorithms/Kotlin/insertionSort.kt @@ -0,0 +1,24 @@ +import java.util.* + +fun insertionsort(items:MutableList):List{ + if (items.isEmpty() || items.size<2){ + return items + } + for (count in 1..items.count() - 1){ + // println(items) + val item = items[count] + var i = count + while (i>0 && item < items[i - 1]){ + items[i] = items[i - 1] + i -= 1 + } + items[i] = item + } + return items +} +fun main(args: Array) { + val names = mutableListOf(8, 3, 2, 7, 4) + println(names) + var ordered = insertionsort(names) + println(ordered) +} diff --git a/Algorithms/Kotlin/selectionSort.kt b/Algorithms/Kotlin/selectionSort.kt new file mode 100644 index 00000000..b80366c7 --- /dev/null +++ b/Algorithms/Kotlin/selectionSort.kt @@ -0,0 +1,16 @@ +fun selectionSort(A:Array){ + var n = A.size + var temp: Int + for(i in n-1 downTo 0){ + var max = i + for(j in 0 until i){ + if(A[j] > A[max]) + max = j + } + if(i != max){ + temp = A[i] + A[i]= A[max] + A[max] = temp + } + } +} diff --git a/Algorithms/PHP/fibonacci.php b/Algorithms/PHP/fibonacci.php new file mode 100644 index 00000000..70fff1fd --- /dev/null +++ b/Algorithms/PHP/fibonacci.php @@ -0,0 +1,12 @@ +"; +} +?> diff --git a/Algorithms/PHP/kadanealgo.php b/Algorithms/PHP/kadanealgo.php new file mode 100644 index 00000000..fc5d3ade --- /dev/null +++ b/Algorithms/PHP/kadanealgo.php @@ -0,0 +1,22 @@ + \ No newline at end of file diff --git a/Algorithms/PHP/primeNumbers.php b/Algorithms/PHP/primeNumbers.php new file mode 100644 index 00000000..2e2b6f5e --- /dev/null +++ b/Algorithms/PHP/primeNumbers.php @@ -0,0 +1,15 @@ +1;$x--) + { + if($i%$x==0) + { + $o=false; + break; + } + } + if($o) echo $i."
"; +} +?> diff --git a/Algorithms/Python/Backtracking.py b/Algorithms/Python/Backtracking.py new file mode 100644 index 00000000..3ff477ce --- /dev/null +++ b/Algorithms/Python/Backtracking.py @@ -0,0 +1,35 @@ +def A_n_k(a, n, k, depth, used, curr, ans): + ''' + Implement permutation of k items out of n items + depth: start from 0, and represent the depth of the search + used: track what items are in the partial solution from the set of n + curr: the current partial solution + ans: collect all the valide solutions + ''' + if depth == k: #end condition + ans.append(curr[::]) # use deepcopy because curr is tracking all partial solution, it eventually become [] + return + + for i in range(n): + if not used[i]: + # generate the next solution from curr + curr.append(a[i]) + used[i] = True + print(curr) + # move to the next solution + A_n_k(a, n, k, depth+1, used, curr, ans) + + #backtrack to previous partial state + curr.pop() + print('backtrack: ', curr) + used[i] = False + return + +a = list(map(int, input("Enter the numbers = ").split())) +n = len(a) +ans = [] +used = [False] * len(a) +ans = [] +A_n_k(a, n, n, 0, used, [], ans) +print(ans) + diff --git a/Algorithms/Python/RadixSort.py b/Algorithms/Python/RadixSort.py new file mode 100644 index 00000000..fb29faec --- /dev/null +++ b/Algorithms/Python/RadixSort.py @@ -0,0 +1,63 @@ + +edit +play_arrow + +brightness_4 +# Python program for implementation of Radix Sort + +# A function to do counting sort of arr[] according to +# the digit represented by exp. +def countingSort(arr, exp1): + + n = len(arr) + + # The output array elements that will have sorted arr + output = [0] * (n) + + # initialize count array as 0 + count = [0] * (10) + + # Store count of occurrences in count[] + for i in range(0, n): + index = (arr[i]/exp1) + count[ (index)%10 ] += 1 + + # Change count[i] so that count[i] now contains actual + # position of this digit in output array + for i in range(1,10): + count[i] += count[i-1] + + # Build the output array + i = n-1 + while i>=0: + index = (arr[i]/exp1) + output[ count[ (index)%10 ] - 1] = arr[i] + count[ (index)%10 ] -= 1 + i -= 1 + + # Copying the output array to arr[], + # so that arr now contains sorted numbers + i = 0 + for i in range(0,len(arr)): + arr[i] = output[i] + +# Method to do Radix Sort +def radixSort(arr): + + # Find the maximum number to know number of digits + max1 = max(arr) + + # Do counting sort for every digit. Note that instead + # of passing digit number, exp is passed. exp is 10^i + # where i is current digit number + exp = 1 + while max1/exp > 0: + countingSort(arr,exp) + exp *= 10 + +# Driver code to test above +arr = [ 170, 45, 75, 90, 802, 24, 2, 66] +radixSort(arr) + +for i in range(len(arr)): + print(arr[i]), \ No newline at end of file diff --git a/Algorithms/Python/SlidingWindowMinMax.py b/Algorithms/Python/SlidingWindowMinMax.py new file mode 100644 index 00000000..2c143f6e --- /dev/null +++ b/Algorithms/Python/SlidingWindowMinMax.py @@ -0,0 +1,78 @@ +# Sliding window technique for finding max/ min window sum +# Integer array and window size are randomly generated +# Done in a Pythonic way + +import random +import math + +def slidingWindowFind(minmax, data, winSize): + # Check for invalid window size + if (len(data) < winSize): + print("Cannot perform sliding window - window size must be less than array length") + return None + + ret = None + + # Sum up the first window + if (minmax == 0): + print("Finding the minimum window") + print("\t Array: " + str(data)) + print("\t Window size: " + str(winSize)) + + # Starting min value is infinity + ret = float("inf") + + # Sliding window + for i in range(winSize, len(data)): + # Slide window forward by 1 element each time + currentSum = sum(data[i-winSize:i]) + print("Current window: " + str(data[i-winSize:i])) + print("Window sum: " + str(currentSum)) + print("Current min: " + str(ret)) + + ret = min(ret, currentSum) + + elif(minmax == 1): + print("Finding the maximum window") + print("\t Array: " + str(data)) + print("\t Window size: " + str(winSize)) + + # Starting min value is negative infinity + ret = float("-inf") + + # Sliding window + for i in range(winSize, len(data)): + # Slide window forward by 1 element each time + currentSum = sum(data[i-winSize:i]) + print("Current window: " + str(data[i-winSize:i])) + print("Window sum: " + str(currentSum)) + print("Current max: " + str(ret)) + + ret = max(ret, currentSum) + + else: + print("Invalid sliding window option - use 0 for min, and 1 for max") + return None + + return ret + + +if __name__== "__main__": + array = [] + + # Generate random array with random length between 10 and 20 elements + for i in range(random.randint(9,20)): + array.append(random.randint(1, 11)) # Append random number between 1 and 10 + + winSize = random.randint(2, 6) # Generate random window size between 2 and 5 + + print("Run sliding window to find max and min...") + minVal = slidingWindowFind(0, array, winSize) + print("\n") + maxVal = slidingWindowFind(1, array, winSize) + + print("\nMinimum sum:" + str(minVal)) + print("Maximum sum:" + str(maxVal)) + + + \ No newline at end of file diff --git a/Algorithms/Python/bubbleSort.py b/Algorithms/Python/bubbleSort.py new file mode 100644 index 00000000..d5e796e8 --- /dev/null +++ b/Algorithms/Python/bubbleSort.py @@ -0,0 +1,16 @@ +# bubble sort + +# test numbers +toSort = [3, 7, 2, 6, 4] + +# perform bubble sort +for i in range(5): + for j in range(4): + if toSort[j] > toSort[j+1]: + temp = toSort[j] + toSort[j] = toSort[j + 1] + toSort[j + 1] = temp + +# print sorted list +for x in toSort: + print(x) diff --git a/Algorithms/Python/linear_Search.py b/Algorithms/Python/linear_Search.py new file mode 100644 index 00000000..918981e6 --- /dev/null +++ b/Algorithms/Python/linear_Search.py @@ -0,0 +1,39 @@ +#python code for linear search +MAX = 20 +#array of items on which linear search will be conducted. +intArray = [1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66] +def printline(count): + for i in range(count-1): + print("=", end="") + print("=") +#this method makes a linear search. +def find(data): + comparisons = 0 + index = -1 + #navigate through all items + for i in range(MAX): + #count the comparisons made + comparisons += 1 + + #if data found, break the loop + if data == intArray[i]: + index = i + break + print("Total comparisons made:", comparisons) + return index +def display(): + print("[", end="") + #navigate through all items + for i in range(MAX): + print(intArray[i], end=" ") + print("]") +print("Input Array: ", end="") +display() +printline(50) +#find location of 1 +location = find(55) +#if element was found +if location != -1: + print("\nElement found at location:", location+1) +else: + print("Element not found.") \ No newline at end of file diff --git a/Algorithms/Python/mergesort.py b/Algorithms/Python/mergesort.py old mode 100755 new mode 100644 index 88cdd7d8..75af1fd7 --- a/Algorithms/Python/mergesort.py +++ b/Algorithms/Python/mergesort.py @@ -1,36 +1,36 @@ -def merge(left, right): - li, ri = 0, 0 - retval = [] - while li < len(left) and ri < len(right): - if left[li] < right[ri]: - retval.append(left[li]) - li += 1 - else: - retval.append(right[ri]) - ri += 1 - - retval += left[li:] - retval += right[ri:] - return retval - - -def merge_sort(array): - # base case - if len(array) <= 1: - return array - - # divide array in half and do recursion - half = len(array) // 2 - left = merge_sort(array[:half]) - right = merge_sort(array[half:]) - - return merge(left, right) - - -def sort(): - list = [5, 7, 6, 2, 1, 7, 3] - sorted_list = merge_sort(list) - print 'Array after sorting: ', sorted_list - -if __name__ == '__main__': +def merge(left, right): + li, ri = 0, 0 + retval = [] + while li < len(left) and ri < len(right): + if left[li] < right[ri]: + retval.append(left[li]) + li += 1 + else: + retval.append(right[ri]) + ri += 1 + + retval += left[li:] + retval += right[ri:] + return retval + + +def merge_sort(array): + # base case + if len(array) <= 1: + return array + + # divide array in half and do recursion + half = len(array) // 2 + left = merge_sort(array[:half]) + right = merge_sort(array[half:]) + + return merge(left, right) + + +def sort(): + list = [5, 7, 6, 2, 1, 7, 3] + sorted_list = merge_sort(list) + print 'Array after sorting: ', sorted_list + +if __name__ == '__main__': sort() \ No newline at end of file diff --git a/Algorithms/Python/selection_sort.py b/Algorithms/Python/selection_sort.py new file mode 100644 index 00000000..b4b9eb11 --- /dev/null +++ b/Algorithms/Python/selection_sort.py @@ -0,0 +1,14 @@ +import sys +A = [64, 25, 12, 22, 11] + +for i in range(len(A)): + min_idx = i + for j in range(i+1, len(A)): + if A[min_idx] > A[j]: + min_idx = j + + A[i], A[min_idx] = A[min_idx], A[i] + +print ("Sorted array") +for i in range(len(A)): + print("%d" %A[i]), diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c91f5e1a..05ef4c49 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,5 +8,5 @@ - For example ```Java/sieve.java```. ## Problem Solutions -- You can directly add the problem solutions to corresponding platform folder. File name should be the ID of the problem on particular plateform. -- If plateform folder doesn't exist then write file name as ```Plateform/file.lang``` where ```Plateform``` is the name of the plateform and ```file.lang``` is the name of file. +- You can directly add the problem solutions to corresponding platform folder. File name should be the ID of the problem on particular platform. +- If platform folder doesn't exist then write file name as ```Platform/file.lang``` where ```Platform``` is the name of the platform and ```file.lang``` is the name of file. diff --git a/CodeWars/Ruby/Bf/fibonacci-sequence.bf b/CodeWars/Ruby/Bf/fibonacci-sequence.bf new file mode 100644 index 00000000..ac49cab5 --- /dev/null +++ b/CodeWars/Ruby/Bf/fibonacci-sequence.bf @@ -0,0 +1,15 @@ +[ Compute (and print) the first + 11 elements of the Fibonacci Sequence + 1, 1, 2, 3, 5, ... ] + ++++++++++++ +>+>>>>++++++++++++++++++++++++++++++++++++++++++++ +>++++++++++++++++++++++++++++++++<<<<<<[>[>>>>>>+> ++<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<[>++++++++++[- +<-[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<[>>>+<<< +-]>>[-]]<<]>>>[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]] +>[<<+>>[-]]<<<<<<<]>>>>>[+++++++++++++++++++++++++ ++++++++++++++++++++++++.[-]]++++++++++<[->-<]>++++ +++++++++++++++++++++++++++++++++++++++++++++.[-]<< +<<<<<<<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<-[>>.>.<<< +[-]]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[<+>-]>[<+>-]<<<-] diff --git a/CodeWars/Ruby/find-the-parity-outlier b/CodeWars/Ruby/find-the-parity-outlier new file mode 100644 index 00000000..f2ee7725 --- /dev/null +++ b/CodeWars/Ruby/find-the-parity-outlier @@ -0,0 +1,11 @@ +def find_outlier(integers) + even = integers.each.select {|el| el.even?} + odd = integers.each.select {|el| el.odd?} + + if even.length < odd.length + outlier = even.join.to_i + else + outlier = odd.join.to_i + end + return outlier +end diff --git a/CodeWars/Ruby/find-unique-number.rb b/CodeWars/Ruby/find-unique-number.rb new file mode 100644 index 00000000..5179c18a --- /dev/null +++ b/CodeWars/Ruby/find-unique-number.rb @@ -0,0 +1,16 @@ +def find_uniq(arr) + new_arr = arr.dup + match = new_arr.uniq[1] + alt = new_arr.uniq[0] + count = 0 + arr.each do |x| + unless x == match + count += 1 + end + end + if count > 1 + match + else + alt + end +end diff --git a/CodeWars/Ruby/gematria-for-all b/CodeWars/Ruby/gematria-for-all new file mode 100644 index 00000000..258d4317 --- /dev/null +++ b/CodeWars/Ruby/gematria-for-all @@ -0,0 +1,42 @@ +# gematria-for-all - Chance Cantrell + +def gematria(string) + hash = { + :a => 1, + :b => 2, + :c => 3, + :d => 4, + :e => 5, + :f => 6, + :g => 7, + :h => 8, + :i => 9, + :k => 10, + :l => 20, + :m => 30, + :n => 40, + :o => 50, + :p => 60, + :q => 70, + :r => 80, + :s => 90, + :t => 100, + :u => 200, + :x => 300, + :y => 400, + :z => 500, + :j => 600, + :v => 700, + :w => 900 + } + + str = string.delete(' ').split('') + value = [] + + str.each do |x| + if x.match(/[a-zA-Z]/) + value << hash[:"#{x.downcase}"] + end + end + value.sum +end diff --git a/CodeWars/Ruby/rot13 b/CodeWars/Ruby/rot13 new file mode 100644 index 00000000..b3d869d4 --- /dev/null +++ b/CodeWars/Ruby/rot13 @@ -0,0 +1,15 @@ +# rot13 - Chance Cantrell + +def rot13(string) + decrypted = "" + shift = 13 + encrypt = ([*('a'..'z')].zip([*('a'..'z')].rotate(shift)) + [*('A'..'Z')].zip([*('A'..'Z')].rotate(shift))).to_h + string.chars.map do |char| + if char.match?(/[a-zA-Z]/) + decrypted << encrypt.fetch(char, " ") + else + decrypted << char + end + end + decrypted +end diff --git a/Codechef/ALPHABET.c b/Codechef/ALPHABET.c new file mode 100644 index 00000000..5b23234b --- /dev/null +++ b/Codechef/ALPHABET.c @@ -0,0 +1,41 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + char s[30],str[15]; + scanf("%s",&s); + int x = strlen(s); + int t; + scanf("%d",&t); + + while(t--) + { + scanf("%s",&str); + int i,j; + int l=strlen(str); + for(i=0;i=strlen(s)) + { + printf("No\n"); + break; + } + } + if(i>=strlen(str)) + { + printf("Yes\n"); + } + } + + return 0; +} + diff --git a/Codechef/ALTARAY.java b/Codechef/ALTARAY.java new file mode 100644 index 00000000..1d80c0f1 --- /dev/null +++ b/Codechef/ALTARAY.java @@ -0,0 +1,45 @@ +import java.util.*; +class DP +{ + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + int t=sc.nextInt(); + if(t>10 || t<1) + { + return ; + } + for(int i=1;i<=t;i++) + { + int n=sc.nextInt(); + if(n<1 || n>100000) + return; + long a[]=new long[n]; + for(int j=0;j(long)Math.pow(10,9) || a[j]<-(long)Math.pow(10,9)) + return; + } + int length[]=new int[n]; + length[n-1]=1; + count(a,length,a.length-2); + for(int j=0;j0) + length[i]=1; + count(a,length,i-1); + } +} + \ No newline at end of file diff --git a/Codechef/BIT2B.cpp b/Codechef/BIT2B.cpp new file mode 100644 index 00000000..241e7229 --- /dev/null +++ b/Codechef/BIT2B.cpp @@ -0,0 +1,151 @@ +#include + +using namespace std; + +#define fast_cin() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); +#define MAX 1000000 +#define ll long long +#define db double +#define str string +#define pb push_back +#define For(i,s,e) for (ll i=(s); i<(e); i++) +#define Forrev(i,s,e) for (ll i=(s); i>=(e); i--) +#define all(v) v.begin(),v.end() + +#define vll vector +#define vs vector +#define mapll map +#define pll pair +#define initialise(a, x) memset(a, x, sizeof(a)) +#define maxheap priority_queue +#define minheap priority_queue ,greater> + +#define ff first +#define ss second +#define endl "\n" +#define mp make_pair +const ll mod=1e9 + 7; + +ll takemod(ll a) { + return ((a%mod)+mod)%mod; +} + +ll gcd(ll a, ll b) { + if (b == 0) + return a; + return gcd(b, a % b); +} + +ll fast_exp(ll base, ll expo) { + ll res=1; + while(expo>0) { + if(expo&1) res=(res*base)%mod; + base=(base*base)%mod; + expo>>=1;} + return res; +} + +ll modinv(ll a) { + return takemod(fast_exp(takemod(a), mod-2)); +} + + +signed main() +{ + fast_cin(); + #ifndef ONLINE_JUDGE + freopen("C:/IO/in.txt", "r", stdin); + freopen("C:/IO/out.txt", "w", stdout); + #endif + ll t,n; + cin>>t; + For(l,0,t) + { + cin>>n; + ll arr[n]; + For(i,0,n) + { + cin>>arr[i]; + } + + ll x; + cin>>x; + + ll i=0,j=n-1,sum1=0,sum2=0; + ll sumarr[n]; + memset(sumarr,0,sizeof(sumarr)); + + ll markarr[n]; + memset(markarr,-1,sizeof(markarr)); + + while(i<=j) + { + if(i==j) + { + if(markarr[i]!=-1) + break; + ll ans1=0,ans2=0; + For(k,0,n) + { + //cout<=ans2) + { + markarr[i]=1; + i++; + } + else + { + markarr[i]=2; + j--; + } + } + else + { + sum1=0,sum2=0; + sum2=arr[j]; + markarr[j]=2; + while(ix*sum2) + { + sumarr[i]+=x*sum2-sum1; + sum1=sum2; + markarr[i]=1; + if(sumarr[i]==arr[i]) + i++; + break; + } + else + { + sum1+=arr[i]-sumarr[i]; + markarr[i]=1; + i++; + } + } + j--; + //cout< +using namespace std; + +//important constants +#define pi M_PI +#define mod 1000000007 +#define maX(a,b) ((a)>(b)?(a):(b)) +#define miN(a,b) ((a)<(b)?(a):(b)) + +#ifdef ONLINE_JUDGE +#define MAX 200005 +#else +#define MAX 100000 +#endif + +int a[MAX],b[MAX]; +char s[MAX],r[MAX]; +int test; + +int main(){ + #ifndef ONLINE_JUDGE + freopen("input.txt","r",stdin); + // freopen("output.txt","w",stdout); + #endif + + int t,n,m,k,l,x,y,z,flag,count,d,mx,mn; + long long int sum,prod; + + scanf("%d",&test); + + while(test--){ + flag=0; + // scanf("%d",&n); + scanf("%d%d",&n,&m); + + if(n%2 && m%2){ + if(abs(n-m)==2) + flag=1; + }else if(n%2){ + if(m-n==1) + flag=1; + }else if(m%2){ + if(n-m==1) + flag=1; + }else{ + if(abs(n-m)==2) + flag=1; + } + if(flag) printf("YES\n"); + else printf("NO\n"); + + } + return 0; +} diff --git a/Codechef/CANDY123.c b/Codechef/CANDY123.c new file mode 100644 index 00000000..9d1f0687 --- /dev/null +++ b/Codechef/CANDY123.c @@ -0,0 +1,39 @@ +//Author: Rakshit Naidu + +#include +int func(int x,int y,int r); + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int a,b; + scanf("%d %d",&a,&b); + int rem=2; + func(a,b,rem); + } + return 0; +} +int func(int x,int y,int r) +{ + x = x - (r/2); + r++; + r++; + if(x<0) + { + printf("Bob\n"); + return; + } + y = y - (r/2); + r++; + r++; + if(y<0) + { + printf("Limak\n"); + return; + } + return func(x,y,r); +} diff --git a/Codechef/CHCHCL.c b/Codechef/CHCHCL.c new file mode 100644 index 00000000..d9a87d58 --- /dev/null +++ b/Codechef/CHCHCL.c @@ -0,0 +1,26 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int m,n; + scanf("%d %d",&m,&n); + + if(m%2==0||n%2==0) + { + printf("Yes\n"); + } + else + { + printf("No\n"); + } + } + return 0; +} + diff --git a/Codechef/CHEFADV.cpp b/Codechef/CHEFADV.cpp new file mode 100644 index 00000000..0f4205bd --- /dev/null +++ b/Codechef/CHEFADV.cpp @@ -0,0 +1,36 @@ +#include +#define ll long long +#define ull unsigned long long +#define vi vector +#define pp pair +#define mp make_pair +#define PI acos(-1.0) +#define all(v) v.begin(),v.end() +#define pb push_back +#define INF 1e18 +#define MOD 1000000007 +using namespace std; +int main() +{ + ll t; + cin>>t; + while(t--) + { + ll n,m,x,y,p=1,k=1,p1,k1,p2,k2; + cin>>n>>m>>x>>y; + k1=1+((n-1)/x)*x; + p1=1+((m-1)/y)*y; + k2=k1;p2=p1; + if(k1-x>1) + k2=k1-x; + if(p1-y>1) + p2=p1-y; + if(((k==n)&&(p==m))||((k==n)&&(p1==m))||((k==n)&&(p2==m))||((k1==n)&&(p==m))||((k1==n)&&(p1==m))||((k1==n)&&(p2==m))||((k2==n)&&(p==m))||((k2==n)&&(p1==m))||((k2==n)&&(p2==m))) + cout<<"Chefirnemo"; + else if(((k==n-1)&&(p==m-1))||((k==n-1)&&(p1==m-1))||((k==n-1)&&(p2==m-1))||((k1==n-1)&&(p==m-1))||((k1==n-1)&&(p1==m-1))||((k1==n-1)&&(p2==m-1))||((k2==n-1)&&(p==m-1))||((k2==n-1)&&(p1==m-1))||((k2==n-1)&&(p2==m-1))) + cout<<"Chefirnemo"; + else + cout<<"Pofik"; + cout< +using namespace std; + +int main() { + int t,n,flag; + cin>>t; + for(int i=0;i>n; + int sum=0,a[n]; + flag = 0; + for(int j=0;j>a[j]; + if(a[j]==0){ + sum=sum+1000; + flag=1; + } + if(flag==1){ + sum=sum+100; + } + } + cout< +using namespace std; +int main() +{ + int t,n; + cin>>t; + while(t) + { int cnt=0; + cin>>n; + int a[26]={0}; + bool f[26]; + memset(f,false,sizeof(f)); + for(int i=0;i>s; + int l=s.length(); + for(int j=0;j + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n1; + scanf("%d",&n1); + + int a[n1]; + for(int i=0;i20) + return; + int c[][]=new int[t][2]; + int count1=0,count2=0,count3=0,max=0,min=0,sum=0; + for(int i=1;i<=t;i++) + { + max=0;min=0;count1=0;count2=0;count3=0; + int n=sc.nextInt(); + + if(n<1 || n>100000) + continue; + sum+=n; + int a[]=new int[n]; + + for( j=0;jMath.pow(10,9)) + continue; + } + + + for(j=0;j0) + count1++; + + else if(a[j]<0) + count2++; + + else count3++; + + if(count1!=0 && count2!=0) + { + if(count3!=0) + { + if(count1>count2) + {max=count1+count3; + min=count2;} + else + {max=count2+count3; + min=count1; + } + } + else + { + if(count1>count2) + { + max=count1; + min=count2; + } + else + { + max=count2; + min=count1; + } + } + } + else + { + if(count1!=0) + { + max=count1;min=count1; + } + if(count2!=0) + { + max=count2;min=count2; + } + + } + + c[i-1][0]=max; + c[i-1][1]=min; + + } + if(sum<=500000) + for(int i=0;i + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n,k; + scanf("%d %d",&n,&k); + + int x = n+k; + int a[n]; + + for(int i=0;i a[j+1]) + { + temp = a[j]; + a[j] = a[j+1]; + a[j+1] = temp; + } + } + } + + if(x%2 == 1) + { + int l = (x+1)/2; + printf("%d\n",a[l-1]); + } + else if(x%2==0) + { + int l = x/2; + printf("%d\n",a[l-1]); + } + + //for(int i=0;i +using namespace std; + +map m; + +long long int change(long long int n){ + if(n<12) return n; + if(m[n]) return m[n]; + m[n]=change(n/2)+change(n/3)+change(n/4); + return m[n]; +} + +int main(){ + long long int n,count=0; + while(scanf("%lld",&n)>0){ + m[n]=1; + count=max(n,change(n/2)+change(n/3)+change(n/4)); + printf("%lld\n",count); + count=0; + m.clear(); + } + return 0; +} diff --git a/Codechef/DIFNEIGH.cpp b/Codechef/DIFNEIGH.cpp new file mode 100644 index 00000000..376a60b4 --- /dev/null +++ b/Codechef/DIFNEIGH.cpp @@ -0,0 +1,133 @@ +#include +using namespace std; + +int main(){ + int t; + int a[50][50]; + int i,j,k; + for(k=0;k<50;k++){ + if(k%2==0){ + for(i=k;i<50;i++){ + if((i-k)%4==0||(i-k)%4==1) + a[k][i]=1; + else + a[k][i]=2; + } + for(i=k+1;i<50;i++){ + if((i-k)%4==1||(i-k)%4==2) + a[i][k]=2; + else + a[i][k]=1; + } + } + else{ + for(i=k;i<50;i++){ + if((i-k)%4==0||(i-k)%4==1) + a[k][i]=3; + else + a[k][i]=4; + } + for(i=k+1;i<50;i++){ + if((i-k)%4==1||(i-k)%4==2) + a[i][k]=4; + else + a[i][k]=3; + } + + } + } + cin>>t; + while(t--){ + int n,m,mod; + cin>>n>>m; + // int a[n][m]; + //int i,j; + if(n>=3&&m>=3){ + cout<<4< +using namespace std; +long long maxi=1000000000; + +int main(){ + int i,j,a[(int)1e6+3]={0}; + vector v; + for(i=2;i*i<=1000001;i++){ + if(a[i]==0){ + //v.push_back(i); + for(j=i*i;j<=1000000;j+=i){ + a[j]=i; + } + + } + } + for(i=2;i<1000001;i++){ + if(a[i]==0) + v.push_back(i); + } + int t; + cin>>t; + while(t--) + { + int n,k,l; + cin>>n; + + long long ans; + //cout<2999) + l=l-2999; + // cout< +using namespace std; + +#define ll long long int + +int getPar(int x,int par[]){ + while(x!=par[x]) + x = par[x]; + return x; +} +int find(int x,int y,int par[]) +{ + return ( getPar(x,par) == getPar(y,par) ); +} +int doUnion(int x,int y,int par[],int size[]) +{ + if( find(x,y,par) ) + return -1; + int p1 = getPar(x,par); + int p2 = getPar(y,par); + int s1 = size[p1]; + int s2 = size[p2]; + if( s1 > s2 ) + { + par[p2] = p1; + size[p1] += s2; + } + else + { + par[p1] = p2; + size[p2] += s1; + } + return 1; +} + +int main() +{ + int t; + cin >> t; + while(t--) + { + int n,m; + cin >> n >> m; + + vector< vector > v(n+1); + unordered_map mp; + // init dsu + int par[n+1],size[n+1]; + for(int i=1;i<=n;i++) + { + par[i] = i; + size[i] = 1; + } + + ll B[n+1]={0},A[n+1]={0}, C[n+1]={0}; + set > st; + int first,second; + for(int i=0;i> x >> y; + first = x; + second = y; + // int X = min(x,y); + // int Y = max(x,y); + // if( st.find({X,Y})!=st.end() ) + // continue; + // st.insert({X,Y}); + v[x].push_back(y); + v[y].push_back(x); + // int b = doUnion(x,y,par,size); + A[x]++; + A[y]++; + } + int total = 0; + for(int i=1;i<=n;i++) + { + total += v[i].size(); + } + total /= 2; + // for(int i=0;i<=n;i++) + // A[i] = B[i]+C[i]; + + map > comp; + for(int i=1;i<=n;i++) + { + int p = getPar(i,par); + int size = v[i].size(); + mp[p]+=size; + comp[p].push_back(i); + } + + + int flag=0; + // int count = 0; + // for(auto it=mp.begin();it!=mp.end();it++) + // { + // // cout << it->first << " : " << it->second << endl; + // int edgeInComp = it->second/2; + // if( edgeInComp%2 ) + // count++; + + // } + if( m%2 == 0) + { + // means all the components have even edges. ( so only 1 subraph is required) + cout << 1 << endl; + for(int i=1;i<=n;i++) + cout << 1 << " "; + cout << endl; + } + else + { + + + // need to move 1 node from any one odd component to the other set + // set goToSecond; + // for(auto it=mp.begin();it!=mp.end();it++) + // { + // int edgeInComp = it->second/2; + // if( edgeInComp%2==0 ) + // { + // int p = it->first; + // vector temp = comp[p]; + // for(int i=0;ifirst << " : " << it->second << endl; + // int edgeInComp = it->second/2; + // if( edgeInComp%2 ) + // { + // allSame = 1; + // int p = it->first; + // vector temp = comp[p]; + // for(int i=0;ifirst << " : " << it->second << endl; + // int edgeInComp = it->second/2; + // int flag = 0; + // if( edgeInComp%2 ) + // { + + // int p = it->first; + // vector temp = comp[p]; + // for(int i=0;i50) + { + + return; + } + for(int i=1;i<=n;i++) + { + String s=br.readLine(); + str=s+" "; + for(int j=0;j100) + continue; + } + if(s.indexOf(" not ")!=-1 || s.indexOf("not ")==0 || s.lastIndexOf(" not")==s.length()-4 ) + System.out.println("Real Fancy"); + else + System.out.println("regularly fancy"); + + + + } +} +} \ No newline at end of file diff --git a/Codechef/FLOW004.c b/Codechef/FLOW004.c new file mode 100644 index 00000000..8577fb87 --- /dev/null +++ b/Codechef/FLOW004.c @@ -0,0 +1,28 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t>0) + { + int n,c=0; + scanf("%d",&n); + + while(n>0) + { + int rem = n % 10; + if(rem==4) + { + c = c+1; + } + n = n / 10; + } + printf("%d\n",c); + t--; + } + return 0; +} diff --git a/Codechef/FLOW007.cpp b/Codechef/FLOW007.cpp new file mode 100644 index 00000000..a2f1ccbc --- /dev/null +++ b/Codechef/FLOW007.cpp @@ -0,0 +1,19 @@ +#include +using namespace std; + +int main() { + int t,n; + cin>>t; + for(int i=0;i>n; + while(n>0){ + sum=sum*10; + rem=n%10; + sum=sum+rem; + n=n/10; + } + cout< + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n; + scanf("%d",&n); + float hra,da; + float gross_sal; + + if(n<1500) + { + hra = 0.1*n; + da = 0.9*n; + } + else + { + hra = 500; + da = 0.98*n; + } + gross_sal = n + hra + da; + + printf("%.2f\n",gross_sal); + } + return 0; +} + diff --git a/Codechef/FRUITS.c b/Codechef/FRUITS.c new file mode 100644 index 00000000..bada6a58 --- /dev/null +++ b/Codechef/FRUITS.c @@ -0,0 +1,42 @@ +//Author: Rakshit Naidu + +#include +#include + +int min(int a, int b); + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n,m,k,x=0; + scanf("%d %d %d",&n,&m,&k); + + if(n>=m) + { + x = n - min(m + k,n); + } + else + { + x = m - min(n + k,m); + } + printf("%d\n",x); + } + return 0; +} + +int min(int a, int b) +{ + if(a + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n,k; + scanf("%d %d",&n,&k); + + int x=0; + for(int i=2;i<=k;i++) + { + if(n%i > x) + { + x = n%i; + } + } + + printf("%d\n",x); + } + return 0; +} diff --git a/Codechef/GDSUB.py b/Codechef/GDSUB.py new file mode 100644 index 00000000..3da89c16 --- /dev/null +++ b/Codechef/GDSUB.py @@ -0,0 +1,41 @@ +# author name: namanbansal013 + +def multiply(A, B, m, n): + + prod = [0] * (m + n - 1); + + # Multiply two polynomials term by term + + # Take ever term of first polynomial + for i in range(m): + + # Multiply the current term of first + # polynomial with every term of + # second polynomial. + for j in range(n): + prod[i + j] += A[i] * B[j]; + + return prod; + + +s1=[int(i) for i in input().split()] +n,k=s1[0],s1[1] +s2=[int(j) for j in input().split()] +s3=[] +s3=list(set(s2)) +s4=[] +if(k==0): + print(1) +elif(k==1): + print(n+1) +elif(k>=2): + for c in range(0,len(s3)): + s4.append(s2.count(s3[c])) + p=[s4[0],1] + for d in range(1,len(s4)): + e=[s4[d],1] + p=multiply(p, e, len(p), 2) + if len(s4)>k: + print((sum(p[len(s3)-k:]))%1000000007) + else: + print(sum(p)%1000000007) diff --git a/Codechef/HDDN.cpp b/Codechef/HDDN.cpp new file mode 100644 index 00000000..bd823629 --- /dev/null +++ b/Codechef/HDDN.cpp @@ -0,0 +1,80 @@ +#pragma GCC optimize ("O2,O3,Ofast") +#pragma GCC target ("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") +#include + +using namespace std; + +struct Node { + int x, y, z; +}; + +const int N = (int)5e5 + 5; + +int n, k, m, a[N], fa[N], lim[N], used[N], cnt[N], pre[N]; +vector v; + +int find(int x) { + return x == fa[x] ? x : fa[x] = find(fa[x]); +} + +void init() { + cin >> n >> k >> m; + v.clear(); + fa[0] = 1; + fa[n + 1] = n + 1; + for(int i = 1 ; i <= n ; ++i) { + pre[i] = 0; + cnt[i] = 0; + used[i] = 0; + lim[i] = 0; + a[i] = -1; + fa[i] = i; + } + for(int i = 0 ; i < m ; ++i) { + int x, y, z; cin >> x >> y >> z; + v.push_back({x, y, z}); + } + sort(v.begin(), v.end(), [&](Node x, Node y) { return x.z < y.z; }); +} +bool solve() { + for(auto i : v) { + if(a[i.z] != -1 || i.y > i.z) return false; + a[i.z] = i.x; fa[i.z] = fa[i.z + 1]; + i.y -= cnt[i.x]; + if(i.y < 1) return false; + cnt[i.x] += i.y; lim[i.z] = i.x; + int tt = i.z; + i.z = pre[i.x]; + while(i.y > 1) { + i.z = find(i.z); +// cerr << pre[i.x] << ' ' << i.z << '\n'; + if(i.z >= tt) break; + a[i.z] = i.x; fa[i.z] = fa[i.z + 1]; i.y--; + } + pre[i.x] = tt; + if(i.y > 1) return false; + } + int now = 1; + for(int i = n ; i >= 1 ; --i) { + if(a[i] == -1) { + while(used[now] && now <= k) now++; + if(now > k) return false; + a[i] = now; + } + else if(lim[i] > 0) { + used[lim[i]] = 1; + } + } + cout << "Yes\n"; + for(int i = 1 ; i <= n ; ++i) cout << a[i] << " \n"[i == n]; + return true; +} + +int main() { + ios_base::sync_with_stdio(0), cin.tie(0); + int t; cin >> t; + while(t--) { + init(); + if(!solve()) cout << "No\n"; + } +} diff --git a/Codechef/HOLES.cpp b/Codechef/HOLES.cpp new file mode 100644 index 00000000..50bf7dba --- /dev/null +++ b/Codechef/HOLES.cpp @@ -0,0 +1,52 @@ +#include + +using namespace std; + + + +int main() { + + int t,count; + + cin>>t; + +string s; + + for(int i=0;i>s; + + //cout< + +int main(void) { + // your code goes here + int withdraw_amount; + float init_balance; + scanf("%d %f",&withdraw_amount,&init_balance); + + + if(withdraw_amount % 5 == 0) + { + + if(withdraw_amount < (init_balance - 0.5)) + { + init_balance = init_balance - withdraw_amount - 0.5; + printf("%.2f",init_balance); + } + else + { + printf("%.2f",init_balance); + } + + } + else + { + printf("%.2f",init_balance); + } + + return 0; +} diff --git a/Codechef/INLO33.java b/Codechef/INLO33.java new file mode 100644 index 00000000..388d78cb --- /dev/null +++ b/Codechef/INLO33.java @@ -0,0 +1,90 @@ +//author:somya +//problem:INLO33 + +//package algo; +import java.util.*; + +public class Main { +public static int distance[] = new int[300]; +public static int cost[][] = new int[300][300]; +public static int t[] = new int[300]; + + +public static int wait(int distofminpos,int minpos,int k) { + + int next_signal=t[minpos]; + while(distofminpos>next_signal) + {next_signal+=t[minpos]; + + } + + return (next_signal-distofminpos); + + +} + +public static void calc(int n, int s) { +int flag[] = new int[n + 1]; +int i, minpos = 1, k, c, minimum; +for (i = 1; i <= n; i++) { +flag[i] = 0; +distance[i] = cost[s][i]; +} +c = 2; +while (c <= n) { +minimum = 999; +for (k = 1; k <= n; k++) { +if (distance[k] < minimum && flag[k] != 1) { +minimum = distance[k]; + +minpos = k; +} +} +flag[minpos] = 1; +c++; +for (k = 1; k <= n; k++) { + +if ( distance[minpos]+wait(distance[minpos],minpos,k) + cost[minpos][k] < distance[k] && flag[k] != 1) + distance[k] = distance[minpos] +cost[minpos][k]+wait(distance[minpos],minpos,k); +} +} +} + +public static void main(String args[]) { + int n,m, source,dest,x, i,j; + +Scanner in = new Scanner(System.in); + +source = in.nextInt(); +dest = in.nextInt(); +n = in.nextInt(); +m = in.nextInt(); +for( x=1;x<=n;++x) + {t[x]=in.nextInt(); + + + } + + +//enter cost matrix by edges +for( x=0;x + +int main() { + // Read the input n, k + int n, k; + scanf("%d %d", &n, &k); + + int ans = 0; + + for (int i = 0; i < n; i++) { + int t; + scanf("%d", &t); + + if (t % k == 0) { + ans++; + } + } + + printf("%d\n", ans); + + return 0; +} diff --git a/Codechef/JOHNY.c b/Codechef/JOHNY.c new file mode 100644 index 00000000..84c3a56a --- /dev/null +++ b/Codechef/JOHNY.c @@ -0,0 +1,51 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n; + scanf("%d",&n); + + int a[n]; + for(int i=0;i a[j]) + { + temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } + } + } + int pos=0; + for(int i=0;i +using namespace std; +#define f(i,a,b) for(int i=a;i>Testcase; + while(Testcase--) + { + int N; + cin>>N; + int A[N]; + unordered_mapmap; + f(i,0,N) + { + cin>>A[i]; + map[A[i]]++; + } + int result=0; + f(i,0,N) + { + if(map.find(2*A[i])!=map.end()) + result+=map[2*A[i]]; + } + cout< + +int main(void) { + // your code goes here + int i,max,t,a[100],j; + char ch; + scanf("%d",&t); + + while(t--) + { + i=0,max=-1; + + while(1) + { + scanf("%d%c",&a[i],&ch); + i++; + if(ch=='\n') + { + break; + } + } + for(j=0;j max) + { + max = a[j]; + } + } + printf("%d\n",max); + } + return 0; +} + diff --git a/Codechef/LUCKFOUR.c b/Codechef/LUCKFOUR.c new file mode 100644 index 00000000..8577fb87 --- /dev/null +++ b/Codechef/LUCKFOUR.c @@ -0,0 +1,28 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t>0) + { + int n,c=0; + scanf("%d",&n); + + while(n>0) + { + int rem = n % 10; + if(rem==4) + { + c = c+1; + } + n = n / 10; + } + printf("%d\n",c); + t--; + } + return 0; +} diff --git a/Codechef/LUCKFOUR.cpp b/Codechef/LUCKFOUR.cpp new file mode 100644 index 00000000..02010656 --- /dev/null +++ b/Codechef/LUCKFOUR.cpp @@ -0,0 +1,18 @@ +#include +using namespace std; + +int main() { + int t, n, c; + cin >> t; + while (t--) { + cin >> n; + c = 0; + while (n) { + c = n%10==4 ? c+1 : c; + n /= 10; + } + + cout << c << endl; + } + return 0; +} diff --git a/Codechef/MAGICHF.cpp b/Codechef/MAGICHF.cpp new file mode 100644 index 00000000..71f17793 --- /dev/null +++ b/Codechef/MAGICHF.cpp @@ -0,0 +1,32 @@ +#include +#define ll long long +#define ull unsigned long long +#define vi vector +#define pp pair +#define mp make_pair +#define PI acos(-1.0) +#define all(v) v.begin(),v.end() +#define pb push_back +#define INF 1e18 +#define MOD 1000000007 +using namespace std; +int main() +{ + ll t; + cin>>t; + while(t--) + { + ll n,x,s; + cin>>n>>x>>s; + ll b1,b2; + for(ll i=0;i>b1>>b2; + if(b1==x) + x=b2; + else if(b2==x) + x=b1; + } + cout< +using namespace std; +#define ll long long int + +int main() +{ + int t; + cin >> t; + while(t--) + { + int n,k; + cin >> n >> k; + ll a[n]; + + for(int i=0;i> a[i]; + // k = min(n,k); + + // if( k<=1e6) + // { + for(int i=0;i +using namespace std; + +int main() +{ + int t; + cin>>t; + while(t--) + { + int a,b,rem; + long long int res,k; + int ar[]={6,2,5,5,4,5,6,3,7,6}; + cin>>a>>b; + res=a+b; + k=0; + while(res>0) + { + rem=res%10; + k=k+ar[rem]; + res/=10; + } + cout< +using namespace std; + +vector get_K_index(int n,int k) +{ + vector temp; + map mp; + + for(int i=0;i > divide_to_slice(int a[],int n,vector &k_ind) +{ + int size = k_ind.size(); + vector > t(size+1); + for(int i=0;i merge_slices(int a[],int n,vector > &slices) +{ + vector b; + for(int i=0;i &a,int n) +{ + int lis[n]; + lis[0] = 1; + int tail[n]; + tail[0] = a[0]; + int l = 1; + for(int i=1;i A(n); + // cout << "hi"; + for(int i=0;i final_B; + + // if( n>= 5*1e3 ) + // { + // srand(time(0)); + // vector K; + // // k = 3; + // for(int i=0;i final_k; + // vector final_perm; + + // for(int z=0;z<10;z++) + // { + + // // get the k-1 indices to slice the array + // // cout << "choose K-indices: "; + // vector k_ind = get_K_index(n,k); + // // for(int j=0;j > slices = divide_to_slice(a,n,k_ind); + // // cout << "the slices: \n"; + // // for(int i=0;i B = merge_slices(a,n,slices); + // // cout << "The final permutation B: "; + // // for(int i=0;i B; + // for(int i=0;i= La and Lb > M) + // { + // M = Lb; + // final_B = B; + // // final_k = k_ind; + // // final_perm = K; + // } + // loop++; + // if(loop == 10) + // break; + // unsigned seed = 0; + + + // } while (1); + // } + + // cout << "La: " << La << "\nLb: " << M << endl; + // for(int i=0;i V = A; + sort(A.begin()+i,A.begin()+i+k-2); + Lb = LIS(A,n); + if( Lb>=La and Lb>M) + { + M = Lb; + final_B = A; + + } + A = V; + + } + // cout << "La: " << La << "\nLb: " << M << endl; + for(int i=0;i rand_ind; + unordered_map mp; + // cout << "hi"; + for(int i=0;i<100;i++) + { + int r = rand()%(n-k); + while(mp.find(r)!=mp.end() ) + r = rand()%(n-k); + + mp[r] = 1; + rand_ind.push_back(r); + + + } + // for(int i=0;i<100;i++) + // cout << rand_ind[i] << " "; + // cout << endl; + for(int i=0;i<80;i++) + { + vector V = A; + sort(A.begin()+rand_ind[i],A.begin()+rand_ind[i]+k-2); + Lb = LIS(A,n); + if( Lb>=La and Lb>M) + { + M = Lb; + final_B = A; + + } + A = V; + + } + // cout << "La: " << La << "\nLb: " << M << endl; + for(int i=0;i='A' and ch<='Z': + val = ord(ch) - 55 + else: + val = ord(ch) - 48 + + if val>=base: + return -1 + + sum = sum + val * (base**l) + if sum > threshold: + return -1 + l += 1 + return sum + +t = int(input()) +for z in range(t): + n = int(input()) + table = [] + d = {} + for i in range(n): + base, s = input().split() + # print(base , s) + base = int(base) + if base == -1: + j = 2 + temp = [] + local = {} + while j<=36: + num = toDecimal(j,s) + if num!=-1 and num not in local: + local[num] = 1 + # temp.append(num) + if num not in d: + d[num] = 1 + else: + d[num] += 1 + j+=1 + # table.append(temp) + else: + temp = [] + num = toDecimal(base,s) + local = {} + if num!=-1 and num not in local: + local[num] = 1 + # temp.append(num) + if num not in d: + d[num] = 1 + else: + d[num] += 1 + # table.append(temp) + + M = 10**14 + # for i in table: + # for j in i: + # ser = j + # count = 0 + # for k in table: + # for l in k: + # if l == ser: + # count+=1 + + # if count == n: + # if ser < M: + # M = ser + + ans = -1 + for k in sorted(d.keys()): + # print(k,d[k]) + if d[k] == n: + ans = k + break + + # if M <= threshold: + # ans = M + print(ans) \ No newline at end of file diff --git a/Codechef/MSNSADM1.c b/Codechef/MSNSADM1.c new file mode 100644 index 00000000..082b8a78 --- /dev/null +++ b/Codechef/MSNSADM1.c @@ -0,0 +1,46 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n; + scanf("%d",&n); + int a[n],b[n]; + for(int i=0;i +using namespace std; +#define ll long long int + +unordered_map mp; +void factor(int x) +{ + for(int i=1;i<=sqrt(x);i++) + { + if( x%i == 0) + { + if( x/i == i ) + mp[i]++; + else + { + mp[i]++; + mp[x/i]++; + } + } + } +} + +int main() +{ + int t; + cin >> t; + while(t--) + { + int n; + cin >> n ; + int a[n]; + for(int i=0;i> a[i]; + int star[n]; + star[0] = 0; + for(int i=0;i " << endl; + // for(auto it=mp.begin();it!=mp.end();it++) + // cout << it->first << ": " << it->second << endl; + // cout << endl; + } + // cout << "star values:-> "; + // for(int i=0;i M) + { + M = star[i]; + ind = i; + } + } + cout << M << endl; + mp.clear(); + } +} \ No newline at end of file diff --git a/Codechef/MUFFINS3.cpp b/Codechef/MUFFINS3.cpp new file mode 100644 index 00000000..02c6f8dc --- /dev/null +++ b/Codechef/MUFFINS3.cpp @@ -0,0 +1,16 @@ +#include +using namespace std; + +int main() +{ ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL); + + int n; + cin>>n; + while(n-->0){ + int l; + cin>>l; + cout<<(l/2+1)<<"\n"; + } + + return 0; +} diff --git a/Codechef/ORDNCHS.cpp b/Codechef/ORDNCHS.cpp new file mode 100644 index 00000000..50603619 --- /dev/null +++ b/Codechef/ORDNCHS.cpp @@ -0,0 +1,47 @@ +#include +#include +using namespace std; +typedef pair pr; +#define fr first +#define se second +pr p[10][10]; +char r(char c){ + return"XO"[c=='X']; +} +void work(){ + int i,x,y; + char s[5]; + pr t; + printf("CHAOS\n"); + fflush(stdout); + for(i=0;i<18;i++){ + scanf("%d%d%s",&x,&y,s); + t=p[x][y]; + printf("%d %d %c\n",t.fr,t.se,(x==1||x==6)&&(y==1||y==6)?s[0]:r(s[0])); + fflush(stdout); + } +} +int main(){ + #define gao(a,b,c,d) p[a][b]={c,d};p[c][d]={a,b}; + gao(1,1,6,6) + gao(1,6,6,1) + gao(1,3,1,4) + gao(6,3,6,4) + gao(3,1,4,1) + gao(3,6,4,6) + gao(2,2,2,3) + gao(3,2,3,3) + gao(4,4,4,5) + gao(5,4,5,5) + gao(4,2,5,2) + gao(4,3,5,3) + gao(2,4,3,4) + gao(2,5,3,5) + gao(1,2,5,6) + gao(2,1,6,5) + gao(5,1,1,5) + gao(6,2,2,6) + int T; + scanf("%d",&T); + while(T--)work(); +} diff --git a/Codechef/PRB01.c b/Codechef/PRB01.c new file mode 100644 index 00000000..888d2dec --- /dev/null +++ b/Codechef/PRB01.c @@ -0,0 +1,34 @@ +//Author: Rakshit Naidu + +#include +#include +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n,i,flag=0; + scanf("%d",&n); + + for(i=2;i +#include +using namespace std; + +int main() { + // your code goes here + int t; + cin>>t; + while(t--) + {long int n,p=0,q,Pn_1=0; + cin>>n; + q=pow(2,n); + for(int i=1;i<=n;++i) + { + if(i%2==0) + p=2*Pn_1-1; + else + p=2*Pn_1+1; + Pn_1=p; + + } + cout< +using namespace std; + +int main() +{ + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + int a[n],i,j,k,temp; + + for(i=0;i>a[i]; + + k=0; + for(i=0;ia[i]) + k++; + } + else + { + temp=a[i-5]; + for(j=i-5;ja[i]) + k++; + } + } + cout< +using namespace std; +#define ll long long int + +int main() +{ + int t; + cin >> t; + while(t--) + { + ll n,m,q; + cin >> n >> m >> q; + ll a[n+1]={0},b[m+1]={0}; + for(int i=0;i> x >> y ; + b[y] += 1; + a[x] += 1; + + } + ll o=0,e=0; + for(int i=1;i<=n;i++) + { + if( a[i]%2) + o++; + else + e++; + } + ll ans = 0; + for(int i=1;i<=m;i++) + { + if( b[i]%2) + ans += e; + else + ans += o; + } + cout << ans << endl; + + } +} \ No newline at end of file diff --git a/Codechef/SALARY.cpp b/Codechef/SALARY.cpp new file mode 100644 index 00000000..cb52777f --- /dev/null +++ b/Codechef/SALARY.cpp @@ -0,0 +1,47 @@ +#include +#include +using namespace std; +int main() +{ + // slmax second last maximum + int t,slmax,max,index,it=0,min; + cin>>t; + while(t--) + { + int n,toadd,it=0; + cin>>n; + int a[n]; + for(int i=0;i>a[i]; + sort(a,a+n); + min=a[0]; + while(a[0]!=a[n-1]) + { + // max is last element + max=a[n-1]; + // second last element + index=n-2; + // find second last max + while(a[index]==max) + { + index--; + } + toadd=max-a[index]; + it=it+toadd; + for(int i=0;i +using namespace std; + +int main() +{ + ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL); + int n; + cin>>n; + cout< +#define ll long long +#define fr(v,s,n) for(int v=s;((sn);((s0 && j>0) ? dp[k][i-1][j-1] : 0; + int v3 = (i>0) ? dp[k][i-1][yy] : 0; + int v4 = (j>0) ? dp[k][xx][j-1] : 0; + int val = v1 + v2 - v3 - v4; + int nl = min(xx-i+1,yy-j+1); + + len[val] = max(len[val],nl); +} + +int main() +{ + cin>>n>>m; + + fr(i,0,n) cin>>board[i]; + + char idealboard[2][n][m]; + idealboard[0][0][0] = '0'; + fr(i,1,m) + { + idealboard[0][0][i] = flip(idealboard[0][0][i-1]); + } + fr(i,1,n) + { + idealboard[0][i][0] = flip(idealboard[0][i-1][0]); + fr(j,1,m) + { + idealboard[0][i][j] = flip(idealboard[0][i][j-1]); + } + } + + fr(i,0,n) fr(j,0,m) idealboard[1][i][j] = flip(idealboard[0][i][j]); + + + + fr(k,0,2) fr(i,0,n) fr(j,0,m) dp[k][i][j] = 0; + + + fr(k,0,2) fr(i,0,n) fr(j,0,m) if(board[i][j] != idealboard[k][i][j]) dp[k][i][j] = 1; + + fr(k,0,2) fr(i,1,m) dp[k][0][i] = dp[k][0][i-1] + dp[k][0][i]; + fr(k,0,2) fr(i,1,n) dp[k][i][0] = dp[k][i-1][0] + dp[k][i][0]; + + fr(k,0,2) fr(i,1,n) fr(j,1,m) dp[k][i][j] = dp[k][i-1][j] + dp[k][i][j-1] - dp[k][i-1][j-1] + dp[k][i][j]; + + int minc = min(dp[0][n-1][m-1],dp[1][n-1][m-1]); + + + fr(k,0,2) fr(i,0,n) fr(j,0,m) + { + int xx = i; + int yy = j; + while(xx < n && yy < m) + { + evaluate(i,j,xx,yy,k); + xx++; + yy++; + } + } + + + + fr(i,1,max(dp[0][n-1][m-1],dp[1][n-1][m-1])) + { + len[i] = max(len[i],len[i-1]); + } + int q; + cin>>q; + while(q--) + { + int k; + cin>>k; + if(k > minc) cout< + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + char str[100]; + scanf("%s",str); + int i,f=1; + char b = str[0]; + char c = str[1]; + if(b!=c) + { + for(i=2;str[i]!='\0';i++) + { + if(i%2==0&&str[i]==b) + { + f=1; + } + else if(i%2==1&&str[i]==c) + { + f=1; + } + else + { + f=0; + break; + } + } + } + else + { + f=0; + } + if(f==1) + { + printf("YES\n"); + } + else + { + printf("NO\n"); + } + } + return 0; +} + diff --git a/Codechef/TIMEASR.cpp b/Codechef/TIMEASR.cpp new file mode 100644 index 00000000..7a58f3a7 --- /dev/null +++ b/Codechef/TIMEASR.cpp @@ -0,0 +1,61 @@ +/* + Just For You 97116:) +*/ + +#include +using namespace std; + +//important constants +#define pi M_PI +#define mod 1000000007 +#define maX(a,b) ((a)>(b)?(a):(b)) +#define miN(a,b) ((a)<(b)?(a):(b) +#define abS(x) ((x)<0?-(x):(x)) + +#ifdef ONLINE_JUDGE +#define MAX 200005 +#else +#define MAX 1000 +#endif + +int a[MAX],b[MAX]; +char s[100],r[100],t[100]; + +const double EPS = 1e-9; +double ang[MAX],angle; +int hh[MAX],mm[MAX]; + +int main(){ + #ifndef ONLINE_JUDGE + freopen("input.txt","r",stdin); + // freopen("output.txt","w",stdout); + #endif + + int t,n,m,k,l,x,y,z,flag,count,sum,d,mx,mn,prod; + double hour_angle = 0.0; + double minute_angle = 0.0; + + for(int i=0;i<60*12;i++){ + if(i%60==0) + minute_angle=0; + else + minute_angle+=6.0; + hh[i] = i/60; + mm[i] = i%60; + ang[i] = abS(minute_angle-hour_angle); + if(ang[i]-EPS>180.0) + ang[i] = 360.0 - ang[i]; + hour_angle += 0.5; + } + + double error = 1.0/120.0; + scanf("%d",&t); + while(t--){ + scanf("%lf",&angle); + for(int i=0;i<12*60;i++){ + if(abS(ang[i]-angle) + +int main(void) { + // your code goes here + int t,cumul_1=0,cumul_2=0,lead_1=0,lead_2=0,a,b; + scanf("%d",&t); + + for(int i=0;i cumul_2) + { + if(lead_1 < (cumul_1 - cumul_2)) + { + lead_1 = cumul_1 - cumul_2; + } + } + else + { + if(lead_2 < (cumul_2 - cumul_1)) + { + lead_2 = cumul_2 - cumul_1; + } + } + } + + if(lead_1 > lead_2) + { + printf("1 %d",lead_1); + } + else + { + printf("2 %d",lead_2); + } + + return 0; +} + diff --git a/Codechef/TWOVSTEN.c b/Codechef/TWOVSTEN.c new file mode 100644 index 00000000..040fa942 --- /dev/null +++ b/Codechef/TWOVSTEN.c @@ -0,0 +1,30 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n; + scanf("%d",&n); + int x = n%10; + if(x==5) + { + printf("1\n"); + } + else if(x==0) + { + printf("0\n"); + } + else + { + printf("-1\n"); + } + } + return 0; +} + diff --git a/Codechef/VOWELTB.c b/Codechef/VOWELTB.c new file mode 100644 index 00000000..c2c1470f --- /dev/null +++ b/Codechef/VOWELTB.c @@ -0,0 +1,22 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + char ch; + scanf("%c",&ch); + if(ch>=65&&ch<=90) + { + if(ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U') + { + printf("Vowel\n"); + } + else + { + printf("Consonant\n"); + } + } + return 0; +} + diff --git a/Codechef/XYPIZQ.cpp b/Codechef/XYPIZQ.cpp new file mode 100644 index 00000000..1b3ed411 --- /dev/null +++ b/Codechef/XYPIZQ.cpp @@ -0,0 +1,51 @@ +#include +using namespace std; +long long maxi=1000000000; +#define l long + +int main(){ + int t; + cin>>t; + while(t--){ + long n,k,x,y,z; + long i,j,gcd; + cin>>n>>k>>x>>y>>z; + long p,q; + q=2*n +1; + if(x==z){ + p=x; + gcd=__gcd(p,q); + cout<

y&&y>x){ + if(k==1) + {p=q-z;} + else if(k==2||k==4){ + p=q-2*y; + } + else{ + p=q-x; + + } + gcd=__gcd(p,q); + cout<

+#include +using namespace std; + +int main() { + + long long n; + cin >> n; + long long total(0); + for(long p = 0; p < n; p++){ + long long m; + cin >> m; + total += (m - 1) * (p + 1) + 1; + } + + cout << total << endl; + + return 0; +} diff --git a/Codeforces/1097B.cpp b/Codeforces/1097B.cpp new file mode 100644 index 00000000..7c7e292a --- /dev/null +++ b/Codeforces/1097B.cpp @@ -0,0 +1,50 @@ +// Codeforces 2019 +// Vinicius Rodrigues 15.10.2019 +// Petr and a Combination Lock : Problem 1097B + +#include +#include + +using namespace std; + +void input(vector *vec) +{ + int rots, num; + scanf("%d", &rots); + for(int i = 0; i < rots; i++) + { + scanf("%d", &num); + vec -> push_back(num); + } +} + +int sumWithBitmask(vector nums, int bitmask) +{ + int summation = 0; + for(int i = 0; i < nums.size(); i++) + { + if(bitmask bitand 1 << i) + summation += nums[i]; + else + summation -= nums[i]; + } + return summation; +} + +bool checkIfValid(vector nums) +{ + for(int i = 0; i < 1 << nums.size(); i++) + if(sumWithBitmask(nums, i) % 360 == 0) + return true; + return false; +} + +int main() +{ + vector nums(0); + input(&nums); + if(checkIfValid(nums)) + printf("YES\n"); + else + printf("NO\n"); +} diff --git a/Codeforces/1143A.cpp b/Codeforces/1143A.cpp new file mode 100644 index 00000000..f7a82222 --- /dev/null +++ b/Codeforces/1143A.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; +#define ll long long int +#define FastRead ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr); +#define MAXN 100001 + + + + int main() + { + FastRead + + ll n,i; + cin>>n; + ll a[n],x=1,y=1; + for(i=0;i>a[i]; + if(a[i]==0) + x=i+1; + else + if(a[i]==1) + y=i+1; + } + cout< +#define _ ios_base::sync_with_stdio(0);cin.tie(0); +#define ALL(x) x.begin(),x.end() +typedef long long ll; +using namespace std; + +#define MAXN 200005 + +int main() +{_ + int n; cin >> n; + vector v(n); + for(int i=0; i> v[i]; + if(v[i]<0) v[i]*=-1; + } + sort(ALL(v)); + + ll ans = 0, k=1; + for(int i=0; i +#include +#define ll long long int +#define FastRead ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr); +using namespace std; + + +int main() +{ + FastRead + int n,a,x,b,y; + cin>>n>>a>>x>>b>>y; + + while(a!=x && b!=y) + { + + if(a1) + b--; + else + b=n; + //cout< +#include +#define ll long long int +#define FastRead ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr); +using namespace std; + + +int main() +{ + FastRead + ll n,k,t,ans; + cin>>n>>k; + t=sqrt(8*n+8*k+9); + if(2*n+3>=t) + ans=((2*n+3)-t)/2; + else + ans=((2*n+3)+t)/2; + +cout< +#include +using namespace std; +using LL =long long; + +int main() + { + LL n,m; + cin>>n; + vector A(n); + for(auto &a:A)cin>>a; + cin>>m; + vector B(m); + for(auto &b:B)cin>>b; + sort(A.begin(),A.end()); + sort(B.begin(),B.end()); + + cout< +#include +using namespace std; +using LL =long long; + +int main(){ + LL n,ele,noof0=0; + cin>>n; + vector pos,neg; + LL nsum=0,psum=0; + for(int i=0;i>ele; + if(ele<0)neg.push_back(ele); + else if(ele>0)pos.push_back(ele); + else nsum++,noof0++; + } + for(auto a:neg)nsum+=-a-1; + for(auto a:pos)psum+=a-1; + + if(neg.size()%2==0) + cout<< nsum+psum; + else + { + if(noof0) + cout< +#define _ ios_base::sync_with_stdio(0);cin.tie(0); +#define PB push_back +typedef long long ll; +using namespace std; + +#define MAXN 200005 + +int gcd(int a, int b) { return b ? gcd(b, a%b) : a; } + +int main() +{_ + ll n, g, MAX=0; cin >> n; + vector vv(n), v; + for(int i=0; i> vv[i]; + MAX = max(MAX, vv[i]); + } + for(int i=0; i +using namespace std; +using LL =long long; + +int main() { + LL n,a,b; + cin>>n; + string str; + cin>>str; + unordered_map um; + for(int i=0;i +using namespace std; +using LL =long long; + +int main() { + LL t,n,a,b; + cin>>t; + while(t--){ + b=0; + cin>>n; + unordered_map um; + for(int i=0;i>a; + if(a<=2048) + um[a]++; + } + for(int i=0;i<12;i++) + { + if(um[1<=2)um[1<<(i+1)]+=um[1< +using namespace std; +using LL =long long; + +int main() { + LL t,i=0; + cin>>t; + char a[t][t]; + while(i +using namespace std; +using LL =long long; + +int main() { + LL t,c,m,x; + cin>>t; + while(t--){ + cin>>c>>m>>x; + LL min1=__min(c,m); + LL max1=(c+m+x)/3; + min1=min(max1,min1); + cout< +using namespace std; +using LL =long long; + +int main() { + LL n,a,b,c,d; + cin>>a>>b>>c>>d; + if(a+b==c+d || a+c==b+d || a+d==b+c || a==b+c+d || b==a+c+d || c==a+b+d || d==a+b+c)cout<<"YES"; + else + cout<<"NO"; + +} diff --git a/Codeforces/1230B.cpp b/Codeforces/1230B.cpp new file mode 100644 index 00000000..3854deb6 --- /dev/null +++ b/Codeforces/1230B.cpp @@ -0,0 +1,26 @@ +#include +using namespace std; +using LL =long long; + +int main() { + LL n,k; + cin>>n>>k; + int a[n],i=1,j=0; + string str; + cin>>str; + if(k==0) + cout< +using namespace std; + +#define pb push_back +#define mp make_pair +#define sort_ar() sort(ar.begin(), ar.end()); +#define sort_ar_inv() sort(ar.begin(), ar.end(), greater<>()); +#define FAST_IOS() ios_base::sync_with_stdio(false); +#define FAST_CIN() cin.tie(0); +#define FAST_COUT() cout.tie(0); +#define MOD 10000007 + +typedef long long ll; +const int INF = 0x3f3f3f3f; + +int k, n; + +std::deque q; +std::set s; + +void add(int ent){ + + if(s.find(ent) == s.end()){ + if(q.size() < k){ + s.insert(ent); + q.emplace_front(ent); + } else { + s.erase(q.back()); + q.pop_back(); + + s.insert(ent); + q.emplace_front(ent); + } + } +} + +int main(){ + FAST_IOS(); + FAST_CIN(); + FAST_COUT(); + + cin >> n >> k; + + for(int i = 0, ent; i < n; i++){ + cin >> ent; + add(ent); + } + + cout << q.size() << "\n"; + for(auto i : q){ + cout << i << " "; + } + + cout << "\n"; + + return 0; +} + \ No newline at end of file diff --git a/Codeforces/1236A.cpp b/Codeforces/1236A.cpp new file mode 100644 index 00000000..29747893 --- /dev/null +++ b/Codeforces/1236A.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; +using LL =long long;#include +#include +using namespace std; +using LL= long long; + +int main() +{ + int t,p=0; + cin>>t; + for(int j=0;j>a>>b>>c; + while(b>0 && c>1) + { + c-=2; + b--; + p+=3; + } + while(a>0 && b>1) + { + b-=2; + a--; + p+=3; + } + cout< +using namespace std; +using LL =long long; +LL x,y,z; + +int main() { + LL n,k=1,m=0; + cin>>n; + int a[n][n]={0}; + for(int i=0;i +using namespace std; + +int main(){ + int n; cin>>n; + int a[n]; + int orig[n]; + float temp; + int sum = 0; + for(int i =0; i>temp; + orig[n] = temp; + if((int)temp%2==0){ + a[i] = temp/2; + } + else{ + temp = temp/2.0; + temp += 0.5; + a[i] = (int)temp; + } + sum+=a[i]; + } + int change=1; + if(sum>0){ + for(int i =0; i0){ + a[i] -=1; + sum -=1; + } + cout<0 + for(int i =0; i0){ + // a[i] +=1; //adding 1 to ceil is wrong + // sum +=1; + //} + cout< +using namespace std; + + +int main() +{ + int t; + cin>>t; + long long x,y,i; + while(t--) + { + cin>>x>>y; + i=x-y; + + if(i==1)cout<<"NO"< +using namespace std; +using LL =long long; +int a[1004],ones,zeros; + +int main() { + LL t,k,count=0; + cin>>t; + string str; + while(t--) + { + cin>>k; + cin>>str; + int y=0,z1=0,z2=0; + while(!(str[y++]-'0'))z1++; + y=k-1; + while(!(str[y--]-'0'))z2++; + + if(str[0]=='1'|| str[k-1]=='1') + cout<<2*k< +using namespace std; +using LL =long long; +LL x,y,z; + +int main() { + LL n,sum1=0,sum2=0; + cin>>n; + int a[n]; + for(int i=0;i>a[i]; + sort(a,a+n); + + for(int i=0;i +#define MAX 10000001 +#define moduloN % 1000000007 +using namespace std; + +unsigned long long n; +unsigned long long toD[MAX]; +unsigned long long toAny[MAX]; + +unsigned long long tetrahedron(unsigned long long x) +{ + toD[0] = 1; + toAny[0] = 0; + for (unsigned long long i = 1; i <= x; i++) + { + toD[i] = (toAny[i - 1] * 3) moduloN; + toAny[i] = ((toAny[i - 1] * 2) + toD[i - 1]) moduloN; + } + return toD[x]; +} + +int main(void) +{ + cin >> n; + cout << tetrahedron(n); +} \ No newline at end of file diff --git a/Codeforces/198A.cpp b/Codeforces/198A.cpp new file mode 100644 index 00000000..c94e96b5 --- /dev/null +++ b/Codeforces/198A.cpp @@ -0,0 +1,12 @@ +#include +using namespace std; + +int main(){ + + long long k, b, n, t; + cin >> k >> b >> n >> t; + for(long long s = k + b; s <= t && n > 0; s = k * s + b, --n); + cout << n; + + return 0; +} diff --git a/Codeforces/281A.cpp b/Codeforces/281A.cpp new file mode 100644 index 00000000..45fb2262 --- /dev/null +++ b/Codeforces/281A.cpp @@ -0,0 +1,13 @@ +#include +#include + +using namespace std; + +int main() +{ + string s; + cin >> s; + s[0] = towupper(s[0]); + cout << s < + +int main(){ + + long long n, k; scanf("%lld %lld", &n, &k); + long long total(0), count(0); + for(long long p = 1; p <= n; p++){ + long long x; scanf("%lld", &x); + if(p > 1 && total - x * (n - p) * (p - count - 1) < k){printf("%lld\n", p); ++count;} + else{total += x * (p - 1 - count);} + } + + return 0; +} diff --git a/Codeforces/318A.cpp b/Codeforces/318A.cpp new file mode 100644 index 00000000..6c5f8d1a --- /dev/null +++ b/Codeforces/318A.cpp @@ -0,0 +1,10 @@ +#include +using namespace std; + +int main(){ + int n, k; + cin >> n >> k; + cout << ((k <= (n+1)/2) ? (2*k - 1) : (2 * (k - (n + 1)/2) ) ) << endl; + + return 0; +} diff --git a/Codeforces/339A.cpp b/Codeforces/339A.cpp new file mode 100644 index 00000000..370ef815 --- /dev/null +++ b/Codeforces/339A.cpp @@ -0,0 +1,25 @@ +//339A - Helpful Maths +//Author : wgarcia1309 + +#include +#include +#include +using namespace std; +int main(){ + char s[101]; + int m[100],ind=0; + memset (s,'+',101); + scanf("%s",s); + for(int i=0;i<101;i++){ + if(s[i]!='+' && (int)s[i]!=0){ + m[ind]=(int)s[i]-48; + ind++; + } + } + sort(m,m+ind); + for(int i=0;i +using namespace std; +int main() { + int n,m[100001],change[3]; + change[0]=change[1]=change[2]=0; + cin>>n; + bool x=true; + for(int i=0;i>m[i]; + if((m[i])/25==1 && x){ + change[0]++; + }else if(x){ + if((m[i])/25==2){ + if(change[0]<=0)x=false; + change[0]--; + change[1]++; + }else{ + if(change[0]>0 && change[1]>0){ + change[0]--; + change[1]--; + change[3]++; + }else if (change[0]>2){ + change[0]-=3; + change[3]++; + }else{ + x=false; + } + } + } + } + if(x)cout << "YES\n"; + else cout << "NO\n"; +} \ No newline at end of file diff --git a/Codeforces/476B.cpp b/Codeforces/476B.cpp new file mode 100644 index 00000000..7c72394b --- /dev/null +++ b/Codeforces/476B.cpp @@ -0,0 +1,63 @@ +// Codeforces 2019 +// Vinicius Rodrigues 15.10.2019 +// Dreamoon and WiFi : Problem 476B + +#include +#include +#include +#include +#include + +using namespace std; + +double pfat(int n, int k) +{ + if(n == 0 or n == k) return 1; + + double factor = 1.0f; + for(int i = k+1; i <= n; i++) + factor *= i; + + return factor; +} + +double comb(int n, int r) +{ + if(n < r) return 0; + return pfat(n, max(r, n - r)) / pfat(min(r, n - r), 0); +} + +double calcScore(string str) +{ + return count(str.begin(), str.end(), '+') - count(str.begin(), str.end(), '-'); +} + +double calcSpace(string str) +{ + return count(str.begin(), str.end(), '?'); +} + +double calcPositives(float score, int spaces) +{ + return (score + spaces) / 2; +} + +int main() +{ + string send, reach; + cin >> send >> reach; + + double deltaScore = calcScore(send) - calcScore(reach); + double spaces = calcSpace(reach); + double positives = calcPositives(deltaScore, spaces); + double prob; + + if(spaces > 0 and abs(deltaScore) <= spaces and round(positives) == positives) + prob = comb(spaces, positives) * pow(0.5, positives) * pow(0.5, spaces - positives); + else + prob = !deltaScore ? 1.0f : 0.0f; + + + printf("%.12f\n", prob); + return 0; +} diff --git a/Codeforces/60A.cpp b/Codeforces/60A.cpp new file mode 100644 index 00000000..f4a33d41 --- /dev/null +++ b/Codeforces/60A.cpp @@ -0,0 +1,39 @@ +#include +#include +using namespace std; +#define ll long long int +#define FastRead ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr); +#define MAXN 100001 + + int main() + { + FastRead + + ll n,m,i,j,k; + cin>>n>>m; + string p,s; + int t; + i=1,j=n; + while(m--) + { + cin>>p>>p>>s>>p>>t; + if(s=="left") + { + if(j>t-1) + j=t-1; + } + else + if(s=="right") + { + if(ij) + cout<<-1; + else + cout< 0: yield j + def g(t): + print(*[t.h[min(q, 1)] for q in t.p[1:]]) + n = int(input()) + r, m = T(), T() + q = [(r, m, 0), (m, r, 0)] + while q: + x, y, i = q.pop() + for j in y.f(i): + y.p[j] = -1 + for k in x.f(j): + x.p[k] -= 1 + if not x.p[k]: q.append((x, y, k)) + r.g() + m.g() \ No newline at end of file diff --git a/Codeforces/903A.cpp b/Codeforces/903A.cpp new file mode 100644 index 00000000..1e244ac8 --- /dev/null +++ b/Codeforces/903A.cpp @@ -0,0 +1,24 @@ +//903A - Hungry Student Problem +//Author : wgarcia1309 +#include +using namespace std; +int main(){ + int n; + bool r[110]; + for(int i=0;i<=109;i++)r[i]=false; + for(int i=3;i<=100;i+=3){ + r[i]=true; + for(int j=7;j<=100;j+=7){ + r[j]=true; + if(i+j<=100)r[i+j]=true; + } + } + cin>>n; + while(n--){ + int t; + cin>>t; + if(r[t])cout<<"YES\n"; + else cout<<"NO\n"; + } + return 0; +} \ No newline at end of file diff --git a/Codeforces/903C.cpp b/Codeforces/903C.cpp new file mode 100644 index 00000000..0d030777 --- /dev/null +++ b/Codeforces/903C.cpp @@ -0,0 +1,36 @@ +//903C - Boxes Packing +//Author : wgarcia1309 +#include +using namespace std; +int main(){ + int n,c[5000],r[5000],ind=0; + cin>>n; + memset(r,0,sizeof(r)); + memset(c,0,sizeof(c)); + for(int i=0;i>r[i]; + sort(r,r+n); + if(n>1){ + c[0]=r[n-1]; + ind++; + bool x=true; + for(int i=n-2;i>=0;i--){ + int m=-1; + for(int j=0;j=c[m]){ + c[ind]=r[i]; + ind++; + }else{ + c[m]=r[i]; + } + } + cout<0): + if(d>=e): + b+=e + else: + b+=d + d-=1 + e+=1 + print(b) diff --git a/Codeforces/90A.cpp b/Codeforces/90A.cpp new file mode 100644 index 00000000..a1ed5461 --- /dev/null +++ b/Codeforces/90A.cpp @@ -0,0 +1,16 @@ +#include + +int main(){ + + int r(0), g(0), b(0); scanf("%d %d %d", &r, &g, &b); + + r = (r + 1) / 2; g = (g + 1) / 2; b = (b + 1) / 2; + + int output(0); + if(b >= g && b >= r){output = 30 + 3 * b - 1;} + else if(g >= r){output = 30 + 3 * g - 2;} + else{output = 30 + 3 * r - 3;} + + printf("%d\n", output); + return 0; +} diff --git a/Codeforces/913B.cpp b/Codeforces/913B.cpp new file mode 100644 index 00000000..c959ca4d --- /dev/null +++ b/Codeforces/913B.cpp @@ -0,0 +1,42 @@ +#include +using namespace std; +int main() +{ + int t,z=0,d=0,e=0; + cin>>t; + int a[t-1]; + int b[t]={0}; + for(int i=0;i>a[i]; + b[a[i]-1]+=1; + } + for(int i=0;i0) + {d+=1; + int c=0; + for(int j=0;j=3) + {e+=1; + } + else + { + cout<<"No"< +#include + +int main(){ + int n, m; scanf("%d %d", &n, &m); + m %= (n * (n + 1) / 2); + int x = (sqrt(8 * m + 1) - 1)/ 2.0; + printf("%d\n", m - x * (x + 1) / 2); + return 0; +} diff --git a/Codeforces/935A.py b/Codeforces/935A.py new file mode 100644 index 00000000..1a162cd5 --- /dev/null +++ b/Codeforces/935A.py @@ -0,0 +1,7 @@ +inp = int(input()) +output = 0 +for x in range(1, int(inp/2) + 1): + s = str((inp-x)/x) + if s[-1] == '0' and s[-2] == '.': + output += 1 +print(output) diff --git a/Codeforces/996A.cpp b/Codeforces/996A.cpp new file mode 100644 index 00000000..987915a9 --- /dev/null +++ b/Codeforces/996A.cpp @@ -0,0 +1,36 @@ +// Codeforces 2020 +// Pedro Vinicius Medeiros De Cerqueira 25.04.2020 +// Hit the Lottery : Problem 996A + + +#include + +using namespace std; + +int main(){ + int n; cin >> n; + int dollar_bills = 0; + + while (n > 0) + { + if (n >= 100) { + dollar_bills += n / 100; + n = n % 100; + } else if (n >= 20) { + dollar_bills += n / 20; + n = n % 20; + } else if (n >= 10) { + dollar_bills += n / 10; + n = n % 10; + } else if (n >= 5) { + dollar_bills += n / 5; + n = n % 5; + } else if (n < 5) { + dollar_bills += n; + n -= n; + } + } + + + cout << dollar_bills << endl; +} \ No newline at end of file diff --git a/Codeforces/9A.py b/Codeforces/9A.py new file mode 100644 index 00000000..43d22b0a --- /dev/null +++ b/Codeforces/9A.py @@ -0,0 +1,19 @@ +s = input() +y = s[0] +w = s[2] +if int(y) > int(w): + p = 7 - int(y) +else: + p = 7 - int(w) +if p == 1: + print('1/6') +if p == 2: + print('1/3') +if p == 3: + print('1/2') +if p == 4: + print('2/3') +if p == 5: + print('5/6') +if p == 6: + print('1/1') diff --git a/DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.cs b/DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.cs new file mode 100644 index 00000000..8548a36a --- /dev/null +++ b/DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.cs @@ -0,0 +1,198 @@ +using System; +using System.Collections.Generic; + +namespace DataStructures +{ + public class BinarySearchTree + { + public TreeNode Root { get; set; } + + private TreeNode PrivateInsert(TreeNode root, int value) + { + if (root == null) + { + root = new TreeNode { data = value }; + return root; + } + TreeNode current = root; + if (current.data == value) + return current; + if (current.data < value) + { + if (current.Left == null) + { + current.Left = new TreeNode { data = value }; + return current.Left; + } + else + return PrivateInsert(current.Left, value); + } + else + { + if (current.Right == null) + { + current.Right = new TreeNode { data = value }; + return current.Right; + } + else + return PrivateInsert(current.Right, value); + } + } + + public TreeNode Insert(int value) => PrivateInsert(Root, value); + + private TreeNode PrivateSearch(TreeNode root, int value) + { + TreeNode current = root; + return current.data == value + ? current + : current.data < value + ? current.Left == null + ? null + : PrivateSearch(current.Left, value) + : current.Right == null + ? null + : PrivateSearch(current.Right, value); + } + + public TreeNode Search(int value) => PrivateSearch(Root, value); + + private TreeNode PrivateFindParent(TreeNode root, int value) + { + if ((root == null) || (root.data == value)) + return null; + if (root.data < value) + return root?.Left.data == value ? root : PrivateFindParent(root.Left, value); + else + return root?.Right.data == value ? root : PrivateFindParent(root.Right, value); + } + + public bool Delete(int value) + { + var toDelete = PrivateSearch(Root, value); + if (toDelete == null) + return false; + if (toDelete.Left != null) + { + // Find the biggest from smaller TreeNodes + var temporary = toDelete.Left; + while (temporary.Right != null) + temporary = temporary.Right; + toDelete.data = temporary.data; + if (temporary.Right != null) + { + temporary.data = temporary.Left.data; + // CAUTION! Proper order of assignment + temporary.Right = temporary.Left.Right; + var anotherTemp = temporary.Left.Left; + temporary.Left.Dispose(); + temporary.Left = anotherTemp; + } + } + else if (toDelete.Right != null) + { + // Find the lowest from bigger TreeNodes + var temporary = toDelete.Right; + while (temporary.Left != null) + temporary = temporary.Left; + toDelete.data = temporary.data; + if (temporary.Right != null) + { + temporary.data = temporary.Right.data; + // CAUTION! Proper order of assignment + temporary.Left = temporary.Right.Left; + var anotherTemp = temporary.Right.Right; + temporary.Right.Dispose(); + temporary.Right = anotherTemp; + } + } + else + { + var parent = PrivateFindParent(Root, value); + if (parent?.Left.data == value) + { + parent.Left.Dispose(); + parent.Left = null; + } + + else + { + parent.Right.Dispose(); + parent.Right = null; + } + } + return false; + } + + private void PrivatePreOrderTraversal(TreeNode root, Action TreeNodeAction) + { + TreeNodeAction(root); + if (root.Left != null) + PrivatePreOrderTraversal(root.Left, TreeNodeAction); + if (root.Right != null) + PrivatePreOrderTraversal(root.Right, TreeNodeAction); + } + public void PreOrderTraversal(Action TreeNodeAction) + { + PrivatePreOrderTraversal(Root, TreeNodeAction); + } + + private void PrivateInOrderTraversal(TreeNode root, Action TreeNodeAction) + { + if (root.Left != null) + PrivateInOrderTraversal(root.Left, TreeNodeAction); + TreeNodeAction(root); + if (root.Right != null) + PrivateInOrderTraversal(root.Right, TreeNodeAction); + } + public void InOrderTraversal(Action TreeNodeAction) + { + PrivateInOrderTraversal(Root, TreeNodeAction); + } + + private void PrivatePodOrderTraversal(TreeNode root, Action TreeNodeAction) + { + if (root.Left != null) + PrivatePodOrderTraversal(root.Left, TreeNodeAction); + if (root.Right != null) + PrivatePodOrderTraversal(root.Right, TreeNodeAction); + TreeNodeAction(root); + } + + public void PostOrderTraversal(Action TreeNodeAction) + { + PrivatePodOrderTraversal(Root, TreeNodeAction); + } + + private void PrivateLevelOrderTraversal(TreeNode root, int level, List> treeLevels) + { + if (treeLevels.Count < level) + treeLevels.Add(new List()); + treeLevels[level - 1].Add(root); + if (root.Left != null) + PrivateLevelOrderTraversal(root.Left, level + 1, treeLevels); + if (root.Right != null) + PrivateLevelOrderTraversal(root.Right, level + 1, treeLevels); + } + + public void LevelOrderTraversal(Action TreeNodeAction, Action levelAction) + { + List> treeLevels = new List>(); + int currentLevel = 1; + + PrivateLevelOrderTraversal(Root, currentLevel, treeLevels); + + for (int i = 0; i < treeLevels.Count; i++) + { + List listItem = treeLevels[i]; + for (int j = 0; j < listItem.Count; j++) + { + TreeNode item = listItem[j]; + TreeNodeAction(item); + } + + levelAction(); + } + } + } +} diff --git a/DS/C#/BinarySearchTree/BinarySearchTree/TreeNode.cs b/DS/C#/BinarySearchTree/BinarySearchTree/TreeNode.cs new file mode 100644 index 00000000..a4f06883 --- /dev/null +++ b/DS/C#/BinarySearchTree/BinarySearchTree/TreeNode.cs @@ -0,0 +1,13 @@ +using System; + +namespace DataStructures +{ + public class TreeNode : IDisposable + { + public int data; + public TreeNode Left { get; set; } + public TreeNode Right { get; set; } + + public void Dispose() => Dispose(); + } +} diff --git a/DS/C++/Dictionary/Table.h b/DS/C++/Dictionary/Table.h new file mode 100644 index 00000000..f1255847 --- /dev/null +++ b/DS/C++/Dictionary/Table.h @@ -0,0 +1,463 @@ + +#include +#include +using namespace std; + +template +class Table{ +public: + Table(){} + virtual bool update(const string& key, const TYPE& value)=0; + virtual bool remove(const string& key)=0; + virtual bool find(const string& key, TYPE& value)=0; + virtual int numRecords() const = 0; + virtual bool isEmpty() const = 0; + virtual ~Table(){} +}; + +template +class SimpleTable:public Table{ + + struct Record{ + TYPE data_; + string key_; + Record(const string& key, const TYPE& data){ + key_=key; + data_=data; + } + + }; + + Record** records_; //the table + int max_; //capacity of the array + int size_; //current number of records held + int search(const string& key); + +public: + SimpleTable(int capacity); + SimpleTable(const SimpleTable& other); + SimpleTable(SimpleTable&& other); + virtual bool update(const string& key, const TYPE& value); + virtual bool remove(const string& key); + virtual bool find(const string& key, TYPE& value); + virtual const SimpleTable& operator=(const SimpleTable& other); + virtual const SimpleTable& operator=(SimpleTable&& other); + virtual ~SimpleTable(); + virtual bool isEmpty() const{return size_==0;} + virtual int numRecords() const{return size_;} +}; + + +//returns index of where key is found. +template +int SimpleTable::search(const string& key){ + int rc=-1; + for(int i=0;ikey_==key){ + rc=i; + } + } + return rc; +} + + +template +SimpleTable::SimpleTable(int capacity): Table(){ + records_=new Record*[capacity]; + max_=capacity; + size_=0; +} + +template +SimpleTable::SimpleTable(const SimpleTable& other){ + records_=new Record*[other.max_]; + max_=other.max_; + size_=0; + for(int i=0;ikey_,other.records_[i]->data_); + } +} +template +SimpleTable::SimpleTable(SimpleTable&& other){ + size_=other.size_; + max_=other.max_; + records_=other.records_; + other.records_=nullptr; + other.size_=0; + other.max_=0; +} + +template +bool SimpleTable::update(const string& key, const TYPE& value){ + int idx=search(key); + if(idx==-1){ + if(size_ < max_){ + records_[size_++]=new Record(key,value); + for(int i=0;i records_[j+1]){ + TYPE tmp=records_[j]; + records_[j]=records_[j+1]; + records_[j+1]=tmp; + } + } + } + } + } + else{ + records_[idx]->data_=value; + } + return true; +} + +template +bool SimpleTable::remove(const string& key){ + int idx=search(key); + if(idx!=-1){ + delete records_[idx]; + for(int i=idx;i +bool SimpleTable::find(const string& key, TYPE& value){ + int idx=search(key); + if(idx==-1) + return false; + else{ + value=records_[idx]->data_; + return true; + } +} + +template +const SimpleTable& SimpleTable::operator=(const SimpleTable& other){ + if(this!=&other){ + if(records_){ + int sz=size_; + for(int i=0;ikey_); + } + delete [] records_; + } + records_=new Record*[other.max_]; + max_=other.max_; + size_=0; + for(int i=0;ikey_,other.records_[i]->data_); + } + + } + return *this; +} + +template +const SimpleTable& SimpleTable::operator=(SimpleTable&& other){ + swap(records_,other.records_); + swap(size_,other.size_); + swap(max_,other.max_); + return *this; +} + +template +SimpleTable::~SimpleTable(){ + if(records_){ + int sz=size_; + for(int i=0;ikey_); + } + delete [] records_; + } +} + +template +class LPTable:public Table{ + struct Record { + TYPE data_; + string key_; + //creating a new variable to keep track incase there is a collision + size_t colind_; + + Record(const string& key, const TYPE& data, const size_t colind =0) { + key_ = key; + data_ = data; + colind_ = colind; + } + + }; + + Record** records_; //the table + int maxLP_; //capacity of the array + int sizeLP_; //current number of records held + double loadLP_; //Load Factor for LP table represented as percentage (0.6 = 60%) + + +public: + LPTable(int capacity,double maxLoadFactor); + LPTable(const LPTable& other); + LPTable(LPTable&& other); + virtual bool update(const string& key, const TYPE& value); + virtual bool remove(const string& key); + virtual bool find(const string& key, TYPE& value); + virtual const LPTable& operator=(const LPTable& other); + virtual const LPTable& operator=(LPTable&& other); + virtual ~LPTable(); + virtual bool isEmpty() const { return sizeLP_ == 0; }; + virtual int numRecords() const { return sizeLP_; }; + +}; + +//Constructor that initializes records array and sizeLP_ to safe empty state! While others to their respective values +template +LPTable::LPTable(int capacity,double maxLoadFactor): Table(){ + + records_ = new Record*[capacity]; + + //going through the records array and ensuring that everything is empty + for (int i = 0; i < capacity; i++) + { + records_[i] = nullptr; + } + + maxLP_ = capacity; + sizeLP_ = 0; + loadLP_ = maxLoadFactor; +} + +//Copy Constructor +template +LPTable::LPTable(const LPTable& other){ + + records_ = new Record*[other.maxLP_]; + //shallow coppy the variables + this->maxLP_ = other.maxLP_; + this->loadLP_ = other.loadLP_; + this->sizeLP_ = other.sizeLP_; + + for (int i = 0; i < other.maxLP_; i++) + { + //make sure that each record is a nullptr + records_[i] = nullptr; + + //doesn't copy nullptrs, but covers other nullptrs with actual values + if (other.records_[i] != nullptr) + { + records_[i] = new Record(other.records_[i]->key_, other.records_[i]->data_, other.records_[i]->colind_); + } + } +} + +//Move Constructor +template +LPTable::LPTable(LPTable&& other){ + records_ = new Record*[other.maxLP_]; + + this->maxLP_ = other.maxLP_; + this->loadLP_ = other.loadLP_; + this->sizeLP_ = other.sizeLP_; + + + for (int i = 0; i < other.maxLP_; i++) + { + records_[i] = other.records_[i]; + other.records_[i] = nullptr; + } + + other.maxLP_ = 0; + other.loadLP_ = 0; + other.sizeLP_ = 0; + delete[] other.records_; //delete the whole table + other.records_ = nullptr; //ensure that destructor doesn't try to delete a nullptr; +} + +template +bool LPTable::update(const string& key, const TYPE& value){ + std::hash hashFunction; //. + + size_t hash = hashFunction(key); // + + int index = hash % maxLP_; //holds the actual place that it needs to store value + + int colind = 0; //keeps track of steps after original index + + for (;records_[index] != nullptr; index= ++index % maxLP_) + { + //you start at the hashed index and check to see if the key's match + if (records_[index]->key_ == key) + { + records_[index]->data_ = value; + return true; //value replaced + } + colind++; + } + + //if a nullptr has been encountered then we place the new value there. + if ((double)sizeLP_ / (double)maxLP_ < loadLP_) + { + records_[index] = new Record(key, value, colind); + sizeLP_++; + return true; + } + + return false; +} + +template +bool LPTable::remove(const string& key){ + std::hash hashFunction; //. + + size_t hash = hashFunction(key); // + + int index = hash % maxLP_; //holds the actual place that it needs to store value + + for (; records_[index] != nullptr; index = ++index % maxLP_) + { + //you start at the hashed index and check to see if the key's match + if (records_[index]->key_ == key) + { + delete records_[index]; + records_[index] = nullptr; + sizeLP_--; + int circular = (index+1) % maxLP_; //ensuring the hash table goes in circle - R-value add + int counter = 1; //because we moved 1 forward from the deletion point + + while (records_[circular] != nullptr) + { + //shifting values to proper place inside the table + if (records_[circular]->colind_ >= counter) + { + records_[circular]->colind_ -= counter; //subtracting a step + records_[index] = records_[circular]; + records_[circular] = nullptr; + index = circular; + counter = 1; //reseting counter + } + else + counter++; //add counter if nothing has to be moved + + circular = ++circular % maxLP_; + } + return true; //value found return true; + } + } + return false; +} + + + +template +bool LPTable::find(const string& key, TYPE& value) { + std::hash hashFunction; //. + + size_t hash = hashFunction(key); // + + int index = hash % maxLP_; //holds the actual place that it needs to store value + + for (; records_[index] != nullptr; index = ++index % maxLP_) + { + //you start at the hashed index and check to see if the key's match + if (records_[index]->key_ == key) + { + value = records_[index]->data_; //changing the reference to value + return true; //value found return true; + } + } + return false; +} + + + +//copy assignment operator that copies the records from other to the current object +//this function also checks for self-assignment and empty tables +template +const LPTable& LPTable::operator=(const LPTable& other){ + if (&other != this) + { + for (int i = 0; i < maxLP_; i++) + { + delete records_[i]; + records_[i] = nullptr; + } + delete[] records_; + records_ = nullptr; + + records_ = new Record*[other.maxLP_]; + //shallow coppy the variables + this->maxLP_ = other.maxLP_; + this->loadLP_ = other.loadLP_; + this->sizeLP_ = other.sizeLP_; + + for (int i = 0; i < other.maxLP_; i++) + { + //make sure that each record is a nullptr + records_[i] = nullptr; + + //doesn't copy nullptrs, but covers other nullptrs with actual values + if (other.records_[i] != nullptr) + { + records_[i] = new Record(other.records_[i]->key_, other.records_[i]->data_, other.records_[i]->colind_); + } + } + } + return *this; +} + +//Move assignment operator that moves the records from other to the current object +template +const LPTable& LPTable::operator=(LPTable&& other){ + if (&other != this) + { + //ensuring that records_ is completely empty; + for (int i = 0; i < maxLP_; i++) + { + delete records_[i]; + records_[i] = nullptr; + } + delete[] records_; + records_ = nullptr; + + records_ = new Record*[other.maxLP_]; + + this->maxLP_ = other.maxLP_; + this->loadLP_ = other.loadLP_; + this->sizeLP_ = other.sizeLP_; + + + for (int i = 0; i < other.maxLP_; i++) + { + records_[i] = other.records_[i]; + other.records_[i] = nullptr; + } + + other.maxLP_ = 0; + other.loadLP_ = 0; + other.sizeLP_ = 0; + delete[] other.records_; //delete the whole table + other.records_ = nullptr; //ensures that destructor doesn't try to delete a nullptr; + } + return *this; +} + +//destructor that goes checks for full records and empties it one index at a time. +template +LPTable::~LPTable(){ + if (records_) + { + for (int i = 0; i < maxLP_; i++) + { + delete records_[i]; + records_[i] = nullptr; + } + delete[] records_; + records_ = nullptr; + } +} + + diff --git a/DS/C++/DynamicArray.cpp b/DS/C++/DynamicArray.cpp new file mode 100644 index 00000000..925af26d --- /dev/null +++ b/DS/C++/DynamicArray.cpp @@ -0,0 +1,118 @@ +#include + +using namespace std; + +class DynamicArray { + + private: + int capacity, used; + int* data; + void resize(int new_capacity); + public: + static const int DEFAULT_CAPACITY = 1; + DynamicArray(int initial_capacity = DEFAULT_CAPACITY); + DynamicArray(const DynamicArray& src); + ~DynamicArray(); + DynamicArray& operator=(const DynamicArray& rhs); + int size() const; + bool empty() const; + void add(int anInt); + void remove(int anInt); + void print(ostream& out) const; +}; + +void DynamicArray::resize(int new_capacity) +{ + if (new_capacity < used) + new_capacity = used; + if (new_capacity < 1) + new_capacity = 1; + int* temp = new int[new_capacity]; + for(int x = 0; x < used; ++x) + { + temp[x] = data[x]; + } + delete[] data; + data = temp; + capacity = new_capacity; +} + +DynamicArray::DynamicArray(int initial_capacity) : capacity(initial_capacity), used(0) +{ + if (initial_capacity < 1) + initial_capacity = DEFAULT_CAPACITY; + data = new int[initial_capacity]; +} + +DynamicArray::~DynamicArray() { delete[] data; } + +DynamicArray& DynamicArray::operator=(const DynamicArray& rhs) +{ + if (this != &rhs) + { + int* newData = new int[rhs.capacity]; + for (int x = 0; x < rhs.used; ++x) + newData[x] = rhs.data[x]; + delete [] data; + data = newData; + capacity = rhs.capacity; + used = rhs.used; + } + return *this; +} + +int DynamicArray::size() const { return used; } + +bool DynamicArray::empty() const { return used == 0; } + +void DynamicArray::add(int anInt) +{ + if (used+1 > capacity) + resize(1.5 * capacity + 1); + data[used] = anInt; + ++used; +} + +void DynamicArray::remove(int anInt) +{ + int x = 0; + while(data[x] != anInt) + ++x; + for(int y = x; y < used-1; ++y) + data[y] = data[y + 1]; + --used; +} + +void DynamicArray::print(ostream& out) const +{ + if (used > 0) + { + out << data[0]; + for (int x = 1; x < used; ++x) + out << " " << data[x]; + } +} + +int main() +{ + DynamicArray test; + test.add(10); + test.add(20); + test.add(30); + + cout << "\ntest.size() : " << test.size(); + cout << "\ntest.empty() : " << (test.empty() ? "true" : "false"); + + cout << "\nThe dynamic array test is : "; + test.print(cout); + test.remove(10); + cout << "\nThe dynamic array test is : "; + test.print(cout); + test.remove(30); + cout << "\nThe dynamic array test is : "; + test.print(cout); + test.remove(20); + cout << "\ntest.size() : " << test.size(); + cout << "\ntest.empty() : " << (test.empty() ? "true" : "false"); + return 0; +} \ No newline at end of file diff --git a/DS/C++/Jesse&Cookies.cpp b/DS/C++/Jesse&Cookies.cpp new file mode 100644 index 00000000..3c46b2cc --- /dev/null +++ b/DS/C++/Jesse&Cookies.cpp @@ -0,0 +1,109 @@ +#include + +using namespace std; + +vector split_string(string); + +/* + * Complete the cookies function below. + */ +int cookies(int k, vector A) { + + int count=0; + priority_queue, greater> pq; + sort(A.begin(),A.end()); + + if(A.size()==1 && A[0]=k) + break; + } + return count; +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + string nk_temp; + getline(cin, nk_temp); + + vector nk = split_string(nk_temp); + + int n = stoi(nk[0]); + + int k = stoi(nk[1]); + + string A_temp_temp; + getline(cin, A_temp_temp); + + vector A_temp = split_string(A_temp_temp); + + vector A(n); + + for (int A_itr = 0; A_itr < n; A_itr++) { + int A_item = stoi(A_temp[A_itr]); + + A[A_itr] = A_item; + } + + int result = cookies(k, A); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} diff --git a/DS/C++/Node.h b/DS/C++/Node.h new file mode 100644 index 00000000..f8e02d47 --- /dev/null +++ b/DS/C++/Node.h @@ -0,0 +1,34 @@ +#include + +using namespace std; + +class Node +{ + private: + int Data; + public: + Node() + { + Data = 0; + } + + Node(int data) + { + Data = data; + } + + void Set_Data(int data) + { + Data = data; + } + + int Get_Data() + { + return Data; + } + + void Print() + { + cout << Data; + } +}; diff --git a/DS/C++/QueueWithDoublyLL.cpp b/DS/C++/QueueWithDoublyLL.cpp new file mode 100644 index 00000000..64387e9d --- /dev/null +++ b/DS/C++/QueueWithDoublyLL.cpp @@ -0,0 +1,107 @@ +//Queue with Doubly Linked list +#include +using namespace std; +class Node +{ +public: + int data ; + Node *next = NULL; + Node *prev = NULL; + Node(int data) + { + this->data = data ; + } +}; +class Queue +{ + Node* front = NULL; + Node* rear = NULL; + int size = 0 ; + public : + void enqueue(int data) + { + Node *new_node = new Node(data) ; + if(front == NULL) + { + front = new_node; + rear = new_node ; + } + else + { + rear->next = new_node ; + new_node->prev = rear ; + rear = new_node ; + } + size++; + } + void dequeue() + { + if(front == NULL) + { + cout<<"Queue is Already Empty !"<next ; + x->next = NULL ; + x->prev = NULL ; + if(front != NULL) + front->prev = NULL ; + delete x ; + size-- ; + } + } + bool isEmpty() + { + if(size == 0) + return true ; + else + return false ; + } + int Size() + { + return size ; + } + int Front() + { + if(front == NULL || size == 0) + { + cout<<"Queue is Empty"<data ; + } + } + void print() + { + Node *temp = front ; + while(temp != NULL) + { + cout<data<<" "; + temp = temp->next ; + } + cout< +using namespace std; +int stack[100], n=100, top=-1; +void push(int val) { + if(top>=n-1) + cout<<"Stack Overflow"<=0) { + cout<<"Stack elements are:"; + for(int i=top; i>=0; i--) + cout<>ch; + switch(ch) { + case 1: { + cout<<"Enter value to be pushed:"<>val; + push(val); + break; + } + case 2: { + pop(); + break; + } + case 3: { + display(); + break; + } + case 4: { + cout<<"Exit"< v1 = {20, 30, 40, 25, 15}; + + // Converting vector into a heap + // using make_heap() + make_heap(v1.begin(), v1.end()); + + // Displaying the maximum element of heap + // using front() + cout << "The maximum element of heap is : "; + cout << v1.front() << endl; + + // using push_back() to enter element + // in vector + v1.push_back(50); + + // using push_heap() to reorder elements + push_heap(v1.begin(), v1.end()); + + // Displaying the maximum element of heap + // using front() + cout << "The maximum element of heap after push is : "; + cout << v1.front() << endl; + + // using pop_heap() to delete maximum element + pop_heap(v1.begin(), v1.end()); + v1.pop_back(); + + // Displaying the maximum element of heap + // using front() + cout << "The maximum element of heap after pop is : "; + cout << v1.front() << endl; + + return 0; +} \ No newline at end of file diff --git a/DS/C++/queueCpp.cpp b/DS/C++/queueCpp.cpp new file mode 100644 index 00000000..d2d41d77 --- /dev/null +++ b/DS/C++/queueCpp.cpp @@ -0,0 +1,77 @@ +#include +using namespace std; + +struct queue +{ + int value; + queue *next; +}; + +void removeFromQueue(queue*& head) // remove first element from queue +{ + if (head) + { + queue* ptr = head->next; + delete head; + head = ptr; + } +} + +void addToQueue(queue*& head, int nValue) // add new value to queue +{ + if (head == nullptr) // first element + { + head = new queue; + head->value = nValue; + head->next = nullptr; + } + else // add element on the end of the queue + { + auto ptr = head; + while (ptr->next) + { + ptr = ptr->next; + } + ptr->next = new queue{ nValue, nullptr }; + } +} + +void deleteQueue(queue *&head) // delete queue +{ + while (head) + { + auto ptr = head->next; + delete head; + head = ptr; + } +} + +void printQueue(queue *head) +{ + while (head) + { + cout << head->value << endl; + head = head->next; + } +} + +int main() +{ + // TEST + queue* pHead = nullptr; + addToQueue(pHead, 231); + addToQueue(pHead, 121); + addToQueue(pHead, 251); + addToQueue(pHead, 12); + addToQueue(pHead, 14); + addToQueue(pHead, 99); + printQueue(pHead); + removeFromQueue(pHead); + removeFromQueue(pHead); + removeFromQueue(pHead); + printQueue(pHead); + deleteQueue(pHead); + + + +} diff --git a/DS/C++/threadedtree.h b/DS/C++/threadedtree.h new file mode 100644 index 00000000..d9aed4d8 --- /dev/null +++ b/DS/C++/threadedtree.h @@ -0,0 +1,514 @@ +/*************************************************** + +Notes: +This an implementation of threaded tree in C++ +Threaded tree is a binary search tree that allows for easier in-order traversal +For each node, all right/ left child pointers that would normally be null instead point to the in-order successor node +This implementation supports generic typing and both forward and backward in-order traversal, but does not handle duplicate values + +Const and non-const iterator implementation also included to facilitate easy traversal via operators + +***************************************************/ + +#include +using namespace std; + +// Generic type threaded tree +template +class ThreadedTree { + struct Node{ + T data_; + Node* left_; + Node* right_; + int lFlag_; // Whether the node has a left thread, 0 = no, 1 = yes + int rFlag_; // Whether the node has a right thread, 0 = no, 1 = yes + + Node(const T& data, Node* lt = nullptr, Node* rt = nullptr, int lFlag = 0, int rFlag = 0) { + data_ = data; + left_ = lt; + right_ = rt; + lFlag_ = lFlag; + rFlag_ = rFlag; + } + }; + Node* root_; + +public: + // Const iterator member + class const_iterator{ + private: + const ThreadedTree* myTree_; + Node* curr_; + + // Private constructor + const_iterator(Node* curr, const ThreadedTree* theTree) { + curr_ = curr; + myTree_ = theTree; + } + + public: + // Constructor + const_iterator(){ + myTree_ = nullptr; + curr_ = nullptr; + } + + // Postfix ++ increments iterator and returns old value + // @return: iterator containing old value + const_iterator operator++(int){ + const_iterator old = *this; + + // If the current node has a right thread, we use that to move forward + if (curr_->rFlag_ == 1) { + curr_ = curr_->right_; + } + // If it doesn't have a right thread, we need to move to the left-most node in its right subtree + // However we only move forward if the right node isn't nullptr (i.e. we're at max value already) + else { + curr_ = curr_->right_; + + if (curr_ != nullptr) { + while (curr_->left_ != nullptr && curr_->lFlag_ != 1) { + curr_ = curr_->left_; + } + } + } + + //Return the old node + return old; + } + + // Postfix -- decrements iterator and returns old value + // @return: iterator containing old value + const_iterator operator--(int){ + const_iterator old = *this; + + // If the current node is nullptr, we're at end, move back to actual last value + // Could also implement an end sentinel, which would be more robust, but I don't want to risk breaking the tester + if (curr_ == nullptr) { + if (myTree_->root_ != nullptr) { + curr_ = myTree_->root_; + while (curr_->right_ != nullptr) { + curr_ = curr_->right_; + } + } + } + else { + // If the current node has a left thread, we use that to move backwards + if (curr_->lFlag_ == 1) { + curr_ = curr_->left_; + } + // If it doesn't have a left thread, we need to move to the right-most node in its left subtree + // However we only move backward if the left node isn't nullptr (i.e. we're at least value already) + else if (curr_->left_ != nullptr) { + curr_ = curr_->left_; + + while (curr_->right_ != nullptr && curr_->rFlag_ != 1) { + curr_ = curr_->right_; + } + } + } + //Return the old node + return old; + } + + // Prefix ++ increments iterator and returns new value + // @return: iterator containing new value + const_iterator operator++(){ + // If the current node has a right thread, we use that to move forward + if (curr_->rFlag_ == 1) { + curr_ = curr_->right_; + } + // If it doesn't have a right thread, we need to move to the left-most node in its right subtree + // However we only move forward if the right node isn't nullptr (i.e. we're at max value already) + else { + curr_ = curr_->right_; + + if (curr_ != nullptr) { + while (curr_->left_ != nullptr && curr_->lFlag_ != 1) { + curr_ = curr_->left_; + } + } + } + + //Return the new node + return *this; + } + + // Prefix -- decrements iterator and returns new value + // @return: iterator containing new value + const_iterator operator--(){ + // If the current node is nullptr, we're at end, move back to actual last value + if (this->curr_ == nullptr) { + if (myTree_->root_ != nullptr) { + curr_ = myTree_->root_; + while (curr_->right_ != nullptr) { + curr_ = curr_->right_; + } + } + } + else { + // If the current node has a left thread, we use that to move backwards + if (curr_->lFlag_ == 1) { + curr_ = curr_->left_; + } + // If it doesn't have a left thread, we need to move to the right-most node in its left subtree + // However we only move backward if the left node isn't nullptr (i.e. we're at least value already) + else if (curr_->left_ != nullptr) { + curr_ = curr_->left_; + + while (curr_->right_ != nullptr && curr_->rFlag_ != 1) { + curr_ = curr_->right_; + } + } + } + //Return the new node + return *this; + } + + // Dereference operator returns the data value stored in the current node + // @return: current node's data value + const T& operator*() const{ + return curr_->data_; + } + + // Returns whether or not the current iterator is the same as the rhs iterator + // @return: True/ False if the iterators are the same + bool operator==(const const_iterator& rhs) const{ + bool ret = false; + + //Test if RHS both the same node and in the same ThreadedTree + if (myTree_ == rhs.myTree_ && curr_ == rhs.curr_) { + ret = true; + } + + return ret; + } + + // Returns whether or not the current iterator is NOT the same as the rhs iterator + // @return: True/ False if the iterators are NOT the same + bool operator!=(const const_iterator& rhs) const{ + bool ret = false; + + //Test if either RHS is not in the same tree, or in the same tree but not the same node + if (myTree_ != rhs.myTree_ || curr_ != rhs.curr_) { + ret = true; + } + + return ret; + } + + friend class ThreadedTree; // Make friend to access threaded tree members + }; + + // Non-const iterator member + class iterator:public const_iterator{ + private: + //Private constructor calls the constant iterator's private constructor + iterator(Node* curr, ThreadedTree* theTree) :const_iterator(curr, theTree) {} + + public: + iterator():const_iterator(){} + + const T& operator*() const{ + return this->curr_->data_; + } + + T& operator*(){ + return this->curr_->data_; + } + + iterator operator++(int){ + iterator old = *this; + + // If the current node has a right thread, we use that to move forward + if (this->curr_->rFlag_ == 1) { + this->curr_ = this->curr_->right_; + } + // If it doesn't have a right thread, we need to move to the left-most node in its right subtree + // However we only move forward if the right node isn't nullptr (i.e. we're at max value already) + else { + this->curr_ = this->curr_->right_; + + if (this->curr_ != nullptr) { + while (this->curr_->left_ != nullptr && this->curr_->lFlag_ != 1) { + this->curr_ = this->curr_->left_; + } + } + } + + //Return the old node + return old; + } + + iterator operator--(int){ + iterator old = *this; + + // If the current node is nullptr, we're at end, move back to actual last value + if (this->curr_ == nullptr) { + if (this->myTree_->root_ != nullptr) { + this->curr_ = this->myTree_->root_; + while (this->curr_->right_ != nullptr) { + this->curr_ = this->curr_->right_; + } + } + } + else { + // If the current node has a left thread, we use that to move backwards + if (this->curr_->lFlag_ == 1) { + this->curr_ = this->curr_->left_; + } + // If it doesn't have a left thread, we need to move to the right-most node in its left subtree + // However we only move backward if the left node isn't nullptr (i.e. we're at least value already) + else if (this->curr_->left_ != nullptr) { + this->curr_ = this->curr_->left_; + + while (this->curr_->right_ != nullptr && this->curr_->rFlag_ != 1) { + this->curr_ = this->curr_->right_; + } + } + } + //Return the old node + return old; + } + + iterator operator++(){ + // If the current node has a right thread, we use that to move forward + if (this->curr_->rFlag_ == 1) { + this->curr_ = this->curr_->right_; + } + // If it doesn't have a right thread, we need to move to the left-most node in its right subtree + // However we only move forward if the right node isn't nullptr (i.e. we're at max value already) + else { + this->curr_ = this->curr_->right_; + + if (this->curr_ != nullptr) { + while (this->curr_->left_ != nullptr && this->curr_->lFlag_ != 1) { + this->curr_ = this->curr_->left_; + } + } + } + + //Return the new node + return *this; + } + + iterator operator--(){ + // If the current node is nullptr, we're at end, move back to actual last value + if (this->curr_ == nullptr) { + if (this->myTree_->root_ != nullptr) { + this->curr_ = this->myTree_->root_; + while (this->curr_->right_ != nullptr) { + this->curr_ = this->curr_->right_; + } + } + } + else { + // If the current node has a left thread, we use that to move backwards + if (this->curr_->lFlag_ == 1) { + this->curr_ = this->curr_->left_; + } + // If it doesn't have a left thread, we need to move to the right-most node in its left subtree + // However we only move backward if the left node isn't nullptr (i.e. we're at least value already) + else if (this->curr_->left_ != nullptr) { + this->curr_ = this->curr_->left_; + + while (this->curr_->right_ != nullptr && this->curr_->rFlag_ != 1) { + this->curr_ = this->curr_->right_; + } + } + } + + //Return the new node + return *this; + } + + friend class ThreadedTree; // Make friend to access threaded tree members + }; + + // Default constructor, sets root node to nullptr + ThreadedTree(){ + root_ = nullptr; + } + + // Inserts a new value into the tree + // @params data: the data value to insert + void insert(const T& data){ + + if (root_ == nullptr) { + root_ = new Node(data); + } + else { + recursiveInsert(root_, data); + } + } + + // Helper function that recursively searches for the correct place to insert a node + // @params node: the current node being inspected while looking for insertion location + // @params parent: the inspected node's immediate parent node + // @params data: the data value to insert + // @return: returns the node modified by the insert (when called recurisely, this chains all the way up to the root) + void recursiveInsert(Node* node, const T& data) { + // If the data is less than the current node's, inspect to the left + if (data < node->data_) { + // If the left node is free, we can add the new node as its left child + if (node->left_ == nullptr || node->lFlag_ == 1) { + Node* ins = new Node(data); + + // Since we are inserting to the left, the new child inherits the current node's left pointer + ins->left_ = node->left_; + // Also need to set the left thread flag of the child if it's not nullptr (i.e. if child is not the least value in the tree) + if (ins->left_ != nullptr) { + ins->lFlag_ = 1; + } + + // The child's right pointer then becomes a thread to the node (iteratively, the parent always comes after left child) + ins->rFlag_ = 1; + ins->right_ = node; + + // Clear the node's left thread flag and point its left to the newly added child + node->lFlag_ = 0; + node->left_ = ins; + + // Null the temporary pointer to avoid errors when going out of scope + ins = nullptr; + } + // If it isn't free, keep inspecting + else { + recursiveInsert(node->left_, data); + } + } + // If the data is greater than the current node's, inspect to the right + else if (data > node->data_) { + // If the right node is free, we can add the new node as its left child + if (node->right_ == nullptr || node->rFlag_ == 1) { + Node* ins = new Node(data); + + // Since we are inserting to the right, the new child inherits the current node's right pointer + ins->right_ = node->right_; + // Also need to set the right thread flag of the child if it's not nullptr (i.e. if child is not the most value in the tree) + if (ins->right_ != nullptr) { + ins->rFlag_ = 1; + } + + // The child's left pointer then becomes a thread to the node (iteratively, the parent always comes after left child) + ins->lFlag_ = 1; + ins->left_ = node; + + // Clear the node's right thread flag and point its right to the newly added child + node->rFlag_ = 0; + node->right_ = ins; + + // Null the temporary pointer to avoid errors when going out of scope + ins = nullptr; + } + // If it isn't free, keep inspecting + else { + recursiveInsert(node->right_, data); + } + } + + // Note: We have to assume that there are no duplicate values as this implementation does not support them + } + + // Helper function that recursively searches for the node with the given data + // @params node: the current node being inspected while looking for insertion location + // @params data: the data value to insert + // @return: returns the found node with matching data, nullptr (end) if not + Node* recursiveFind(Node* node, const T& data) { + Node* ret = nullptr; + + // Only inspect if the node isn't null + if (node != nullptr) { + // If the value is less than the current node's value, continue search to the left + if (data < node->data_) { + ret = recursiveFind(node->left_, data); + } + // If the data is greater than the current node's value, continue searching to the right + else if (data > node->data_) { + ret = recursiveFind(node->right_, data); + } + // If the data is a match, return the current node + else { + ret = node; + } + } + + return ret; + } + + // Finds the node with the matching data value and returns an iterator to it + // @params node: the data value to find + iterator find(const T& data){ + // The recursiveFind() function will either return a node, if found, or nullptr representing "end" if not found + iterator* ret = new iterator(recursiveFind(root_, data), this); + + return *ret; + } + + // Finds the node with the matching data value and returns a constant iterator to it + // @params node: the data value to find + const_iterator find(const T& data) const{ + // The recursiveFind() function will either return a node, if found, or nullptr representing "end" if not found + const_iterator* ret = new const_iterator(recursiveFind(root_, data), this); + + return *ret; + } + + // Returns an iterator to the left-most (least) node in the tree + // @return: iterator pointing to left-most node + iterator begin(){ + Node* ret = nullptr; + + if (root_ != nullptr) { + ret = root_; + while (ret->left_ != nullptr) { + ret = ret->left_; + } + } + + return iterator(ret, this); + } + + // Returns an iterator containing nullptr, which represents the end of the tree's traversal path + // A nullptr works as a suitable end node, because should not occur anywhere else in the tree's traversal path + // All nullptrs at non-end nodes are replaced by thread pointers in a threaded BST + // The only logical nullptr would be to the right of the maximum value, or "one past" the max node + // @return: iterator pointing to right-most node + iterator end(){ + return iterator(nullptr, this); + } + + // Returns a constant iterator to the left-most (least) node in the tree + // @return: constant iterator pointing to left-most node + const_iterator cbegin()const{ + Node* ret = nullptr; + + if (root_ != nullptr) { + ret = root_; + while (ret->left_ != nullptr) { + ret = ret->left_; + } + } + + return const_iterator(ret, this); + } + + // Returns a constant iterator containing nullptr, which represents the end of the tree's traversal path + // A nullptr works as a suitable end node, because should not occur anywhere else in the tree's traversal path + // All nullptrs at non-end nodes are replaced by thread pointers in a threaded BST + // The only logical nullptr would be to the right of the maximum value, or "one past" the max node + // @return: iterator pointing to right-most node + const_iterator cend() const{ + return const_iterator(nullptr, this); + } + + // Destructor uses postfix operator to delete nodes in tree + ~ThreadedTree(){ + iterator i = begin(); + + while (i != end()) { + delete (i++).curr_; + } + } +}; \ No newline at end of file diff --git a/DS/C/avl_tree.c b/DS/C/avl_tree.c new file mode 100644 index 00000000..9fa493de --- /dev/null +++ b/DS/C/avl_tree.c @@ -0,0 +1,239 @@ +# include +# include + +#define clear() printf("\033[H\033[J") + +typedef struct _node{ + int key; + int height, level; + int right_height, left_height; + struct _node *left; + struct _node *right; + struct _node *root_node; +} Node; + +typedef struct _tree{ + Node *root; +} Tree; + +Tree *init_tree(){ + Tree *tree = (Tree*)malloc(sizeof(Tree)); + tree->root=NULL; + return tree; +} + +void show_menu(); +void show_tree(Node *root); +Node * normal_insert(Node *root_node, int value); +Node * search_insert_element(Node *root, int value); +Node * verify_weight(Node *added_node); +Node * right_rotate(Node *root_node); +Node * left_rotate(Node *root_node); +void new_tree_height(Node *sub_tree); +int height_calc(Node *sub_tree); + +int main(){ + Tree *test = init_tree(); + + int value; + int option=-1; + do{ + show_menu(); + scanf("%d", &option); + switch(option){ + case 0: + exit(0); + case 1: + clear(); + printf("\nInsert value: "); + scanf("%d", &value); + if(test->root == NULL) + test->root = normal_insert(test->root,value); + else + test->root = search_insert_element(test->root,value); + break; + case 2: + clear(); + printf ("\nTree elements:\n"); + show_tree(test->root); + getchar(); + getchar(); + break; + default: + clear(); + printf("Invalid\n"); + } + }while(1); +} + +void show_menu(){ + printf("\nAVL Tree\n"); + printf("Choose an option\n"); + printf("0 - Exit\n"); + printf("1 - Insert Element\n"); + printf("2 - List Elements\n"); + printf("\nOption: "); +} + +Node *normal_insert(Node *root_node, int value){ + Node *new_node = (Node*)malloc(sizeof(Node)); + new_node->left = NULL; + new_node->right = NULL; + new_node->root_node = root_node; + new_node->key = value; + new_node->height = 0; + new_node->right_height = 0; + new_node->left_height = 0; + + return new_node; +} + +Node * search_insert_element(Node *root, int value){ + if(root == NULL) + return root; + + if(value > root->key){ + root->right_height++; + root->level = root->left_height - root->right_height; + if(root->right == NULL){ + root->right = normal_insert(root,value); + new_tree_height(root->right); + root = verify_weight(root->right); + }else + root = search_insert_element(root->right,value); + + }else if(value < root->key){ + root->left_height++; + root->level = root->left_height - root->right_height; + if(root->left == NULL){ + root->left = normal_insert(root,value); + new_tree_height(root->left); + root = verify_weight(root->left); + }else + root = search_insert_element(root->left,value); + }else{ + printf("Already inserted"); + } + if(root->left_height>=root->right_height) + root->height = root->left_height; + else + root->height = root->right_height; + +} + + +Node * verify_weight(Node *added_node){ + Node *root_node = added_node->root_node; + Node *root_root_node = root_node->root_node; + + new_tree_height(added_node); + + while(root_root_node != NULL){ + if(root_root_node->level < -1 && root_node->level < 0){ + root_node = left_rotate(root_root_node); + break; + }else if(root_root_node->level > 1 && root_node->level > 0){ + root_node = right_rotate(root_root_node); + break; + }else if(root_root_node->level< -1 && root_node->level > 0){ + root_node = right_rotate(root_node); + root_root_node = left_rotate(root_root_node); + break; + }else if(root_root_node->level > 1 && root_node->level < 0){ + root_node = left_rotate(root_node); + root_root_node = right_rotate(root_root_node); + break; + } + + root_root_node = root_root_node->root_node; + root_node = root_node->root_node; + } + while(root_node->root_node != NULL) + root_node = root_node->root_node; + + return root_node; +} + +void show_tree(Node *root){ + if(root == NULL) + return; + + show_tree(root->left); + if(root->root_node == NULL) + printf("\nKey: %d || Left Height: %d || Right Height: %d || Height: %d || Level: %d || Root: %s", root->key, root->left_height, root->right_height, root->height, root->level, "Raiz"); + else + printf("\nKey: %d || Left Height: %d || Right Height: %d || Height: %d || Level: %d || Root: %d", root->key, root->left_height, root->right_height, root->height, root->level, root->root_node->key); + show_tree(root->right); +} + + +Node * left_rotate(Node *root){ + Node *node_son = root->right; + root->right = node_son->left; + + if ( node_son->left != NULL ) + node_son->left->root_node = root; + node_son->left = root; + node_son->root_node = root->root_node; + if ( root->root_node != NULL ) + if ( root->root_node->left == root ) + root->root_node->left = node_son; + else + root->root_node->right = node_son; + root->root_node = node_son; + + new_tree_height(node_son->right); + new_tree_height(node_son->left); + return node_son; +} + +Node * right_rotate(Node *root){ + Node *node_son = root->left; + + root->left = node_son->right; + if ( node_son->right != NULL ) + node_son->right->root_node = root; + node_son->right = root; + node_son->root_node = root->root_node; + if ( root->root_node != NULL ) + if ( root->root_node->left == root ) + root->root_node->left = node_son; + else + root->root_node->right = node_son; + root->root_node = node_son; + + new_tree_height(node_son->right); + new_tree_height(node_son->left); + return node_son; +} + +void new_tree_height(Node *node_son){ + if(node_son == NULL) + return; + + node_son->right_height = height_calc(node_son->right); + node_son->left_height = height_calc(node_son->left); + if(node_son->left_height >= node_son->right_height) + node_son->height = node_son->left_height; + else + node_son->height = node_son->right_height; + + node_son->level = node_son->left_height - node_son->right_height; + new_tree_height(node_son->root_node); +} + +int height_calc(Node *sub_tree){ + if(sub_tree == NULL) + return 0; + + int t_left_height; + int t_right_height; + + t_left_height = height_calc(sub_tree->left); + t_right_height = height_calc(sub_tree->right); + + if(t_left_height>=t_right_height) + return t_left_height+1; + else + return t_right_height+1; +} diff --git a/DS/C/heap.c b/DS/C/heap.c new file mode 100644 index 00000000..9c85bde5 --- /dev/null +++ b/DS/C/heap.c @@ -0,0 +1,154 @@ +#include +#include + +//data type to be stored in the heap +typedef int elem; +//max number of elements in the heap +#define MAX_SIZE 100 + +//easily passing from index zero to index one +#define PARENT (((pos+1)/2)-1) //truncate division +#define LEFT ((pos+1)*2-1) +#define RIGHT (((pos+1)*2+1)-1) +//failed to allocate memory +#define MEM_ERR 1 + +//heap data type definition +struct heap{ + elem *list; + int size; +}; + +//FUNCTIONS +//constructors +int init_heap(int size, struct heap *heap); +struct heap *heapify(elem *list, int size); +//destructor +void destroy_heap(struct heap *heap); +//actions +void insert(elem a, struct heap *heap); +elem extract_min(struct heap *heap); +elem remove_min(struct heap *heap); +//internal functions +int sift_up(int pos, struct heap *heap); +int sift_down(int pos, struct heap *heap); + +//Simple use of heap for sorting +int main(){ + elem list[8] = {45, 42, 26, 48, 86, 39, 46, 30}; + struct heap *heap; + heap = heapify(list, 8); + int i; + for(i=0; i<8; i++){ + printf("%d ", remove_min(heap)); + } + putchar('\n'); + + destroy_heap(heap); + return 0; +} + +//Returns 0 if sucessfull or MEM_ERR if it fails to allocate memory +int init_heap(int size, struct heap *heap){ + heap->size = 0; + heap->list = malloc(sizeof(elem)*size); + if(heap->list == NULL) return MEM_ERR; + return 0; +} + +//Returns heap if sucessfull or NULL if it fails to allocate memory +struct heap *heapify(elem *list, int size){ + + struct heap *heap = malloc(1*sizeof(struct heap)); + //Check for failures when allocating the heap + if(heap==NULL) return NULL; + if (init_heap(MAX_SIZE, heap) == MEM_ERR){ + free(heap); + return NULL; + } + + //Copy list to heap + int i; + for(i=0; ilist[i] = list[i]; + heap->size = size; + + if (size <= 1) {return heap;} //list is already heap + + //Every leaf is a heap, pos is the first non-leaf node + int pos = size-1; + pos = PARENT; + //Put the smallest on top + while(pos >= 0){ + sift_down(pos, heap); + pos--; + } + + return heap; +} + +void destroy_heap(struct heap *heap){ + heap->size=0; + free(heap->list); +} + +void insert(elem a, struct heap *heap){ + int pos = heap->size; //Inserting in the end of the list + heap->list[pos] = a; + heap->size++; + //Pulls the last element up the heap + sift_up(pos, heap); +} + +elem extract_min(struct heap *heap){ + return heap->list[0]; +} + +elem remove_min(struct heap *heap){ + elem min = heap->list[0]; + //Puts last element on top + heap->list[0] = heap->list[--heap->size]; + //Pushes the first element down the heap + sift_down(0, heap); + return min; +} + +int sift_up(int pos, struct heap *heap){ + elem aux; + while(heap->list[pos] < heap->list[PARENT]){ + aux = heap->list[pos]; + heap->list[pos] = heap->list[PARENT]; + heap->list[PARENT] = aux; + pos = PARENT; + } + return pos; +} + +int sift_down(int pos, struct heap *heap){ + elem aux; + while(RIGHT < heap->size){ + if(heap->list[LEFT] <= heap->list[RIGHT] && heap->list[LEFT] < heap->list[pos]){ + aux = heap->list[pos]; + heap->list[pos] = heap->list[LEFT]; + heap->list[LEFT] = aux; + pos = LEFT; + } + else if(heap->list[RIGHT] < heap->list[pos]){ + aux = heap->list[pos]; + heap->list[pos] = heap->list[RIGHT]; + heap->list[RIGHT] = aux; + pos = RIGHT; + } + else{ //current is the smallest + return pos; + } + } + + //Last parent has one child + if(LEFT < heap->size && heap->list[LEFT] < heap->list[pos]){ + aux = heap->list[LEFT]; + heap->list[LEFT] = heap->list[pos]; + heap->list[pos] = aux; + } + + return pos; +} diff --git a/DS/C/queue.c b/DS/C/queue.c new file mode 100644 index 00000000..341414cf --- /dev/null +++ b/DS/C/queue.c @@ -0,0 +1,57 @@ +#include +#include + +typedef int Value; + +typedef struct Node { + struct Node* previous; + struct Node* next; + Value value; +} Node; + +typedef struct { + Node* head; + Node* tail; +} Queue; + +int is_empty(Queue* queue) +{ + return queue->head == NULL && queue->tail == NULL; +} + +void enqueue(Queue* queue, Value value) { + Node* node = malloc(sizeof(Node)); + Node* head = queue->head; + node->value = value; + node->next = head; + node->previous = NULL; + + if (head != NULL) { + head->previous = node; + } + if (is_empty(queue)) { + queue->tail = node; + } + queue->head = node; +} + +Value dequeue(Queue* queue) { + Value value = queue->tail->value; + Node* tail = queue->tail; + if (queue->tail == queue->head) { + queue->tail = NULL; + queue->head = NULL; + } else { + queue->tail = queue->tail->previous; + } + free(tail); + return value; +} + +Queue* init_queue() +{ + Queue* queue = malloc(sizeof(Queue)); + queue->head = NULL; + queue->tail = NULL; + return queue; +} diff --git a/DS/Go/queue.go b/DS/Go/queue.go new file mode 100644 index 00000000..5e2281b4 --- /dev/null +++ b/DS/Go/queue.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" +) + +func main() { + size := 20 + queue := make([]int, 0) + printPeek(queue) + fmt.Println("Push operations:") + for i := 0; i < size; i++ { + queue = enQueue(queue, i+1) + printPeek(queue) + } + fmt.Println("Pop operations:") + for i := 0; i < size; i++ { + queue = deQueue(queue) + } +} + +func enQueue(queue []int, value int) []int { + newQueue := make([]int, len(queue)+1) + for i := 0; i < len(queue); i++ { + newQueue[i] = queue[i] + } + newQueue[len(queue)] = value + fmt.Println("Enqueue: ", value) + fmt.Println("After enqueue: ", newQueue) + return newQueue +} + +func deQueue(queue []int) []int { + printPeek(queue) + if len(queue) > 0 { + p := peek(queue) + fmt.Println("Dequeue: ", p) + newQueue := queue[1:len(queue)] + fmt.Println("After dequeue: ", newQueue) + return newQueue + } + return queue +} + +func printPeek(queue []int) { + if len(queue) == 0 { + fmt.Println("Queue is empty now.") + } else { + fmt.Println("Peek:", peek(queue)) + } +} + +func peek(queue []int) int { + return queue[0] +} diff --git a/DS/Go/stack.go b/DS/Go/stack.go new file mode 100644 index 00000000..1a3b6fc0 --- /dev/null +++ b/DS/Go/stack.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" +) + +func main() { + size := 20 + stack := make([]int, 0) + printPeek(stack) + fmt.Println("Push operations:") + for i := 0; i < size; i++ { + stack = push(stack, i+1) + printPeek(stack) + } + fmt.Println("Pop operations:") + for i := 0; i < size; i++ { + stack = pop(stack) + } +} + +func push(stack []int, value int) []int { + newStack := make([]int, len(stack)+1) + for i := 0; i < len(stack); i++ { + newStack[i] = stack[i] + } + newStack[len(stack)] = value + fmt.Println("Pushed: ", value) + fmt.Println("After pushed: ", newStack) + return newStack +} + +func pop(stack []int) []int { + printPeek(stack) + if len(stack) > 0 { + p := peek(stack) + fmt.Println("Popped: ", p) + newStack := stack[:len(stack)-1] + fmt.Println("After popped: ", newStack) + return newStack + } + return stack +} + +func printPeek(stack []int) { + if len(stack) == 0 { + fmt.Println("Stack is empty now.") + } else { + fmt.Println("Peek:", peek(stack)) + } +} + +func peek(stack []int) int { + return stack[len(stack)-1] +} diff --git a/DS/Java/Queue.java b/DS/Java/Queue.java new file mode 100644 index 00000000..8dcdf622 --- /dev/null +++ b/DS/Java/Queue.java @@ -0,0 +1,51 @@ +import java.util.LinkedList; +import java.util.Queue; + +public class Test { + + public static void main(String args[]) { + Queue queue = new LinkedList<>(); + + queue_add(queue); + queue_poll(queue); + queue_add(queue); + queue_peek(queue); + queue_size(queue); + queue_remove(queue); + queue_size(queue); + } + + private static void queue_add(Queue queue) { + for (int i = 0; i < 5; i++) { + queue.add(i); + } + } + + private static void queue_poll(Queue queue) { + System.out.println("Poll :"); + + for (int i = 0; i < 5; i++) { + Integer y = queue.poll(); + System.out.println(y); + } + } + + private static void queue_remove(Queue queue) { + System.out.println("Remove :"); + + for (int i = 0; i < 5; i++) { + Integer y = queue.remove(); + System.out.println(y); + } + } + + private static void queue_peek(Queue queue) { + Integer element = queue.peek(); + System.out.println("Element on queue top : " + element); + } + + private static void queue_size(Queue queue) { + Integer size = queue.size(); + System.out.println("The actual size of the queue is: " + size); + } +} diff --git a/DS/Linked_List/linked_list.s b/DS/Linked_List/linked_list.s old mode 100755 new mode 100644 index c80baf84..3130391f --- a/DS/Linked_List/linked_list.s +++ b/DS/Linked_List/linked_list.s @@ -1,344 +1,344 @@ - .data -descriptor: .space 12 -theBucket: .space 80 -printMenu: .asciiz "\n1 - Insert element in the list\n2 - Update/Remove\n3 - Radix sort\n4 - Print list\n5 - Exit\nOption: " -askValue: .asciiz "\nType a value: " -whatDo: .asciiz "\nUpdate or remove? [0] Update / [1] Remove: " -newValue: .asciiz "\nType a new value: " -askIndex: .asciiz "\nType the index of element: " -msg_Inval: .asciiz "\nInvalid option\n" -msg_empty: .asciiz "\nEmpty list\n" -charEnter: .asciiz "\n" -openSquareBrac: .asciiz "Index [" -end_SquareBrac: .asciiz "] = " - .text - -main: - la $s0, descriptor - sw $zero, 0($s0) - sw $zero, 4($s0) - sw $zero, 8($s0) - move $s1, $zero - -menuOp: - li $v0, 4 - la $a0, printMenu - syscall - - li $v0, 5 - syscall - - beq $v0, 1, insert_element - beq $v0, 2, search - beq $v0, 3, order - beq $v0, 4, show_list - beq $v0, 5, exit - - j showInvalid - -insert_element: - li $v0, 4 - la $a0, askValue - syscall - - li $v0, 5 - syscall - move $t0, $v0 - - li $v0, 9 - addi $a0, $zero, 12 - syscall - - lw $t1, 4($s0) - addi $t1, $t1, 1 - sw $t1, 4($s0) - - sw $t0, 4($v0) - sw $zero, 8($v0) - - lw $s1, 8($s0) - bne $s1, $zero, insertEnd - sw $v0, 0($s0) - -insertEnd: - sw $v0, 8($s0) - sw $s1, 0($v0) - beq $s1, $zero, return - sw $v0, 8($s1) - b return - -search: - li $v0, 4 - la $a0, askIndex - syscall - li $v0, 5 - syscall - lw $t1, 0($s0) - lw $t0, 4($s0) - addi $t2, $zero, -1 - blt $v0, $t0, loop_search - li $v0, 4 - la $a0, msg_Inval - syscall - - b return - -loop_search: - move $t0, $t1 - lw $t1, 8($t1) - addi $t2, $t2, 1 - blt $t2, $v0, loop_search - - li $v0, 4 - la $a0, whatDo - syscall - - li $v0, 5 - syscall - - beq $v0, 1, remove_element - bne $v0, $zero, showInvalid - - li $v0, 4 - la $a0, newValue - syscall - - li $v0, 5 - syscall - - sw $v0, 4($t0) - b return - -remove_element: - lw $t7, 4($s0) - addi $t7, $t7, -1 - sw $t7, 4($s0) - lw $t2, 0($t0) - lw $t3, 8($t0) - beq $t2, $zero, remove_first - beq $t3, $zero, remove_last - sw $t2, 0($t3) - sw $t3, 8($t2) - - b return -remove_first: - sw $t3, 0($s0) - beq $t3, $zero, main - sw $zero, 0($t3) - - b return - -remove_last: - sw $t2, 8($s0) - beq $t2, $zero, main - sw $zero, 8($t2) - - b return - -show_list: - lw $s1, 0($s0) - beq $s1, $zero, emptyList - move $t0, $zero - -loop: - lw $t1, 4($s1) - - li $v0, 4 - la $a0, charEnter - syscall - - li $v0, 4 - la $a0, openSquareBrac - syscall - - li $v0, 1 - move $a0, $t0 - syscall - - li $v0, 4 - la $a0, end_SquareBrac - syscall - - li $v0, 1 - move $a0, $t1 - syscall - - lw $s1, 8($s1) - addi $t0, $t0, 1 - bne $s1, $zero, loop - - li $v0, 4 - la $a0, charEnter - syscall - - b return - -return: - b menuOp - - -emptyList: - li $v0, 4 - la $a0, msg_empty - syscall - j menuOp - -showInvalid: - li $v0, 4 - la $a0, msg_Inval - syscall - j menuOp - -order: - lw $t0, 4($s0) - beq $t0, $zero, emptyList - - li $t1, 4 - mult $t0, $t1 - mflo $t0 - sub $sp, $sp, $t0 - - move $s1, $sp - lw $a0, 0($s0) - jal searchBigger - - move $s4, $v0 - li $t1, 1 - -radix: - jal cleanBucket - - lw $t0, 0($s0) - la $s2, theBucket - addi $s2, $s2, 40 - li $t2, 10 - li $t4, 4 - - bgt $t1, $s4, disaloc - -fillBucket: - jal accessBucket - - lw $t3, 0($v1) - - addi $t3, $t3, 1 - sw $t3, 0($v1) - - lw $t0, 8($t0) - - bne $t0, $zero, fillBucket - - la $t0, theBucket - lw $t6, 0($t0) - addi $t0, $t0, 4 - li $t5, 1 - -sum_buckets: - lw $t7, 0($t0) - add $t6, $t6, $t7 - sw $t6, 0($t0) - addi $t0, $t0, 4 - addi $t5, $t5, 1 - blt $t5, 20, sum_buckets - - lw $t0, 8($s0) - -fill_aux: - jal accessBucket - - lw $t3, 0($v1) - - addi $t3, $t3, -1 - sw $t3, 0($v1) - - mult $t3, $t4 - mflo $t3 - sub $t3, $s1, $t3 - - lw $t5, 4($t0) - sw $t5, 0($t3) - lw $t0, 0($t0) - bne $t0, $zero, fill_aux - - lw $t0, 0($s0) - lw $t5, 4($s0) - li $t2, 0 - move $t3, $s1 - -fill_list: - lw $t4, 0($t3) - sw $t4, 4($t0) - lw $t0, 8($t0) - - addi $t3, $t3, -4 - addi $t2, $t2, 1 - - blt $t2, $t5, fill_list - mult $t5, $t2 - mflo $t5 - - li $t2, 10 - mult $t2, $t1 - mflo $t1 - - b radix - -accessBucket: - lw $t3, 4($t0) - div $t3, $t1 - mflo $t3 - - div $t3, $t2 - mfhi $t3 - - mult $t4, $t3 - mflo $t3 - - add $v1, $s2, $t3 - jr $ra - -searchBigger: - li $t7, -1 - lw $t0, 4($a0) - mult $t0, $t7 - mflo $t6 - bgt $t6, $t0, isBigger - -loopMaior: - lw $a0, 8($a0) - beq $a0, $zero, endList - lw $t6, 4($a0) - bgt $t6, $t0, isBigger - mult $t6, $t7 - mflo $t6 - bgt $t6, $t0, isBigger - b loopMaior -isBigger: - move $t0, $t6 - b loopMaior -endList: - move $v0, $t0 - jr $ra - -cleanBucket: - la $s6, theBucket - move $s7, $zero -loopBucket: - sw $zero, 0($s6) - addi $s7, $s7, 1 - addi $s6, $s6, 4 - blt $s7, 20, loopBucket - jr $ra - -disaloc: - lw $t7, 4($s0) - li $t4, 4 - mult $t4, $t7 - mflo $t7 - add $sp, $sp, $t7 - - b return - -exit: - li $v0, 10 - syscall + .data +descriptor: .space 12 +theBucket: .space 80 +printMenu: .asciiz "\n1 - Insert element in the list\n2 - Update/Remove\n3 - Radix sort\n4 - Print list\n5 - Exit\nOption: " +askValue: .asciiz "\nType a value: " +whatDo: .asciiz "\nUpdate or remove? [0] Update / [1] Remove: " +newValue: .asciiz "\nType a new value: " +askIndex: .asciiz "\nType the index of element: " +msg_Inval: .asciiz "\nInvalid option\n" +msg_empty: .asciiz "\nEmpty list\n" +charEnter: .asciiz "\n" +openSquareBrac: .asciiz "Index [" +end_SquareBrac: .asciiz "] = " + .text + +main: + la $s0, descriptor + sw $zero, 0($s0) + sw $zero, 4($s0) + sw $zero, 8($s0) + move $s1, $zero + +menuOp: + li $v0, 4 + la $a0, printMenu + syscall + + li $v0, 5 + syscall + + beq $v0, 1, insert_element + beq $v0, 2, search + beq $v0, 3, order + beq $v0, 4, show_list + beq $v0, 5, exit + + j showInvalid + +insert_element: + li $v0, 4 + la $a0, askValue + syscall + + li $v0, 5 + syscall + move $t0, $v0 + + li $v0, 9 + addi $a0, $zero, 12 + syscall + + lw $t1, 4($s0) + addi $t1, $t1, 1 + sw $t1, 4($s0) + + sw $t0, 4($v0) + sw $zero, 8($v0) + + lw $s1, 8($s0) + bne $s1, $zero, insertEnd + sw $v0, 0($s0) + +insertEnd: + sw $v0, 8($s0) + sw $s1, 0($v0) + beq $s1, $zero, return + sw $v0, 8($s1) + b return + +search: + li $v0, 4 + la $a0, askIndex + syscall + li $v0, 5 + syscall + lw $t1, 0($s0) + lw $t0, 4($s0) + addi $t2, $zero, -1 + blt $v0, $t0, loop_search + li $v0, 4 + la $a0, msg_Inval + syscall + + b return + +loop_search: + move $t0, $t1 + lw $t1, 8($t1) + addi $t2, $t2, 1 + blt $t2, $v0, loop_search + + li $v0, 4 + la $a0, whatDo + syscall + + li $v0, 5 + syscall + + beq $v0, 1, remove_element + bne $v0, $zero, showInvalid + + li $v0, 4 + la $a0, newValue + syscall + + li $v0, 5 + syscall + + sw $v0, 4($t0) + b return + +remove_element: + lw $t7, 4($s0) + addi $t7, $t7, -1 + sw $t7, 4($s0) + lw $t2, 0($t0) + lw $t3, 8($t0) + beq $t2, $zero, remove_first + beq $t3, $zero, remove_last + sw $t2, 0($t3) + sw $t3, 8($t2) + + b return +remove_first: + sw $t3, 0($s0) + beq $t3, $zero, main + sw $zero, 0($t3) + + b return + +remove_last: + sw $t2, 8($s0) + beq $t2, $zero, main + sw $zero, 8($t2) + + b return + +show_list: + lw $s1, 0($s0) + beq $s1, $zero, emptyList + move $t0, $zero + +loop: + lw $t1, 4($s1) + + li $v0, 4 + la $a0, charEnter + syscall + + li $v0, 4 + la $a0, openSquareBrac + syscall + + li $v0, 1 + move $a0, $t0 + syscall + + li $v0, 4 + la $a0, end_SquareBrac + syscall + + li $v0, 1 + move $a0, $t1 + syscall + + lw $s1, 8($s1) + addi $t0, $t0, 1 + bne $s1, $zero, loop + + li $v0, 4 + la $a0, charEnter + syscall + + b return + +return: + b menuOp + + +emptyList: + li $v0, 4 + la $a0, msg_empty + syscall + j menuOp + +showInvalid: + li $v0, 4 + la $a0, msg_Inval + syscall + j menuOp + +order: + lw $t0, 4($s0) + beq $t0, $zero, emptyList + + li $t1, 4 + mult $t0, $t1 + mflo $t0 + sub $sp, $sp, $t0 + + move $s1, $sp + lw $a0, 0($s0) + jal searchBigger + + move $s4, $v0 + li $t1, 1 + +radix: + jal cleanBucket + + lw $t0, 0($s0) + la $s2, theBucket + addi $s2, $s2, 40 + li $t2, 10 + li $t4, 4 + + bgt $t1, $s4, disaloc + +fillBucket: + jal accessBucket + + lw $t3, 0($v1) + + addi $t3, $t3, 1 + sw $t3, 0($v1) + + lw $t0, 8($t0) + + bne $t0, $zero, fillBucket + + la $t0, theBucket + lw $t6, 0($t0) + addi $t0, $t0, 4 + li $t5, 1 + +sum_buckets: + lw $t7, 0($t0) + add $t6, $t6, $t7 + sw $t6, 0($t0) + addi $t0, $t0, 4 + addi $t5, $t5, 1 + blt $t5, 20, sum_buckets + + lw $t0, 8($s0) + +fill_aux: + jal accessBucket + + lw $t3, 0($v1) + + addi $t3, $t3, -1 + sw $t3, 0($v1) + + mult $t3, $t4 + mflo $t3 + sub $t3, $s1, $t3 + + lw $t5, 4($t0) + sw $t5, 0($t3) + lw $t0, 0($t0) + bne $t0, $zero, fill_aux + + lw $t0, 0($s0) + lw $t5, 4($s0) + li $t2, 0 + move $t3, $s1 + +fill_list: + lw $t4, 0($t3) + sw $t4, 4($t0) + lw $t0, 8($t0) + + addi $t3, $t3, -4 + addi $t2, $t2, 1 + + blt $t2, $t5, fill_list + mult $t5, $t2 + mflo $t5 + + li $t2, 10 + mult $t2, $t1 + mflo $t1 + + b radix + +accessBucket: + lw $t3, 4($t0) + div $t3, $t1 + mflo $t3 + + div $t3, $t2 + mfhi $t3 + + mult $t4, $t3 + mflo $t3 + + add $v1, $s2, $t3 + jr $ra + +searchBigger: + li $t7, -1 + lw $t0, 4($a0) + mult $t0, $t7 + mflo $t6 + bgt $t6, $t0, isBigger + +loopMaior: + lw $a0, 8($a0) + beq $a0, $zero, endList + lw $t6, 4($a0) + bgt $t6, $t0, isBigger + mult $t6, $t7 + mflo $t6 + bgt $t6, $t0, isBigger + b loopMaior +isBigger: + move $t0, $t6 + b loopMaior +endList: + move $v0, $t0 + jr $ra + +cleanBucket: + la $s6, theBucket + move $s7, $zero +loopBucket: + sw $zero, 0($s6) + addi $s7, $s7, 1 + addi $s6, $s6, 4 + blt $s7, 20, loopBucket + jr $ra + +disaloc: + lw $t7, 4($s0) + li $t4, 4 + mult $t4, $t7 + mflo $t7 + add $sp, $sp, $t7 + + b return + +exit: + li $v0, 10 + syscall diff --git a/DS/README.md b/DS/README.md index 642e3a71..3b5701f8 100644 --- a/DS/README.md +++ b/DS/README.md @@ -8,3 +8,4 @@ - Heap - Deque - Graph +- Dynamic Array diff --git a/DS/python/collatz.py b/DS/python/collatz.py new file mode 100644 index 00000000..e28b6cad --- /dev/null +++ b/DS/python/collatz.py @@ -0,0 +1,21 @@ +steps = 1 +seq_length = 1 + +for number in range(1, 10): + start_number = number + list_length = 1 + #print(number) + while(number != 1): + if number % 2 == 0: + number = number / 2 + list_length += 1 + else: + number = 3 * number + 1 + list_length += 1 + + if list_length > steps: + steps = list_length + seq_length = start_number + +print("The initial starting number <= 10000000 is", seq_length) +print("The second-longest sequence of integers <= 10000000 is", steps) diff --git a/DS/tree.cpp b/DS/tree.cpp new file mode 100644 index 00000000..269c9035 --- /dev/null +++ b/DS/tree.cpp @@ -0,0 +1,21 @@ +/* you only have to complete the function given below. +Node is defined as + +struct node +{ + int data; + node* left; + node* right; +}; + +*/ + +void preOrder(node *root) { + if(root) + { + cout<data<<" "; + preOrder(root->left); + preOrder(root->right); + } + +} diff --git a/Hackerearth/Acronym.cpp b/Hackerearth/Acronym.cpp new file mode 100644 index 00000000..0a0690e3 --- /dev/null +++ b/Hackerearth/Acronym.cpp @@ -0,0 +1,44 @@ +//Code by Abhishek Tiwari +//Hackerearth : https://www.hackerearth.com/@become +//Github : https://github.com/becomeahacker + +#include +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +#define tc int t; cin>>t; while(t--) +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +int k; cin>>k; string s; +map m; +while(k--) +{ + cin>>s; + m[s]=1; +} +cin>>k; +while(--k) +{ + cin>>s; + if(m[s]==0) + cout<>s; +if(m[s]==0) + cout< +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +#define tc int t; cin>>t; while(t--) + +using namespace std; +int main() +{ +string s; +int i,count=0; +getline(cin,s); +for(i=0;i +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +#define tc int t; cin>>t; while(t--) +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +tc{ +string s; +getline(cin,s); +int a[26]={0}; +fi(s.length()) +{ + if(s[i]!=' ') + a[s[i]-'a']++; +} +getline(cin,s); +fi(s.length()) +{ + if(s[i]!=' ') + a[s[i]-'a']--; +} +bool fir=false,sec=false; +fi(26) +{ + if(a[i]>0) + fir=true; + if(a[i]<0) + sec=true; +} +if(fir && sec) + cout<<"You draw some."<<"\n"; +else { + if(fir) + cout<<"You win some.\n"; + else + cout<<"You lose some.\n"; +} +} + + +return 0; +} diff --git a/Hackerearth/Color The Boxes.c b/Hackerearth/Color The Boxes.c new file mode 100644 index 00000000..5c10b8b7 --- /dev/null +++ b/Hackerearth/Color The Boxes.c @@ -0,0 +1,12 @@ +#include +#include +int main() +{ + unsigned long int n,m,val=1,i,mod=1000000007; + scanf("%lu %lu",&n,&m); + for(i=1;i<=m;i++) { + val=(val*i)%mod; + } + printf("%lu",val); + return 0; +} diff --git a/Hackerearth/Count Of Integers.c b/Hackerearth/Count Of Integers.c new file mode 100644 index 00000000..0d640d5b --- /dev/null +++ b/Hackerearth/Count Of Integers.c @@ -0,0 +1,40 @@ + #include + #include + #define SIZE 1000001 + typedef long int ll; + ll Find(ll Prime[],ll N){ + ll temp=N,curr=Prime[N]; + while(N>1){ + N/=Prime[N]; + if(Prime[N]!=curr){ + temp=(temp/curr)*(curr-1); + curr=Prime[N]; + } + } + return(temp); + } + int main(){ + ll i,j,N,Q; + ll *Prime=(ll *)malloc(SIZE*sizeof(ll)); + ll *count=(ll *)malloc(SIZE*sizeof(ll)); + ll *Sum=(ll *)malloc(SIZE*sizeof(ll)); + for(i=0;i +int main() +{ + long int D,Oc,Of,Od,Cs,Cb,Cm,Cd; + float O,C; + scanf("%ld",&D); + scanf("%ld%ld%ld",&Oc,&Of,&Od); + scanf("%ld%ld%ld%ld",&Cs,&Cb,&Cm,&Cd); + O=(Oc+(D-Of)*Od); + C=Cb+((D/Cs)+Cm)+(D*Cd); + if(O<=C) + printf("Online Taxi"); + else + printf("Classic Taxi"); +return 0; +} diff --git a/Hackerearth/Max Profit.cpp b/Hackerearth/Max Profit.cpp new file mode 100644 index 00000000..a5b5e0e3 --- /dev/null +++ b/Hackerearth/Max Profit.cpp @@ -0,0 +1,35 @@ +//Code by Abhishek Tiwari +//Hackerearth : https://www.hackerearth.com/@become +//Github : https://github.com/becomeahacker + +#include +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +using namespace std; + +int main() +{ +int n, ans=0; +scanf("%d", &n); +int a[n]; +for (int i=0; ians) +ans=a[i]-a[j]; +} +printf("%d\n", ans); +return 0; +} diff --git a/Hackerearth/Old and Cold Numbers.cpp b/Hackerearth/Old and Cold Numbers.cpp new file mode 100644 index 00000000..f9512b62 --- /dev/null +++ b/Hackerearth/Old and Cold Numbers.cpp @@ -0,0 +1,33 @@ +//Code by Abhishek Tiwari +//Hackerearth : https://www.hackerearth.com/@become +//Github : https://github.com/becomeahacker + +#include +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +int t; cin>>t; +while(t--) +{ + +} + + + +return 0; +} diff --git a/Hackerearth/Palindromic Grid.cpp b/Hackerearth/Palindromic Grid.cpp new file mode 100644 index 00000000..88db7b3f --- /dev/null +++ b/Hackerearth/Palindromic Grid.cpp @@ -0,0 +1,90 @@ +//Code by Abhishek Tiwari +//Hackerearth : https://www.hackerearth.com/@become +//Github : https://github.com/becomeahacker + +#include +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +int t; cin>>t; +while(t--){ + +int m,n; +cin>>n>>m; +int count[26]={0}; +int single = 0,pairs=0; string ent; +fi(n){cin>>ent; fj(m) ++count[ent[j]-'a'];} +fi(26) +{ + if(count[i]%2) + { + ++single; + + } + count[i]=count[i]>>1; + if(count[i]%2) + { + ++pairs; + } +} +//cout<<"P : "< +inline int scan() +{ + char c = getchar_unlocked(); + int x = 0; + while(c<'0'||c>'9'){ + c=getchar_unlocked(); + } + while(c>='0'&&c<='9'){ + x=(x<<1)+(x<<3)+c-'0'; + c=getchar_unlocked(); + } + return x; +} +int main() +{ + int x,y,t; + t=scan(); + while(t--) + { + x=scan(); + y=scan(); + int ans=-1; + if(x==y) + ans=1; + if(ans!=1) + for(int i = 2; i < 21; i++) + { + if(pow(1.0*x / i, i) >= y) + { + ans=i; + break; + } + } + printf("%d\n",ans); + } +} diff --git a/Hackerearth/Special Points Of A Polygon.c b/Hackerearth/Special Points Of A Polygon.c new file mode 100644 index 00000000..e34aec54 --- /dev/null +++ b/Hackerearth/Special Points Of A Polygon.c @@ -0,0 +1,44 @@ +#include + +#include +int main() + +{ + int n; + scanf("%d ",&n); + + + int a, b, i = 0, count = 0, dount = 0; + int*c = NULL; + c = (int*)calloc(n, sizeof(int)); + int*d = NULL; + d = (int*)calloc(n, sizeof(int)); + scanf("%d %d", &a, &b); + for (int k = 0; k < n; k++) + { + int x, y; + scanf("%d %d",&x,&y); + *(c + k) = x; + *(d + k) = y; + } + + while (i < n) + { + if (a > *(c + i) && b > *(d + i)) + { + count++; + } + else if (a < *(c + i) && b < *(d + i)) + { + dount++; + } + i++; + } + if (count == dount) + { + printf("%d %d", a, b); + } + + + return 0; +} diff --git a/Hackerearth/Special Sets.c b/Hackerearth/Special Sets.c new file mode 100644 index 00000000..6e6deb58 --- /dev/null +++ b/Hackerearth/Special Sets.c @@ -0,0 +1,20 @@ +#include +int main() +{ + long long int n,r,max,product,mod=1000000007,result=0,i; + scanf("%lld",&n); + if(n%2) + max=(n+1)/2; + else + max=(n+2)/2; + for(r=1;r<=max;++r) + { + product=n-2*r+2; + + for(i=n-2*r+3;i<=n-r+1;++i) + product=(product*(i%mod))%mod; + result=(result+product)%mod; + } + printf("%lld",result); + return 0; +} diff --git a/Hackerearth/Time conversion.py b/Hackerearth/Time conversion.py new file mode 100644 index 00000000..2dacaf0b --- /dev/null +++ b/Hackerearth/Time conversion.py @@ -0,0 +1,37 @@ +#!/bin/python3 + +import os +import sys + +# +# Complete the timeConversion function below. +# +def timeConversion(s): + hour = int(s[:2]) + meridian = s[8:] +# Special-case '12AM' -> 0, '12PM' -> 12 (not 24) + if (hour == 12): + hour = 0 + if (meridian == 'PM'): + hour += 12 + return ("%02d" % hour + s[2:8]) + + + + + + + # + # Write your code here. + # + +if __name__ == '__main__': + f = open(os.environ['OUTPUT_PATH'], 'w') + + s = input() + + result = timeConversion(s) + + f.write(result + '\n') + + f.close() diff --git a/Hackerearth/determinenumber.cpp b/Hackerearth/determinenumber.cpp new file mode 100644 index 00000000..480cf7d5 --- /dev/null +++ b/Hackerearth/determinenumber.cpp @@ -0,0 +1,45 @@ +//problem picked from Novemeber Easy 19 +#include +using namespace std; + +// function to find and print duplicates +void printDuplicates(int arr[], int n) +{ + // unordered_map to store frequencies + vector v; + unordered_map freq; + for (int i=0; i:: iterator itr; + for (itr=freq.begin(); itr!=freq.end(); itr++) + { + // if frequency is more than 1 + // print the element + if (itr->second == 1) + { + v.push_back(itr->first); + dup = false; + } + } + sort(v.begin(), v.end()); + for (auto x : v) + cout << x << " "; + // // no duplicates present + // if (dup == false) + // cout << itr->first; +} + +// Driver program to test above +int main() +{ + int n,q,p; + cin>>n; + int a[n]; + for(int i=0;i>a[i]; + } + printDuplicates(a,n); + return 0; +} diff --git a/Hackerearth/exchangingmoney.cpp b/Hackerearth/exchangingmoney.cpp new file mode 100644 index 00000000..ea279a8a --- /dev/null +++ b/Hackerearth/exchangingmoney.cpp @@ -0,0 +1,24 @@ +//hackerearth problem picked from noveasy19 +#include +using naemespace std; +#define ll long long int +int main() +{ + int n,q,i; + cin>>n>>q; + ll a[n],p,g=0; + for(i=0;i>a[i]; + g=__gcd(a[i],g); + } + while(q--) + { + cin>>p; + if(__gcd(g,p)==g) + cout<<"YES"< i + 3) { + System.Console.WriteLine("Too chaotic"); + return; + } + if (q[i] < i + 2) { + for (int j = Math.Max(0, q[i] - 2); j < i; j++) { + if (q[j] > q[i]) { + result += 1; + } + } + } + } + System.Console.WriteLine(result); + } + +/* +Bubble sort the array twice from tail to head, then compare to a sorted array. +This reverse the bribe operations with minimum moves. +O(n) time. O(n) space. +*/ + static void minimumBribesBubbles(int[] q) { + int[] sortedQ = new int[q.Length]; + for (int i = 0; i < q.Length; i ++) { + sortedQ[i] = i + 1; + } + + int result = 0; + for (int k = 0; k < 2; k++) { + for (int i = q.Length - 1; i > 0; i--) { + if (q[i] < q[i - 1]) { + int temp = q[i - 1]; + q[i - 1] = q[i]; + q[i] = temp; + result += 1; + } + } + } + if (!sortedQ.SequenceEqual(q)) { + System.Console.WriteLine("Too chaotic"); + } + else { + System.Console.WriteLine(result); + } + } + + static void Main(string[] args) { + int t = Convert.ToInt32(Console.ReadLine()); + + for (int tItr = 0; tItr < t; tItr++) { + int n = Convert.ToInt32(Console.ReadLine()); + + int[] q = Array.ConvertAll(Console.ReadLine().Split(' '), qTemp => Convert.ToInt32(qTemp)) + ; + minimumBribes(q); + } + } +} diff --git a/Hackerrank/C#/SolveMeFirst.cs b/Hackerrank/C#/SolveMeFirst.cs new file mode 100644 index 00000000..74b98d95 --- /dev/null +++ b/Hackerrank/C#/SolveMeFirst.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.IO; +class Solution { + + static int solveMeFirst(int a, int b) { + return a+b; + + } + + static void Main(String[] args) { + int val1 = Convert.ToInt32(Console.ReadLine()); + int val2 = Convert.ToInt32(Console.ReadLine()); + int sum = solveMeFirst(val1,val2); + Console.WriteLine(sum); + } +} diff --git a/Hackerrank/C++/BirthdayCakeCandles.cpp b/Hackerrank/C++/BirthdayCakeCandles.cpp new file mode 100644 index 00000000..6b578378 --- /dev/null +++ b/Hackerrank/C++/BirthdayCakeCandles.cpp @@ -0,0 +1,77 @@ +#include + +using namespace std; + +vector split_string(string); + +// Complete the birthdayCakeCandles function below. +int birthdayCakeCandles(vector ar) { + int max = *max_element(ar.begin(), ar.end()); + int count= 0; + for (int i =0; i> ar_count; + cin.ignore(numeric_limits::max(), '\n'); + + string ar_temp_temp; + getline(cin, ar_temp_temp); + + vector ar_temp = split_string(ar_temp_temp); + + vector ar(ar_count); + + for (int i = 0; i < ar_count; i++) { + int ar_item = stoi(ar_temp[i]); + + ar[i] = ar_item; + } + + int result = birthdayCakeCandles(ar); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} diff --git a/Hackerrank/C++/CoinChange.cpp b/Hackerrank/C++/CoinChange.cpp new file mode 100644 index 00000000..f7261ec4 --- /dev/null +++ b/Hackerrank/C++/CoinChange.cpp @@ -0,0 +1,36 @@ +#include + +using namespace std; + +long getWays(long n, vector < long > c, long m){ + long table[n+1][m]; + + for(int j=0; j=0) ? table[i-c[j]][j]:0; + long y = (j>=1) ? table[i][j-1]:0; + + table[i][j]= x+y; + } + } + return table[n][m-1]; +} + +int main() { + int n; + int m; + cin >> n >> m; + vector c(m); + for(int c_i = 0; c_i < m; c_i++){ + cin >> c[c_i]; + } + // Print the number of ways of making change for 'n' units using coins having the values given by 'c' + long ways = getWays(n, c, m); + cout< + +using namespace std; + +string ltrim(const string &); +string rtrim(const string &); +vector split(const string &); + +/* + * Complete the 'diagonalDifference' function below. + * + * The function is expected to return an INTEGER. + * The function accepts 2D_INTEGER_ARRAY arr as parameter. + */ + +int diagonalDifference(vector> arr) { + int d1 =0, d2 =0; + + for (int i=0; i> arr(n); + + for (int i = 0; i < n; i++) { + arr[i].resize(n); + + string arr_row_temp_temp; + getline(cin, arr_row_temp_temp); + + vector arr_row_temp = split(rtrim(arr_row_temp_temp)); + + for (int j = 0; j < n; j++) { + int arr_row_item = stoi(arr_row_temp[j]); + + arr[i][j] = arr_row_item; + } + } + + int result = diagonalDifference(arr); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +string ltrim(const string &str) { + string s(str); + + s.erase( + s.begin(), + find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) + ); + + return s; +} + +string rtrim(const string &str) { + string s(str); + + s.erase( + find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), + s.end() + ); + + return s; +} + +vector split(const string &str) { + vector tokens; + + string::size_type start = 0; + string::size_type end = 0; + + while ((end = str.find(" ", start)) != string::npos) { + tokens.push_back(str.substr(start, end - start)); + + start = end + 1; + } + + tokens.push_back(str.substr(start)); + + return tokens; +} diff --git a/Hackerrank/C++/Equal.cpp b/Hackerrank/C++/Equal.cpp new file mode 100644 index 00000000..87c279e3 --- /dev/null +++ b/Hackerrank/C++/Equal.cpp @@ -0,0 +1,104 @@ +#include +#DEFINE PI 3.14 +using namespace std; + +vector split_string(string); + +int ops(int n) +{ + int res=n/5; + n%=5; + res+=n/2; + n%=2; + res+=n; + return res; +} + +// Complete the equal function below. +int equal(vector arr) { + + int min=INT_MAX; + for(int i=0;i> t; + cin.ignore(numeric_limits::max(), '\n'); + + for (int t_itr = 0; t_itr < t; t_itr++) { + int n; + cin >> n; + cin.ignore(numeric_limits::max(), '\n'); + + string arr_temp_temp; + getline(cin, arr_temp_temp); + + vector arr_temp = split_string(arr_temp_temp); + + vector arr(n); + + for (int i = 0; i < n; i++) { + int arr_item = stoi(arr_temp[i]); + + arr[i] = arr_item; + } + + int result = equal(arr); + + fout << result << "\n"; + } + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} diff --git a/Hackerrank/C++/LonelyInteger.cpp b/Hackerrank/C++/LonelyInteger.cpp new file mode 100644 index 00000000..dfb4adb3 --- /dev/null +++ b/Hackerrank/C++/LonelyInteger.cpp @@ -0,0 +1,81 @@ +#include + +using namespace std; + +vector split_string(string); + +// Complete the lonelyinteger function below. +int lonelyinteger(vector a) { + int res[100]={0}; + int lone=0; + for(int i=0;i> n; + cin.ignore(numeric_limits::max(), '\n'); + + string a_temp_temp; + getline(cin, a_temp_temp); + + vector a_temp = split_string(a_temp_temp); + + vector a(n); + + for (int i = 0; i < n; i++) { + int a_item = stoi(a_temp[i]); + + a[i] = a_item; + } + + int result = lonelyinteger(a); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} diff --git a/Hackerrank/C++/NonDivisibleSubset.cpp b/Hackerrank/C++/NonDivisibleSubset.cpp new file mode 100644 index 00000000..9d7ebce1 --- /dev/null +++ b/Hackerrank/C++/NonDivisibleSubset.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include +#include +using namespace std; + +int main() { + int n,k; + cin>>n>>k; + int rem[k]={0}; + for(int i=0;i>x; + rem[x%k]++; + }int count = 0; + count += min(rem[0],1); + if(k%2 != 0){ + for(int i=1;i<(k/2)+1;i++){ + count += max(rem[i],rem[k-i]); + } + } + else{ + for(int i=1;i +#include +using namespace std; + +int main() { + int T; cin >> T; + cout << setiosflags(ios::uppercase); + cout << setw(0xf) << internal; + while (T--) { + double A; cin >> A; + double B; cin >> B; + double C; cin >> C; + std::cout << std::hex << std::left << std::showbase << std::nouppercase << (long long)A << std::endl; + + std::cout << std::right << setw(15) << setfill('_') << std::showpos << std::fixed << std::setprecision(2); + std::cout << B << std::endl; + + std::cout << std::scientific << std::uppercase << std::noshowpos << std::setprecision(9) << C << std::endl; + /* Enter your code here */ + + } + return 0; + +} \ No newline at end of file diff --git a/Hackerrank/C++/RectangleArea.cpp b/Hackerrank/C++/RectangleArea.cpp new file mode 100644 index 00000000..e416e6f9 --- /dev/null +++ b/Hackerrank/C++/RectangleArea.cpp @@ -0,0 +1,46 @@ +#include + +using namespace std; +/* + * Create classes Rectangle and RectangleArea + */ + +class Rectangle { +public: + void display() { std::cout << width << " " << height << std::endl; } + int height; + int width; +}; + +class RectangleArea : public Rectangle { + +public: + void read_input() { std::cin >> width; std::cin >> height; } + void display() { std::cout << width * height << std::endl; } +}; + + +int main() +{ + /* + * Declare a RectangleArea object + */ + RectangleArea r_area; + + /* + * Read the width and height + */ + r_area.read_input(); + + /* + * Print the width and height + */ + r_area.Rectangle::display(); + + /* + * Print the area + */ + r_area.display(); + + return 0; +} \ No newline at end of file diff --git a/Hackerrank/C++/SamAndSubstrings.cpp b/Hackerrank/C++/SamAndSubstrings.cpp new file mode 100644 index 00000000..08525454 --- /dev/null +++ b/Hackerrank/C++/SamAndSubstrings.cpp @@ -0,0 +1,38 @@ +#include + +using namespace std; + +// Complete the substrings function below. +// Utility method to covert character digit to +// integer digit +int toDigit(char ch) +{ + return (ch - '0'); +} +int substrings(string s) { + int MOD=1000000007; + int l=s.length(); + long long int res = 0; + long long int f = 1; + for(int i = l-1; i >= 0; i--) { + res = (res + (s[i]-'0')*f*(i+1)) % MOD; + f = (f*10+1) % MOD; + } + return res; +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + string n; + getline(cin, n); + + int result = substrings(n); + + fout << result << "\n"; + + fout.close(); + + return 0; +} diff --git a/Hackerrank/C++/SherlockAndCost.cpp b/Hackerrank/C++/SherlockAndCost.cpp new file mode 100644 index 00000000..85381f03 --- /dev/null +++ b/Hackerrank/C++/SherlockAndCost.cpp @@ -0,0 +1,95 @@ +#include + +using namespace std; + +vector split_string(string); + +int maxi(int a,int b) +{ + if(a>b) + return a; + else + return b; +} +// Complete the cost function below. +int cost(vector B) { + int hi=0,lo=0; + int N=B.size(); + for(int i=1;i> t; + cin.ignore(numeric_limits::max(), '\n'); + + for (int t_itr = 0; t_itr < t; t_itr++) { + int n; + cin >> n; + cin.ignore(numeric_limits::max(), '\n'); + + string B_temp_temp; + getline(cin, B_temp_temp); + + vector B_temp = split_string(B_temp_temp); + + vector B(n); + + for (int i = 0; i < n; i++) { + int B_item = stoi(B_temp[i]); + + B[i] = B_item; + } + + int result = cost(B); + + fout << result << "\n"; + } + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} diff --git a/Hackerrank/C++/apple_tree_problem b/Hackerrank/C++/apple_tree_problem new file mode 100644 index 00000000..77f7b6c0 --- /dev/null +++ b/Hackerrank/C++/apple_tree_problem @@ -0,0 +1,159 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); +char** split_string(char*); + +// Complete the countApplesAndOranges function below. +void countApplesAndOranges(int s, int t, int a, int b, int apples_count, int* apples, int oranges_count, int* oranges) { + int x[2] = {0,0}; +for(int i=0;i=s && (a+*(apples+i))<=t) + x[0]+=1; +} +for (int i = 0; i < oranges_count; i++) { + if (b + *(oranges + i) >= s && a + *(oranges + i) <= t) + x[1] += 1; +} +printf("%d \n%d",x[0],x[1]); +} + +int main() +{ + char** st = split_string(readline()); + + char* s_endptr; + char* s_str = st[0]; + int s = strtol(s_str, &s_endptr, 10); + + if (s_endptr == s_str || *s_endptr != '\0') { exit(EXIT_FAILURE); } + + char* t_endptr; + char* t_str = st[1]; + int t = strtol(t_str, &t_endptr, 10); + + if (t_endptr == t_str || *t_endptr != '\0') { exit(EXIT_FAILURE); } + + char** ab = split_string(readline()); + + char* a_endptr; + char* a_str = ab[0]; + int a = strtol(a_str, &a_endptr, 10); + + if (a_endptr == a_str || *a_endptr != '\0') { exit(EXIT_FAILURE); } + + char* b_endptr; + char* b_str = ab[1]; + int b = strtol(b_str, &b_endptr, 10); + + if (b_endptr == b_str || *b_endptr != '\0') { exit(EXIT_FAILURE); } + + char** mn = split_string(readline()); + + char* m_endptr; + char* m_str = mn[0]; + int m = strtol(m_str, &m_endptr, 10); + + if (m_endptr == m_str || *m_endptr != '\0') { exit(EXIT_FAILURE); } + + char* n_endptr; + char* n_str = mn[1]; + int n = strtol(n_str, &n_endptr, 10); + + if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); } + + char** apples_temp = split_string(readline()); + + int* apples = malloc(m * sizeof(int)); + + for (int i = 0; i < m; i++) { + char* apples_item_endptr; + char* apples_item_str = *(apples_temp + i); + int apples_item = strtol(apples_item_str, &apples_item_endptr, 10); + + if (apples_item_endptr == apples_item_str || *apples_item_endptr != '\0') { exit(EXIT_FAILURE); } + + *(apples + i) = apples_item; + } + + int apples_count = m; + + char** oranges_temp = split_string(readline()); + + int* oranges = malloc(n * sizeof(int)); + + for (int i = 0; i < n; i++) { + char* oranges_item_endptr; + char* oranges_item_str = *(oranges_temp + i); + int oranges_item = strtol(oranges_item_str, &oranges_item_endptr, 10); + + if (oranges_item_endptr == oranges_item_str || *oranges_item_endptr != '\0') { exit(EXIT_FAILURE); } + + *(oranges + i) = oranges_item; + } + + int oranges_count = n; + + countApplesAndOranges(s, t, a, b, apples_count, apples, oranges_count, oranges); + + return 0; +} + +char* readline() { + size_t alloc_length = 1024; + size_t data_length = 0; + char* data = malloc(alloc_length); + + while (true) { + char* cursor = data + data_length; + char* line = fgets(cursor, alloc_length - data_length, stdin); + + if (!line) { break; } + + data_length += strlen(cursor); + + if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } + + size_t new_length = alloc_length << 1; + data = realloc(data, new_length); + + if (!data) { break; } + + alloc_length = new_length; + } + + if (data[data_length - 1] == '\n') { + data[data_length - 1] = '\0'; + } + + data = realloc(data, data_length); + + return data; +} + +char** split_string(char* str) { + char** splits = NULL; + char* token = strtok(str, " "); + + int spaces = 0; + + while (token) { + splits = realloc(splits, sizeof(char*) * ++spaces); + if (!splits) { + return splits; + } + + splits[spaces - 1] = token; + + token = strtok(NULL, " "); + } + + return splits; +} diff --git a/Hackerrank/C++/bon-appetit.cpp b/Hackerrank/C++/bon-appetit.cpp new file mode 100644 index 00000000..6f65e916 --- /dev/null +++ b/Hackerrank/C++/bon-appetit.cpp @@ -0,0 +1,96 @@ +#include + +using namespace std; + +string ltrim(const string &); +string rtrim(const string &); +vector split(const string &); + +// Complete the bonAppetit function below. +void bonAppetit(vector bill, int k, int b) { +int total = 0; +for(int i=0;i nk = split(rtrim(nk_temp)); + + int n = stoi(nk[0]); + + int k = stoi(nk[1]); + + string bill_temp_temp; + getline(cin, bill_temp_temp); + + vector bill_temp = split(rtrim(bill_temp_temp)); + + vector bill(n); + + for (int i = 0; i < n; i++) { + int bill_item = stoi(bill_temp[i]); + + bill[i] = bill_item; + } + + string b_temp; + getline(cin, b_temp); + + int b = stoi(ltrim(rtrim(b_temp))); + + bonAppetit(bill, k, b); + + return 0; +} + +string ltrim(const string &str) { + string s(str); + + s.erase( + s.begin(), + find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) + ); + + return s; +} + +string rtrim(const string &str) { + string s(str); + + s.erase( + find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), + s.end() + ); + + return s; +} + +vector split(const string &str) { + vector tokens; + + string::size_type start = 0; + string::size_type end = 0; + + while ((end = str.find(" ", start)) != string::npos) { + tokens.push_back(str.substr(start, end - start)); + + start = end + 1; + } + + tokens.push_back(str.substr(start)); + + return tokens; +} diff --git a/Hackerrank/C++/compareTheTriplets.cpp b/Hackerrank/C++/compareTheTriplets.cpp new file mode 100644 index 00000000..5cab4b1c --- /dev/null +++ b/Hackerrank/C++/compareTheTriplets.cpp @@ -0,0 +1,108 @@ +#include + +using namespace std; + +string ltrim(const string &); +string rtrim(const string &); +vector split(const string &); + +// Complete the compareTriplets function below. +vector compareTriplets(vector a, vector b) { +vector arr(2); +for(int i=0;i<3;i++) +{ + if(a[i]>b[i]) + arr[0]++; + else if(b[i]>a[i]) + arr[1]++; + +} +return arr; + +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + string a_temp_temp; + getline(cin, a_temp_temp); + + vector a_temp = split(rtrim(a_temp_temp)); + + vector a(3); + + for (int i = 0; i < 3; i++) { + int a_item = stoi(a_temp[i]); + + a[i] = a_item; + } + + string b_temp_temp; + getline(cin, b_temp_temp); + + vector b_temp = split(rtrim(b_temp_temp)); + + vector b(3); + + for (int i = 0; i < 3; i++) { + int b_item = stoi(b_temp[i]); + + b[i] = b_item; + } + + vector result = compareTriplets(a, b); + + for (int i = 0; i < result.size(); i++) { + fout << result[i]; + + if (i != result.size() - 1) { + fout << " "; + } + } + + fout << "\n"; + + fout.close(); + + return 0; +} + +string ltrim(const string &str) { + string s(str); + + s.erase( + s.begin(), + find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) + ); + + return s; +} + +string rtrim(const string &str) { + string s(str); + + s.erase( + find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), + s.end() + ); + + return s; +} + +vector split(const string &str) { + vector tokens; + + string::size_type start = 0; + string::size_type end = 0; + + while ((end = str.find(" ", start)) != string::npos) { + tokens.push_back(str.substr(start, end - start)); + + start = end + 1; + } + + tokens.push_back(str.substr(start)); + + return tokens; +} diff --git a/Hackerrank/C++/inputOutput.cpp b/Hackerrank/C++/inputOutput.cpp new file mode 100644 index 00000000..24156001 --- /dev/null +++ b/Hackerrank/C++/inputOutput.cpp @@ -0,0 +1,15 @@ +#include +#include +#include +#include +#include +using namespace std; + +// Problem https://www.hackerrank.com/challenges/cpp-input-and-output/problem + +int main() { + int a, b, c; + cin >> a >> b >> c; + cout << a+b+c << endl; + return 0; +} diff --git a/Hackerrank/C++/insertNodeSpecificPosition.cpp b/Hackerrank/C++/insertNodeSpecificPosition.cpp new file mode 100644 index 00000000..113ac0f9 --- /dev/null +++ b/Hackerrank/C++/insertNodeSpecificPosition.cpp @@ -0,0 +1,92 @@ +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem + +class SinglyLinkedListNode { + public: + int data; + SinglyLinkedListNode *next; + + SinglyLinkedListNode(int node_data) { + this->data = node_data; + this->next = nullptr; + } +}; + +class SinglyLinkedList { + public: + SinglyLinkedListNode *head; + SinglyLinkedListNode *tail; + + SinglyLinkedList() { + this->head = nullptr; + this->tail = nullptr; + } + + void insert_node(int node_data) { + SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data); + + if (!this->head) { + this->head = node; + } else { + this->tail->next = node; + } + + this->tail = node; + } +}; + +void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) { + while (node) { + fout << node->data; + + node = node->next; + + if (node) { + fout << sep; + } + } +} + +void free_singly_linked_list(SinglyLinkedListNode* node) { + while (node) { + SinglyLinkedListNode* temp = node; + node = node->next; + + free(temp); + } +} + +// Complete the insertNodeAtPosition function below. + +/* + * For your reference: + * + * SinglyLinkedListNode { + * int data; + * SinglyLinkedListNode* next; + * }; + * + */ +SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* head, int data, int position) { + + SinglyLinkedListNode *curr = head, *temp; + + if (position == 0){ + temp = head; + head = new SinglyLinkedListNode(data); + head->next = temp; + } + + while (--position) curr = curr->next; + + temp = curr->next; + curr->next = new SinglyLinkedListNode(data); + curr->next->next = temp; + + return head; +} + +int main() \ No newline at end of file diff --git a/Hackerrank/C++/insertNodeTailLinkedList.cpp b/Hackerrank/C++/insertNodeTailLinkedList.cpp new file mode 100644 index 00000000..48314d18 --- /dev/null +++ b/Hackerrank/C++/insertNodeTailLinkedList.cpp @@ -0,0 +1,70 @@ +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list + +class SinglyLinkedListNode { + public: + int data; + SinglyLinkedListNode *next; + + SinglyLinkedListNode(int node_data) { + this->data = node_data; + this->next = nullptr; + } +}; + +class SinglyLinkedList { + public: + SinglyLinkedListNode *head; + + SinglyLinkedList() { + this->head = nullptr; + } + +}; + +void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) { + while (node) { + fout << node->data; + + node = node->next; + + if (node) { + fout << sep; + } + } +} + +void free_singly_linked_list(SinglyLinkedListNode* node) { + while (node) { + SinglyLinkedListNode* temp = node; + node = node->next; + + free(temp); + } +} + +// Complete the insertNodeAtTail function below. + +/* + * For your reference: + * + * SinglyLinkedListNode { + * int data; + * SinglyLinkedListNode* next; + * }; + * + */ +SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) { + if (!head) head = new SinglyLinkedListNode(data); + else { + SinglyLinkedListNode* curr = head; + while (curr->next) curr = curr->next; + curr->next = new SinglyLinkedListNode(data); + } + return head; +} + +int main() \ No newline at end of file diff --git a/Hackerrank/C++/kangaroo.cpp b/Hackerrank/C++/kangaroo.cpp new file mode 100644 index 00000000..11bec119 --- /dev/null +++ b/Hackerrank/C++/kangaroo.cpp @@ -0,0 +1,73 @@ +#include + +using namespace std; + +vector split_string(string); + +// Complete the kangaroo function below. +string kangaroo(int x1, int v1, int x2, int v2) { + int del_x = x1-x2; + int del_v = v2-v1; + + float k = (float)del_x/del_v; + + if(k<0){return "NO";} + if(floor(k)==k){return "YES";} + return "NO"; + +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + string x1V1X2V2_temp; + getline(cin, x1V1X2V2_temp); + + vector x1V1X2V2 = split_string(x1V1X2V2_temp); + + int x1 = stoi(x1V1X2V2[0]); + + int v1 = stoi(x1V1X2V2[1]); + + int x2 = stoi(x1V1X2V2[2]); + + int v2 = stoi(x1V1X2V2[3]); + + string result = kangaroo(x1, v1, x2, v2); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} diff --git a/Hackerrank/C++/mapsSTL.cpp b/Hackerrank/C++/mapsSTL.cpp new file mode 100644 index 00000000..6b8c66ee --- /dev/null +++ b/Hackerrank/C++/mapsSTL.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +//Problem https://www.hackerrank.com/challenges/cpp-maps/problem + +int main() { + /* Enter your code here. Read input from STDIN. Print output to STDOUT */ + int iQueries, iType; + long long iData; + string sName; + unordered_map mStudents; + cin >> iQueries; + while (iQueries--){ + cin >> iType; + switch (iType){ + case 1: + cin >> sName >> iData; + mStudents[sName] += iData; + break; + case 2: + cin >> sName; + mStudents[sName] = 0; + break; + case 3: + cin >> sName; + cout << mStudents[sName] << endl; + break; + default: + break; + } + } + return 0; +} \ No newline at end of file diff --git a/Hackerrank/C++/plusMinus.cpp b/Hackerrank/C++/plusMinus.cpp new file mode 100644 index 00000000..d1f03a8b --- /dev/null +++ b/Hackerrank/C++/plusMinus.cpp @@ -0,0 +1,77 @@ +#include + +using namespace std; + +vector split_string(string); + +// Complete the plusMinus function below. +void plusMinus(vector arr) { + int a=0,b=0,c=0,n; + n=arr.size(); + for(int i=0;i0) + a=a+1; + else if(arr[i]<0) + b=b+1; + else c=c+1; + + } + float x=a*1.0/n,y=b*1.0/n,z=c*1.0/n; + printf("%.6f\n%.6f\n%.6f", x,y,z); + // cout<> n; + cin.ignore(numeric_limits::max(), '\n'); + + string arr_temp_temp; + getline(cin, arr_temp_temp); + + vector arr_temp = split_string(arr_temp_temp); + + vector arr(n); + + for (int i = 0; i < n; i++) { + int arr_item = stoi(arr_temp[i]); + + arr[i] = arr_item; + } + + plusMinus(arr); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} diff --git a/Hackerrank/C++/printLinkedList.cpp b/Hackerrank/C++/printLinkedList.cpp new file mode 100644 index 00000000..69b53f5b --- /dev/null +++ b/Hackerrank/C++/printLinkedList.cpp @@ -0,0 +1,69 @@ +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list + +class SinglyLinkedListNode { + public: + int data; + SinglyLinkedListNode *next; + + SinglyLinkedListNode(int node_data) { + this->data = node_data; + this->next = nullptr; + } +}; + +class SinglyLinkedList { + public: + SinglyLinkedListNode *head; + SinglyLinkedListNode *tail; + + SinglyLinkedList() { + this->head = nullptr; + this->tail = nullptr; + } + + void insert_node(int node_data) { + SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data); + + if (!this->head) { + this->head = node; + } else { + this->tail->next = node; + } + + this->tail = node; + } +}; + +void free_singly_linked_list(SinglyLinkedListNode* node) { + while (node) { + SinglyLinkedListNode* temp = node; + node = node->next; + + free(temp); + } +} + +// Complete the printLinkedList function below. + +/* + * For your reference: + * + * SinglyLinkedListNode { + * int data; + * SinglyLinkedListNode* next; + * }; + * + */ +void printLinkedList(SinglyLinkedListNode* head) { + SinglyLinkedListNode* curr = head; + while (curr){ + cout << curr->data << endl; + curr = curr->next; + } +} + +int main() \ No newline at end of file diff --git a/Hackerrank/C++/sayHelloWorld.cpp b/Hackerrank/C++/sayHelloWorld.cpp new file mode 100644 index 00000000..8da50c66 --- /dev/null +++ b/Hackerrank/C++/sayHelloWorld.cpp @@ -0,0 +1,10 @@ +#include +#include +using namespace std; + +// Problem https://www.hackerrank.com/challenges/cpp-hello-world/problem + +int main() { + printf("Hello, World!"); + return 0; +} \ No newline at end of file diff --git a/Hackerrank/C++/solveMeFirst.cpp b/Hackerrank/C++/solveMeFirst.cpp new file mode 100644 index 00000000..03e2190a --- /dev/null +++ b/Hackerrank/C++/solveMeFirst.cpp @@ -0,0 +1,22 @@ +#include +#include +#include +#include +#include +using namespace std; + +//Problem https://www.hackerrank.com/challenges/solve-me-first/problem + +int solveMeFirst(int a, int b) { + // Hint: Type return a+b; below + return a + b; +} + +int main() { + int num1, num2; + int sum; + cin>>num1>>num2; + sum = solveMeFirst(num1,num2); + cout< + +using namespace std; + +// Complete the viralAdvertising function below. +int viralAdvertising(int n) { + int likes = 0; + int current = 5; + while(n){ + likes += current/2; + current/=2; + current = 3*current; + n--; + } + return likes; + +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + int n; + cin >> n; + cin.ignore(numeric_limits::max(), '\n'); + + int result = viralAdvertising(n); + + fout << result << "\n"; + + fout.close(); + + return 0; +} diff --git a/Hackerrank/C/Counting Sort 2.cpp b/Hackerrank/C/Counting Sort 2.cpp new file mode 100644 index 00000000..8fee443e --- /dev/null +++ b/Hackerrank/C/Counting Sort 2.cpp @@ -0,0 +1,147 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); +char** split_string(char*); + +// Complete the countingSort function below. + +// Please store the size of the integer array to be returned in result_count pointer. For example, +// int a[3] = {1, 2, 3}; +// +// *result_count = 3; +// +// return a; +// +int* countingSort(int arr_count, int* arr, int* result_count) { + int flag,k=0; + int temp[100]; + * result_count=arr_count; + int *result=malloc(arr_count*sizeof(int)); + for(int i=0;i<100;i++) + temp[i]=0; + for(int i=0;i +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); + +// Complete the gridChallenge function below. + +// Please either make the string static or allocate on the heap. For example, +// static char str[] = "hello world"; +// return str; +// +// OR +// +// char* str = "hello world"; +// return str; +// +char* gridChallenge(int grid_count, char** grid) { + + char* ans1="YES"; + char* ans2="NO"; + + char key; + int k; + for(int i=0;i=0&&grid[i][k]>key) + { + grid[i][k+1]=grid[i][k]; + k=k-1; + } + grid[i][k+1]=key; + } + } + + for(int i=0;igrid[j+1][i]) + return ans2; + } + } + return ans1; + +} + +int main() +{ + FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w"); + + char* t_endptr; + char* t_str = readline(); + int t = strtol(t_str, &t_endptr, 10); + + if (t_endptr == t_str || *t_endptr != '\0') { exit(EXIT_FAILURE); } + + for (int t_itr = 0; t_itr < t; t_itr++) { + char* n_endptr; + char* n_str = readline(); + int n = strtol(n_str, &n_endptr, 10); + + if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); } + + char** grid = malloc(n * sizeof(char*)); + + for (int i = 0; i < n; i++) { + char* grid_item = readline(); + + *(grid + i) = grid_item; + } + + int grid_count = n; + + char* result = gridChallenge(grid_count, grid); + + fprintf(fptr, "%s\n", result); + } + + fclose(fptr); + + return 0; +} + +char* readline() { + size_t alloc_length = 1024; + size_t data_length = 0; + char* data = malloc(alloc_length); + + while (true) { + char* cursor = data + data_length; + char* line = fgets(cursor, alloc_length - data_length, stdin); + + if (!line) { break; } + + data_length += strlen(cursor); + + if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } + + size_t new_length = alloc_length << 1; + data = realloc(data, new_length); + + if (!data) { break; } + + alloc_length = new_length; + } + + if (data[data_length - 1] == '\n') { + data[data_length - 1] = '\0'; + } + + data = realloc(data, data_length); + + return data; +} diff --git a/Hackerrank/C/ModifiedKaprekarNumbers.c b/Hackerrank/C/ModifiedKaprekarNumbers.c new file mode 100644 index 00000000..ebae93f7 --- /dev/null +++ b/Hackerrank/C/ModifiedKaprekarNumbers.c @@ -0,0 +1,118 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); + +// Complete the kaprekarNumbers function below. +void kaprekarNumbers(int p, int q) { + long i;int check=0; + int cnt=0; long sum1=0,sum2=0; + + + for(i=p;i<=q;i++) + {long sq=pow(i,2); + + long a=sq,b=sq; + cnt=0;sum1=sum2=0; + int flag=1;int mult1=0,mult2=0; + + while(a>0) + {a=a/10; + cnt=cnt+1;} + + + while(b>0) + {int rem=b%10; + b=b/10; + + if(flag<=floor((cnt+1)/2)) + {sum1=sum1+(rem*pow(10,mult1)); + flag+=1;mult1++;continue;} + + if(flag>floor((cnt+1)/2)&&flag<=cnt) + {sum2+=rem*pow(10,mult2); + flag+=1;mult2++;}} + int tot=sum1+sum2; + + if((tot==i)&&(tot%100!=0)&&(tot!=10)) + {printf("%d ",i); + check++;}} + + + + if(check==0) + printf("INVALID RANGE"); + + + + + + +} + +int main() +{ + char* p_endptr; + char* p_str = readline(); + int p = strtol(p_str, &p_endptr, 10); + + if (p_endptr == p_str || *p_endptr != '\0') { exit(EXIT_FAILURE); } + + char* q_endptr; + char* q_str = readline(); + int q = strtol(q_str, &q_endptr, 10); + + if (q_endptr == q_str || *q_endptr != '\0') { exit(EXIT_FAILURE); } + + kaprekarNumbers(p, q); + + return 0; +} + +char* readline() { + size_t alloc_length = 1024; + size_t data_length = 0; + char* data = malloc(alloc_length); + + while (true) { + char* cursor = data + data_length; + char* line = fgets(cursor, alloc_length - data_length, stdin); + + if (!line) { + break; + } + + data_length += strlen(cursor); + + if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { + break; + } + + alloc_length <<= 1; + + data = realloc(data, alloc_length); + + if (!line) { + break; + } + } + + if (data[data_length - 1] == '\n') { + data[data_length - 1] = '\0'; + + data = realloc(data, data_length); + } else { + data = realloc(data, data_length + 1); + + data[data_length] = '\0'; + } + + return data; +} diff --git a/Hackerrank/C/PlusMinus.c b/Hackerrank/C/PlusMinus.c new file mode 100644 index 00000000..e90488a9 --- /dev/null +++ b/Hackerrank/C/PlusMinus.c @@ -0,0 +1,35 @@ +#include +#include +#include +#include +#include +#include +#include + +int main() +{ + int n; + + scanf("%d",&n); + int arr[n]; + int arr_i; + + for(arr_i = 0; arr_i < n; arr_i++) + { + scanf("%d",&arr[arr_i]); + } + float a=0 ,b=0 ,c=0 ; + for(arr_i = 0; arr_i < n; arr_i++) + { if(arr[arr_i]> 0) + {a += 1;} + + else if(arr[arr_i]<0) + {b += 1;} + + else + {c += 1;} + } + printf("%f\n%f\n%f\n", a/n, b/n, c/n); + + return 0; +} diff --git a/Hackerrank/C/Priyanka And Toys.cpp b/Hackerrank/C/Priyanka And Toys.cpp new file mode 100644 index 00000000..ece05440 --- /dev/null +++ b/Hackerrank/C/Priyanka And Toys.cpp @@ -0,0 +1,96 @@ +#include + +using namespace std; + +vector split_string(string); + +// Complete the toys function below. +int toys(vector w) { + sort(w.begin(),w.end()); + long int flag=0,z,count; + long int size; + while(!w.empty()) + { + count=0; + flag++; + size=w.size(); + z=w.front(); + + /*for(int i=0;i=z&&w[i]<=z+4) + count++; + + } + for(int i=0;i> n; + cin.ignore(numeric_limits::max(), '\n'); + + string w_temp_temp; + getline(cin, w_temp_temp); + + vector w_temp = split_string(w_temp_temp); + + vector w(n); + + for (int i = 0; i < n; i++) { + int w_item = stoi(w_temp[i]); + + w[i] = w_item; + } + + int result = toys(w); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} diff --git a/Hackerrank/Go/plus-minus.go b/Hackerrank/Go/plus-minus.go new file mode 100644 index 00000000..66da2d5d --- /dev/null +++ b/Hackerrank/Go/plus-minus.go @@ -0,0 +1,69 @@ +// Author: Vatsal Chanana +// URL: https://www.hackerrank.com/challenges/plus-minus/problem + +package main + +import ( + "bufio" + "fmt" + "io" + "os" + "strconv" + "strings" +) + +// Complete the plusMinus function below. +func plusMinus(arr []int32) { + pos, neg, zero := 0, 0, 0 + + for _, num := range arr { + if num > 0 { + pos++ + } else if num == 0 { + zero++ + } else { + neg++ + } + } + + size := float32(len(arr)) + fmt.Println(float32(pos) / size) + fmt.Println(float32(neg) / size) + fmt.Println(float32(zero) / size) +} + +func main() { + reader := bufio.NewReaderSize(os.Stdin, 1024 * 1024) + + nTemp, err := strconv.ParseInt(readLine(reader), 10, 64) + checkError(err) + n := int32(nTemp) + + arrTemp := strings.Split(readLine(reader), " ") + + var arr []int32 + + for i := 0; i < int(n); i++ { + arrItemTemp, err := strconv.ParseInt(arrTemp[i], 10, 64) + checkError(err) + arrItem := int32(arrItemTemp) + arr = append(arr, arrItem) + } + + plusMinus(arr) +} + +func readLine(reader *bufio.Reader) string { + str, _, err := reader.ReadLine() + if err == io.EOF { + return "" + } + + return strings.TrimRight(string(str), "\r\n") +} + +func checkError(err error) { + if err != nil { + panic(err) + } +} diff --git a/Hackerrank/Java/CountingValleys.java b/Hackerrank/Java/CountingValleys.java new file mode 100644 index 00000000..d2aee83e --- /dev/null +++ b/Hackerrank/Java/CountingValleys.java @@ -0,0 +1,33 @@ +//This code is contributed by Shreevatsa N, @vatsa287 + +package practice; +public class CountingValleys { + public int getValleyCount(String s) + { + int altitudeCount = 0, valleyCount = 0; + + for(int i=0; i stack = new ArrayDeque(); + static Deque maxValues = new ArrayDeque(); + + public static void push(int x) { + stack.push(x); + + if (maxValues.isEmpty() || maxValues.peek() <= x) { + maxValues.push(x); + } + } + + public static int getMax() { + return maxValues.peek(); + } + + public static void pop() { + if (stack.isEmpty()) return; + + int ret = stack.pop(); + + if (ret == maxValues.peek()) { + maxValues.pop(); + } + } + } + + public static void main(String[] args) { + /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ + + try { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String line = br.readLine(); + int N = Integer.parseInt(line); + + Stack stack = new Stack(); + + for (int i = 0; i < N; i++) { + line = br.readLine(); + if (line.contains(" ")) { + int num = Integer.parseInt(line.split(" ")[1]); + stack.push(num); + } else if (line.equals("2")) { + stack.pop(); + } else { + System.out.println(stack.getMax()); + } + } + } catch (IOException e) {} + } +} diff --git a/Hackerrank/Java/Pairs.java b/Hackerrank/Java/Pairs.java new file mode 100644 index 00000000..2344f6d2 --- /dev/null +++ b/Hackerrank/Java/Pairs.java @@ -0,0 +1,61 @@ +//This code is contributed by Shreevatsa N, @vatsa287 +import java.io.*; +import java.math.*; +import java.security.*; +import java.text.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.regex.*; + +public class Solution { + + // Complete the pairs function below. + static int pairs(int k, int[] arr) { + HashSet set = new HashSet(); + int count = 0; + for(int i=0;i colors = new HashSet<>(); + int pairs = 0; + + for (int i = 0; i < n; i++) { + if (!colors.contains(c[i])) { + colors.add(c[i]); + } else { + pairs++; + colors.remove(c[i]); + } + } + + System.out.println(pairs); \ No newline at end of file diff --git a/Hackerrank/Java/Sock-Merchant/Thumbs.db b/Hackerrank/Java/Sock-Merchant/Thumbs.db new file mode 100644 index 00000000..8db21009 Binary files /dev/null and b/Hackerrank/Java/Sock-Merchant/Thumbs.db differ diff --git a/Hackerrank/Java/Staircase.java b/Hackerrank/Java/Staircase.java new file mode 100644 index 00000000..498a1ca1 --- /dev/null +++ b/Hackerrank/Java/Staircase.java @@ -0,0 +1,29 @@ +import java.util.*; +class Staircase +{ +public static void main(String[] args) +{ +Scanner sc = new Scanner (System.in); +int N = sc.nextInt(); + + for(int i=1;i<=n;i++) + { + for(int j=1;j<=n;j++) + + { + if((i+j)>n) + { + System.out.print("#"); + } + else + { + System.out.print(" "); + } + + } + System.out.println(); + + } +sc.close(); +} +} \ No newline at end of file diff --git a/Hackerrank/Java/StringConstruction.java b/Hackerrank/Java/StringConstruction.java new file mode 100644 index 00000000..db672e56 --- /dev/null +++ b/Hackerrank/Java/StringConstruction.java @@ -0,0 +1,38 @@ +import java.io.*; +import java.math.*; +import java.security.*; +import java.text.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.regex.*; + +public class Solution { + + // Complete the stringConstruction function below. + static int stringConstruction(String s) { + + + } + + private static final Scanner scanner = new Scanner(System.in); + + public static void main(String[] args) throws IOException { + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); + + int q = scanner.nextInt(); + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); + + for (int qItr = 0; qItr < q; qItr++) { + String s = scanner.nextLine(); + + int result = stringConstruction(s); + + bufferedWriter.write(String.valueOf(result)); + bufferedWriter.newLine(); + } + + bufferedWriter.close(); + + scanner.close(); + } +} diff --git a/Hackerrank/Java/The-maximum-subarray.java b/Hackerrank/Java/The-maximum-subarray.java new file mode 100644 index 00000000..bb65ea24 --- /dev/null +++ b/Hackerrank/Java/The-maximum-subarray.java @@ -0,0 +1,89 @@ +//This code is contributed by Shreevatsa N, @vatsa287 +import java.io.*; +import java.math.*; +import java.security.*; +import java.text.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.regex.*; + +public class Solution { + + // Complete the maxSubarray function below. + static int[] maxSubarray(int[] arr) { + int ans = 0, wsum = 0, nonnegsum = 0; + //ans is the final answer when there is contigous subarray case, wsum is the subarray sum, nonnegsum is the sum of all non negative nos when we deal with non contigous elements. + ans = wsum = arr[0]; //Using Kadanes Algorithm for this case of contigous subarray. So intialize the wsum , ans as arr[0] i.e is the first element. + int ansArray[] = new int[2]; //Since we have to return the array having the result for two cases we set size as 2 which consits of the maxsum from both the est case respectiiely. + + for(int i=1;i arr[i]) + { + wsum+=arr[i]; + } + else + { + wsum = arr[i]; + } + ans = Math.max(ans,wsum); //ans is the result for maximum subarray having contigous elements. + } + Arrays.sort(arr); //Sort the array in order to find out if all elements are negative or not. If yes then the last element will be negative, + System.out.println("ans is "+ arr[0]); + if(arr[arr.length-1]<0) + { + nonnegsum = arr[arr.length-1]; //if all elements are negative then max amongst them is the last element in that sorted array. + } + else + { + for(int i=0;i=0) + nonnegsum+=arr[i]; + } + } + ansArray[0] = ans; + ansArray[1] = nonnegsum; + return ansArray; + } + + private static final Scanner scanner = new Scanner(System.in); + + public static void main(String[] args) throws IOException { + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); + + int t = scanner.nextInt(); + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); + + for (int tItr = 0; tItr < t; tItr++) { + int n = scanner.nextInt(); + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); + + int[] arr = new int[n]; + + String[] arrItems = scanner.nextLine().split(" "); + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); + + for (int i = 0; i < n; i++) { + int arrItem = Integer.parseInt(arrItems[i]); + arr[i] = arrItem; + } + + int[] result = maxSubarray(arr); + + for (int i = 0; i < result.length; i++) { + bufferedWriter.write(String.valueOf(result[i])); + + if (i != result.length - 1) { + bufferedWriter.write(" "); + } + } + + bufferedWriter.newLine(); + } + + bufferedWriter.close(); + + scanner.close(); + } +} diff --git a/Hackerrank/Java/cats-and-mouse.java b/Hackerrank/Java/cats-and-mouse.java new file mode 100644 index 00000000..83669a29 --- /dev/null +++ b/Hackerrank/Java/cats-and-mouse.java @@ -0,0 +1,62 @@ +//This code is contruibuted by Shreevatsa N, @vatsa287 +import java.io.*; +import java.math.*; +import java.security.*; +import java.text.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.regex.*; + +public class Solution { + + // Complete the catAndMouse function below. + static String catAndMouse(int x, int y, int z) { + + + if(Math.abs(z-y) < Math.abs(z-x)) + { + return "Cat B"; + } + else if(Math.abs(z-y) > Math.abs(z-x)) + { + return "Cat A"; + } + else if(Math.abs(z-y) == Math.abs(z-x)) + { + return "Mouse C"; + } + + throw new IllegalArgumentException("NOT A VALID CO-ORDINATE"); + + + + } + + private static final Scanner scanner = new Scanner(System.in); + + public static void main(String[] args) throws IOException { + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); + + int q = scanner.nextInt(); + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); + + for (int qItr = 0; qItr < q; qItr++) { + String[] xyz = scanner.nextLine().split(" "); + + int x = Integer.parseInt(xyz[0]); + + int y = Integer.parseInt(xyz[1]); + + int z = Integer.parseInt(xyz[2]); + + String result = catAndMouse(x, y, z); + + bufferedWriter.write(result); + bufferedWriter.newLine(); + } + + bufferedWriter.close(); + + scanner.close(); + } +} diff --git a/Hackerrank/Java/leftRotation.java b/Hackerrank/Java/leftRotation.java new file mode 100644 index 00000000..d647ce90 --- /dev/null +++ b/Hackerrank/Java/leftRotation.java @@ -0,0 +1,58 @@ +//This code is contributed by Shreevatsa N, @vatsa287 +import java.io.*; +import java.math.*; +import java.security.*; +import java.text.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.regex.*; + +public class Solution { + + public void LeftRotation(int n, int k, int a[]) + { + k = k%a.length; + reverse(a,0,n-1); + reverse(a,n-k,n-1); + reverse(a,0,n-k-1); + for(int i=0;i { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/** +* The variables 'firstInteger', 'firstDecimal', and 'firstString' are declared for you -- do not modify them. +* Print three lines: +* 1. The sum of 'firstInteger' and the Number representation of 'secondInteger'. +* 2. The sum of 'firstDecimal' and the Number representation of 'secondDecimal'. +* 3. The concatenation of 'firstString' and 'secondString' ('firstString' must be first). +* +* Parameter(s): +* secondInteger - The string representation of an integer. +* secondDecimal - The string representation of a floating-point number. +* secondString - A string consisting of one or more space-separated words. +**/ +function performOperation(secondInteger, secondDecimal, secondString) { + // Declare a variable named 'firstInteger' and initialize with integer value 4. + const firstInteger = 4; + + // Declare a variable named 'firstDecimal' and initialize with floating-point value 4.0. + const firstDecimal = 4.0; + + // Declare a variable named 'firstString' and initialize with the string "HackerRank". + const firstString = 'HackerRank '; + + // Write code that uses console.log to print the sum of the 'firstInteger' and 'secondInteger' (converted to a Number type) on a new line. + console.log(firstInteger + Number(secondInteger)); + + // Write code that uses console.log to print the sum of 'firstDecimal' and 'secondDecimal' (converted to a Number type) on a new line. + console.log(firstDecimal + Number(secondDecimal)); + + // Write code that uses console.log to print the concatenation of 'firstString' and 'secondString' on a new line. The variable 'firstString' must be printed first. + console.log(firstString + secondString); +} + + +function main() { + const secondInteger = readLine(); + const secondDecimal = readLine(); + const secondString = readLine(); + + performOperation(secondInteger, secondDecimal, secondString); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day0-hello-world.js b/Hackerrank/JavaScript/10-Days-Of-JS/day0-hello-world.js new file mode 100644 index 00000000..7826dc44 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day0-hello-world.js @@ -0,0 +1,45 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/** +* A line of code that prints "Hello, World!" on a new line is provided in the editor. +* Write a second line of code that prints the contents of 'parameterVariable' on a new line. +* +* Parameter: +* parameterVariable - A string of text. +**/ +function greeting(parameterVariable) { + // This line prints 'Hello, World!' to the console: + console.log('Hello, World!'); + console.log(parameterVariable); + // Write a line of code that prints parameterVariable to stdout using console.log: + +} + + +function main() { + const parameterVariable = readLine(); + + greeting(parameterVariable); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day1-arithmetic-operators.js b/Hackerrank/JavaScript/10-Days-Of-JS/day1-arithmetic-operators.js new file mode 100644 index 00000000..083ce7bc --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day1-arithmetic-operators.js @@ -0,0 +1,56 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/** +* Calculate the area of a rectangle. +* +* length: The length of the rectangle. +* width: The width of the rectangle. +* +* Return a number denoting the rectangle's area. +**/ +function getArea(length, width) { + let area; + // Write your code here + area = length * width; + + return area; +} + +/** +* Calculate the perimeter of a rectangle. +* +* length: The length of the rectangle. +* width: The width of the rectangle. +* +* Return a number denoting the perimeter of a rectangle. +**/ +function getPerimeter(length, width) { + let perimeter; + // Write your code here + perimeter = 2 * (length + width); + return perimeter; +} + + diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day1-function.js b/Hackerrank/JavaScript/10-Days-Of-JS/day1-function.js new file mode 100644 index 00000000..19eef5b0 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day1-function.js @@ -0,0 +1,35 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} +/* + * Create the function factorial here + */ +function factorial(n) { + var result = 1; + while (n > 0) { + result *=n; + n--; + } + return result; +} + diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day1-let-const.js b/Hackerrank/JavaScript/10-Days-Of-JS/day1-let-const.js new file mode 100644 index 00000000..230b4f88 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day1-let-const.js @@ -0,0 +1,41 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +function main() { + // Write your code here. Read input using 'readLine()' and print output using 'console.log()'. + const PI = Math.PI; + let r = Number(readLine()); + // Print the area of the circle: + console.log((PI * (r * r))); + // Print the perimeter of the circle: + console.log(2 * (PI * r)); + try { + // Attempt to redefine the value of constant variable PI + PI = 0; + // Attempt to print the value of PI + console.log(PI); + } catch(error) { + console.error("You correctly declared 'PI' as a constant."); + } +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day2-if-else.js b/Hackerrank/JavaScript/10-Days-Of-JS/day2-if-else.js new file mode 100644 index 00000000..59ce0fd8 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day2-if-else.js @@ -0,0 +1,48 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +function getGrade(score) { + let grade; + // Write your code here + if (score > 25 && score <= 30) + grade = 'A'; + else if (score > 20 && score <= 25) + grade = 'B'; + if (score > 15 && score <= 20) + grade = 'C'; + else if (score > 10 && score <= 15) + grade = 'D'; + if (score > 5 && score <= 10) + grade = 'E'; + else if (score >= 0 && score <= 5) + grade = 'F'; + return grade; +} + + +function main() { + const score = +(readLine()); + + console.log(getGrade(score)); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day2-loops.js b/Hackerrank/JavaScript/10-Days-Of-JS/day2-loops.js new file mode 100644 index 00000000..1a20dee3 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day2-loops.js @@ -0,0 +1,53 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/* + * Complete the vowelsAndConsonants function. + * Print your output using 'console.log()'. + */ +function vowelsAndConsonants(s) { + var i = 0; + while (s[i]!=null) + { + if ((s[i] == 'a') || (s[i] == 'e') || (s[i] == 'i') || (s[i] == 'o') || (s[i] == 'u')) { + console.log(s[i]); + } + i++; + } + i = 0; + while (s[i] != null) { + if (!((s[i] == 'a') || (s[i] == 'e') || (s[i] == 'i') || (s[i] == 'o') || (s[i] == 'u'))) { + console.log(s[i]); + } + i++; + } + +} + + +function main() { + const s = readLine(); + + vowelsAndConsonants(s); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day2-switch.js b/Hackerrank/JavaScript/10-Days-Of-JS/day2-switch.js new file mode 100644 index 00000000..3097aa68 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day2-switch.js @@ -0,0 +1,62 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +function getLetter(s) { + let letter; + // Write your code here + switch (s[0]){ + case 'a': + case 'e': + case 'i': + case 'o': + case 'u': + letter = 'A'; + break; + case 'b': + case 'c': + case 'd': + case 'f': + case 'g': + letter = 'B'; + break; + case 'h': + case 'j': + case 'k': + case 'l': + case 'm': + letter = 'C'; + break; + default: + letter = 'D'; + break; + } + return letter; +} + + +function main() { + const s = readLine(); + + console.log(getLetter(s)); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day3-arrays.js b/Hackerrank/JavaScript/10-Days-Of-JS/day3-arrays.js new file mode 100644 index 00000000..c5b30604 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day3-arrays.js @@ -0,0 +1,51 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/** +* Return the second largest number in the array. +* @param {Number[]} nums - An array of numbers. +* @return {Number} The second largest number in the array. +**/ +function getSecondLargest(nums) { + // Complete the function + nums.sort(function (a, b) { return a - b });; + let res = 0; + let largest = nums.pop(); + + for (let i = nums.length; i != null; i--) { + if (nums[i] < largest) { + res = nums[i]; + break; + } + } + return res; +} + + +function main() { + const n = +(readLine()); + const nums = readLine().split(' ').map(Number); + + console.log(getSecondLargest(nums)); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day3-throw.js b/Hackerrank/JavaScript/10-Days-Of-JS/day3-throw.js new file mode 100644 index 00000000..bcc8a1e3 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day3-throw.js @@ -0,0 +1,54 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/* + * Complete the isPositive function. + * If 'a' is positive, return "YES". + * If 'a' is 0, throw an Error with the message "Zero Error" + * If 'a' is negative, throw an Error with the message "Negative Error" + */ +function isPositive(a) { + if (a > 0) { + return 'YES'; + } else if (a == 0) { + throw new Error('Zero Error'); + } else if (a < 0) { + throw new Error('Negative Error'); + } +} + + +function main() { + const n = +(readLine()); + + for (let i = 0; i < n; i++) { + const a = +(readLine()); + + try { + console.log(isPositive(a)); + } catch (e) { + console.log(e.message); + } + } +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day3-try-catch.js b/Hackerrank/JavaScript/10-Days-Of-JS/day3-try-catch.js new file mode 100644 index 00000000..63dc1c1a --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day3-try-catch.js @@ -0,0 +1,42 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +function reverseString(s) { + try { + s = s.split("").reverse().join(""); + } + catch (e) { + console.log(e.message); + } + finally { + console.log(s); + } +} + + +function main() { + const s = eval(readLine()); + + reverseString(s); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day4-class.js b/Hackerrank/JavaScript/10-Days-Of-JS/day4-class.js new file mode 100644 index 00000000..f4df9b4a --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day4-class.js @@ -0,0 +1,22 @@ +/* + * Implement a Polygon class with the following properties: + * 1. A constructor that takes an array of integer side lengths. + * 2. A 'perimeter' method that returns the sum of the Polygon's side lengths. + */ +class Polygon{ + constructor(sides) { + this.sides = sides; + } + perimeter() { + return this.sides.reduce((total, side) => total + side); + } + +} + +const rectangle = new Polygon([10, 20, 10, 20]); +const square = new Polygon([10, 10, 10, 10]); +const pentagon = new Polygon([10, 20, 30, 40, 43]); + +console.log(rectangle.perimeter()); +console.log(square.perimeter()); +console.log(pentagon.perimeter()); diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day4-count-objects.js b/Hackerrank/JavaScript/10-Days-Of-JS/day4-count-objects.js new file mode 100644 index 00000000..8c744ad3 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day4-count-objects.js @@ -0,0 +1,55 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/* + * Return a count of the total number of objects 'o' satisfying o.x == o.y. + * + * Parameter(s): + * objects: an array of objects with integer properties 'x' and 'y' + */ +function getCount(objects) { + let count = 0 + + for (let item of objects) { + if (item.x == item.y) { + count++ + } + + } + return count +} + + +function main() { + const n = +(readLine()); + let objects = []; + + for (let i = 0; i < n; i++) { + const [a, b] = readLine().split(' '); + + objects.push({x: +(a), y: +(b)}); + } + + console.log(getCount(objects)); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day4-objects.js b/Hackerrank/JavaScript/10-Days-Of-JS/day4-objects.js new file mode 100644 index 00000000..f8e8093f --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day4-objects.js @@ -0,0 +1,48 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/* + * Complete the Rectangle function + */ +function Rectangle(a, b) { + let rec = { + length: a, + width: b, + perimeter: 2 * (a + b), + area : a * b + }; + return rec; + } + +function main() { + const a = +(readLine()); + const b = +(readLine()); + + const rec = new Rectangle(a, b); + + console.log(rec.length); + console.log(rec.width); + console.log(rec.perimeter); + console.log(rec.area); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day5-arrows.js b/Hackerrank/JavaScript/10-Days-Of-JS/day5-arrows.js new file mode 100644 index 00000000..299575dd --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day5-arrows.js @@ -0,0 +1,41 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/* + * Modify and return the array so that all even elements are doubled and all odd elements are tripled. + * + * Parameter(s): + * nums: An array of numbers. + */ +function modifyArray(nums) { + return nums.map(elem => elem % 2 == 0 ? elem * 2 : elem * 3); +} + + +function main() { + const n = +(readLine()); + const a = readLine().split(' ').map(Number); + + console.log(modifyArray(a).toString().split(',').join(' ')); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day5-inheritance.js b/Hackerrank/JavaScript/10-Days-Of-JS/day5-inheritance.js new file mode 100644 index 00000000..20255bfa --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day5-inheritance.js @@ -0,0 +1,33 @@ +class Rectangle { + constructor(w, h) { + this.w = w; + this.h = h; + } +} + +/* + * Write code that adds an 'area' method to the Rectangle class' prototype + */ +Rectangle.prototype.area = function () { + return (this.w * this.h); +} +/* + * Create a Square class that inherits from Rectangle and implement its class constructor + */ +class Square extends Rectangle{ + constructor(s) { + super(s,s); + } +} + + +if (JSON.stringify(Object.getOwnPropertyNames(Square.prototype)) === JSON.stringify([ 'constructor' ])) { + const rec = new Rectangle(3, 4); + const sqr = new Square(3); + + console.log(rec.area()); + console.log(sqr.area()); +} else { + console.log(-1); + console.log(-1); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day5-template-literals.js b/Hackerrank/JavaScript/10-Days-Of-JS/day5-template-literals.js new file mode 100644 index 00000000..448ccebe --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day5-template-literals.js @@ -0,0 +1,54 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/* + * Determine the original side lengths and return an array: + * - The first element is the length of the shorter side + * - The second element is the length of the longer side + * + * Parameter(s): + * literals: The tagged template literal's array of strings. + * expressions: The tagged template literal's array of expression values (i.e., [area, perimeter]). + */ +function sides(literals, ...expressions) { + let arr = []; + let area = Number(expressions[0]); + let perimeter = Number(expressions[1]); + arr[0] = Number((perimeter + Math.sqrt((perimeter * perimeter) - (16 * area)))/4) + arr[1] = Number((perimeter - Math.sqrt((perimeter * perimeter) - (16 * area)))/4) + return arr.sort(); +} + + +function main() { + let s1 = +(readLine()); + let s2 = +(readLine()); + + [s1, s2] = [s1, s2].sort(); + + const [x, y] = sides`The area is: ${s1 * s2}.\nThe perimeter is: ${2 * (s1 + s2)}.`; + + console.log((s1 === x) ? s1 : -1); + console.log((s2 === y) ? s2 : -1); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day6-bitwise.js b/Hackerrank/JavaScript/10-Days-Of-JS/day6-bitwise.js new file mode 100644 index 00000000..f6e945ce --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day6-bitwise.js @@ -0,0 +1,39 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} +function getMaxLessThanK(n, k) { + // (╯°□°)╯︵ ┻━┻ + return ((k | (k - 1)) > n) ? (k - 2) : (k - 1); +} + + + +function main() { + const q = +(readLine()); + + for (let i = 0; i < q; i++) { + const [n, k] = readLine().split(' ').map(Number); + + console.log(getMaxLessThanK(n, k)); + } +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day6-date.js b/Hackerrank/JavaScript/10-Days-Of-JS/day6-date.js new file mode 100644 index 00000000..50b9a4b2 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day6-date.js @@ -0,0 +1,43 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +// The days of the week are: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" +function getDayName(dateString) { + let date = new Date(dateString); + let dayNum = date.getDay(); + + let dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] + return dayNames[dayNum]; +} + + +function main() { + const d = +(readLine()); + + for (let i = 0; i < d; i++) { + const date = readLine(); + + console.log(getDayName(date)); + } +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex1.js b/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex1.js new file mode 100644 index 00000000..d9e34332 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex1.js @@ -0,0 +1,40 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +function regexVar() { + /* + * Declare a RegExp object variable named 're' + * It must match a string that starts and ends with the same vowel (i.e., {a, e, i, o, u}) + */ + const re = new RegExp("^([aeiou]).*\\1$") + return re; +} + + +function main() { + const re = regexVar(); + const s = readLine(); + + console.log(re.test(s)); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex2.js b/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex2.js new file mode 100644 index 00000000..98c8d31c --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex2.js @@ -0,0 +1,41 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +function regexVar() { + /* + * Declare a RegExp object variable named 're' + * It must match a string that starts with 'Mr.', 'Mrs.', 'Ms.', 'Dr.', or 'Er.', + * followed by one or more letters. + */ + const re = /^(Mr|Mrs|Ms|Dr|Er)\.[A-Za-z]*$/ + return re; +} + + +function main() { + const re = regexVar(); + const s = readLine(); + + console.log(!!s.match(re)); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex3.js b/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex3.js new file mode 100644 index 00000000..00fdae03 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex3.js @@ -0,0 +1,44 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +function regexVar() { + /* + * Declare a RegExp object variable named 're' + * It must match ALL occurrences of numbers in a string. + */ + const re = /\d+/g + return re; +} + + +function main() { + const re = regexVar(); + const s = readLine(); + + const r = s.match(re); + + for (const e of r) { + console.log(e); + } +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day8-button-container.html b/Hackerrank/JavaScript/10-Days-Of-JS/day8-button-container.html new file mode 100644 index 00000000..779a8039 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day8-button-container.html @@ -0,0 +1,44 @@ + + + + + Buttons Grid + + + +

+ + + + + + + + + +
+ + + + diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day8-button.html b/Hackerrank/JavaScript/10-Days-Of-JS/day8-button.html new file mode 100644 index 00000000..be377481 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day8-button.html @@ -0,0 +1,25 @@ + + + + + Button + + + + + + + + diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day9-binary-calculator.html b/Hackerrank/JavaScript/10-Days-Of-JS/day9-binary-calculator.html new file mode 100644 index 00000000..e5d236ad --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day9-binary-calculator.html @@ -0,0 +1,105 @@ + + + + + + Binary Calculator + + + + +
+
+
+ + + + + + + + +
+
+ + + + diff --git a/Hackerrank/PHP/DayOfProgrammer.php b/Hackerrank/PHP/DayOfProgrammer.php new file mode 100644 index 00000000..79e4e434 --- /dev/null +++ b/Hackerrank/PHP/DayOfProgrammer.php @@ -0,0 +1,49 @@ +=1919){ + if($year%4 != 0) { + $mday = 243; + } + else { + if($year%400 != 0 && $year%100 == 0) { + $mday = 243; + } else { + $mday = 244; + } + } + } + elseif ($year == 1918) { + + $mday = 243-13; + } + else { + if($year%4 == 0) { + $mday = 244; + } + else { + $mday = 243; + } + } + + $dp = 256-$mday; + + $str = $dp.".".$mn.".".$year; + + return $str; + +} + +$fptr = fopen(getenv("OUTPUT_PATH"), "w"); + +$year = intval(trim(fgets(STDIN))); + +$result = dayOfProgrammer($year); + +fwrite($fptr, $result . "\n"); + +fclose($fptr); + diff --git a/Hackerrank/ExtraLongFactorial.php b/Hackerrank/PHP/ExtraLongFactorial.php similarity index 100% rename from Hackerrank/ExtraLongFactorial.php rename to Hackerrank/PHP/ExtraLongFactorial.php diff --git a/Hackerrank/kangaroo.php b/Hackerrank/PHP/kangaroo.php similarity index 100% rename from Hackerrank/kangaroo.php rename to Hackerrank/PHP/kangaroo.php diff --git a/Hackerrank/Python/Arithmetic Operators.py b/Hackerrank/Python/Arithmetic Operators.py new file mode 100644 index 00000000..42744d59 --- /dev/null +++ b/Hackerrank/Python/Arithmetic Operators.py @@ -0,0 +1,10 @@ +#Author: Rakshit Naidu + + +if __name__ == '__main__': + a = int(input()) + b = int(input()) + + print(a+b) + print(a-b) + print(a*b) diff --git a/Hackerrank/Python/DesignerPdfViewer.py b/Hackerrank/Python/DesignerPdfViewer.py new file mode 100644 index 00000000..96194a48 --- /dev/null +++ b/Hackerrank/Python/DesignerPdfViewer.py @@ -0,0 +1,30 @@ +#This code is contributed by Shreevatsa N, @vatsa287 +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the designerPdfViewer function below. +def designerPdfViewer(h, word): + max1=0 + ch='' + count = len(word) + for ch in range(0,len(word)): + if h[ ord(word[ch]) - 97 ] > max1: + max1 = h[ord(word[ch]) - 97] + return count * max1 +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + h = list(map(int, input().rstrip().split())) + + word = input() + + result = designerPdfViewer(h, word) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Hackerrank/Python/DijkstraShortestReach2.py b/Hackerrank/Python/DijkstraShortestReach2.py new file mode 100644 index 00000000..8a16a1cc --- /dev/null +++ b/Hackerrank/Python/DijkstraShortestReach2.py @@ -0,0 +1,49 @@ + +from collections import defaultdict + +import heapq + + +def dijkstra(S, N, G): + D = {} + H = [(0, S)] + + for n in range(1, N + 1): + D[n] = float('inf') + + D[S] = 0 + + while H: + t = heapq.heappop(H) + for h in G[t[1]]: + if D[h[0]] > D[t[1]] + h[1]: + D[h[0]] = D[t[1]] + h[1] + if (h[1], h[0]) in H: + H.remove((h[1], h[0])) + heapq.heapify(H) + heapq.heappush(H, (D[h[0]], h[0])) + + return D + + +def main(): + T = int(input()) + + for _ in range(T): + N, M = [int(i) for i in input().split()] + + G = defaultdict(set) + + for _ in range(M): + e = [int(i) for i in input().split()] + G[e[0]].add((e[1], e[2])) + G[e[1]].add((e[0], e[2])) + + S = int(input()) + + D = dijkstra(S, N, G) + print(' '.join(str(D[n]) if D[n] != float('inf') else '-1' for n in range(1, N + 1) if n != S)) + + +if __name__ == "__main__": + main() diff --git a/Hackerrank/Python/JourneytotheMoon.py b/Hackerrank/Python/JourneytotheMoon.py new file mode 100644 index 00000000..e8e32d8d --- /dev/null +++ b/Hackerrank/Python/JourneytotheMoon.py @@ -0,0 +1,54 @@ +MAXN = 100000+5 +MAXI = 1000000+5 + +n,i = input().split(' ') + +n = int(n) +I = int(i) + +a = [-1 for i in range(0,n)] +co = [1 for i in range(0,n)] + +def F(x): + t = x + while ( a[t] != -1 ): + t = a[t] + if ( ( a[x] != -1 ) & ( a[x] != t ) ): + a[x] = t + #co[t] += co[x] + return t + +def U(x,y): + fx = F(x) + fy = F(y) + #print("!! %d %d"%(fx,fy)) + if ( fx != fy ): + a[fx] = fy + co[fy] += co[fx] + + +for i in range(0,I): + x,y = input().split(' ') + x = int(x) + y = int(y) + U(x,y) + + +l = [] +c = 0 +A = 0 + +for i in range(0,n): + if ( a[i] == -1 ): + l.insert(c,co[i]) + A += co[i] + c = c+1 + +#print(l) +ans = 0 +for i in range(0,c): + ans += l[i]*(A-l[i]) + +ans = ans//2 + +print(ans) diff --git a/Hackerrank/Python/Loops.py b/Hackerrank/Python/Loops.py new file mode 100644 index 00000000..f2ccb039 --- /dev/null +++ b/Hackerrank/Python/Loops.py @@ -0,0 +1,7 @@ +#Author: Rakshit Naidu + +if __name__ == '__main__': + n = int(input()) + + for i in range(n): + print(i**2) diff --git a/Hackerrank/Python/Mod Divmod.py b/Hackerrank/Python/Mod Divmod.py new file mode 100644 index 00000000..de3b2e69 --- /dev/null +++ b/Hackerrank/Python/Mod Divmod.py @@ -0,0 +1,11 @@ +#Author: Rakshit Naidu + +a = int(input()) +b = int(input()) + +x = a // b +y = a % b + +print(x) +print(y) +print((x,y,)) diff --git a/Hackerrank/Python/Mutations.py b/Hackerrank/Python/Mutations.py new file mode 100644 index 00000000..7eb9d10b --- /dev/null +++ b/Hackerrank/Python/Mutations.py @@ -0,0 +1,11 @@ +#Author: Rakshit Naidu + +def mutate_string(string, position, character): + + return string[0:position]+character+string[position+1:] + +if __name__ == '__main__': + s = input() + i, c = input().split() + s_new = mutate_string(s, int(i), c) + print(s_new) diff --git a/Hackerrank/Python/Pairs.py b/Hackerrank/Python/Pairs.py new file mode 100644 index 00000000..6e9dafe0 --- /dev/null +++ b/Hackerrank/Python/Pairs.py @@ -0,0 +1,37 @@ +#This code is contributed by Shreevatsa N, @vatsa287 +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the pairs function below. +def pairs(k, arr): + s = {}; + count=0 + for i in arr: #add all elements to the set, it does not have any duplicates present. + s[i] = i + for a in arr: #for every element in the array, check if its complement exists in the set. + g = a + k #complement = array ele + given target + if g in s: #if complement is present in the set, it means that already found and added so increment counter + count+=1 + return count; + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + nk = input().split() + + n = int(nk[0]) + + k = int(nk[1]) + + arr = list(map(int, input().rstrip().split())) + + result = pairs(k, arr) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Hackerrank/Python/Python b/Hackerrank/Python/Python new file mode 100644 index 00000000..e69de29b diff --git a/Hackerrank/Python/Python If-Else.py b/Hackerrank/Python/Python If-Else.py new file mode 100644 index 00000000..d1e0d30d --- /dev/null +++ b/Hackerrank/Python/Python If-Else.py @@ -0,0 +1,13 @@ +#Author: Rakshit Naidu + +if __name__ == '__main__': + n = int(input().strip()) + + if n % 2 ==0 and n > 20: + print("Not Weird") + elif n % 2 ==0 and n > 5 and n < 21: + print("Weird") + elif n % 2==0 and n > 1 and n < 6: + print("Not Weird") + elif n % 2 == 1: + print("Weird") diff --git a/Hackerrank/Python/Simple Array Sum.py b/Hackerrank/Python/Simple Array Sum.py new file mode 100644 index 00000000..84830aa3 --- /dev/null +++ b/Hackerrank/Python/Simple Array Sum.py @@ -0,0 +1,12 @@ +#By NAIRITYA TALE +#Algorithms +#Data Structures + +size=int(input("Entre The Size Of Array")) #takes input as size of array +ar=[] #array declaration +arrsum=0 +for i in range(0,size): + ar.append(input()) #input in the array + arrsum=arrsum+int(ar[i]) #summation of array +print("The Sum Of The Array Is =",arrsum) #result display +exit() diff --git a/Hackerrank/Python/Sock-Merchant.py b/Hackerrank/Python/Sock-Merchant.py new file mode 100644 index 00000000..9bded289 --- /dev/null +++ b/Hackerrank/Python/Sock-Merchant.py @@ -0,0 +1,42 @@ +#This code is contributed by Shreevatsa N, @vatsa287 + +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the sockMerchant function below. +def sockMerchant(n, ar): + op = [] #remove the duplicates. + for ch in ar: + if ch not in op: + op.append(ch) + count = 0 #intialize count of pairs to 0. + for i in op: #check the count of all elements in original list. + if ar.count(i) == 1: #if the no of duplicates is 0, then no pair available. + count = count + 0 + elif ar.count(i)%2==1 and ar.count(i)>1: #if count > 1 i.e pair and odd meaning one should be removed to form a pair. + c = ar.count(i) + c=c-1 #the removal is done here + count = count + (c/2) #since no of pair is required divide by 2. + elif ar.count(i)%2==0 and ar.count(i)>1: #if count > 1 i.e pair and its even , just divide by 2 to get no of pair socks present. + count = count + ar.count(i)/2 + c = 0 #make c = 0 for next iteration so it is treated as a fresh case for next odd element. + return(int(count)) #return the non decimal part. + + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + n = int(input()) + + ar = list(map(int, input().rstrip().split())) + + result = sockMerchant(n, ar) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Hackerrank/Staircase.py b/Hackerrank/Python/Staircase.py similarity index 100% rename from Hackerrank/Staircase.py rename to Hackerrank/Python/Staircase.py diff --git a/Hackerrank/Python/Swap_Case.py b/Hackerrank/Python/Swap_Case.py new file mode 100644 index 00000000..d9b192ba --- /dev/null +++ b/Hackerrank/Python/Swap_Case.py @@ -0,0 +1,8 @@ +def swapCase(s): + a = '' + for x in s: + if x.isupper(): + a = a + x.lower() + else: + a = a + x.upper() + return a diff --git a/Hackerrank/Python/The-maximum-subarray.py b/Hackerrank/Python/The-maximum-subarray.py new file mode 100644 index 00000000..3a7aaa2e --- /dev/null +++ b/Hackerrank/Python/The-maximum-subarray.py @@ -0,0 +1,44 @@ +#This code is contributed by Shreevatsa N, @vatsa287 +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the maxSubarray function below. +def maxSubarray(arr): + wsum,ans = arr[0],arr[0] + nonnegsum = 0 + ansarray = [] + for i in range(1,len(arr)): + wsum = max(arr[i],wsum+arr[i]) + ans = max(wsum,ans) + arr.sort() + if(arr[len(arr)-1]<0): + nonnegsum = arr[len(arr)-1] + else: + for i in arr: + if i >=0: + nonnegsum+=i + ansarray.append(ans) + ansarray.append(nonnegsum) + return ansarray + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + t = int(input()) + + for t_itr in range(t): + n = int(input()) + + arr = list(map(int, input().rstrip().split())) + + result = maxSubarray(arr) + + fptr.write(' '.join(map(str, result))) + fptr.write('\n') + + fptr.close() diff --git a/Hackerrank/Time_Conversion.py b/Hackerrank/Python/Time_Conversion.py similarity index 94% rename from Hackerrank/Time_Conversion.py rename to Hackerrank/Python/Time_Conversion.py index d3aa39dd..76c06dfe 100644 --- a/Hackerrank/Time_Conversion.py +++ b/Hackerrank/Python/Time_Conversion.py @@ -1,34 +1,34 @@ -# Author Name : Akshay Jain -#!/bin/python3 - -import os -import sys - -# -# Complete the timeConversion function below. -# -def timeConversion(s): - # - # Write your code here. - # - hh, mm, ssNu = s.split(':') - ss = ssNu[:2] - u = ssNu[2:] - - if u == 'AM' : - if hh == '12' : - hh = '00' - else : - if hh != '12' : - hh = (int(hh) + 12 ) - return ("{}:{}:{}".format(hh, mm, ss)) -if __name__ == '__main__': - f = open(os.environ['OUTPUT_PATH'], 'w') - - s = input() - - result = timeConversion(s) - - f.write(result + '\n') - - f.close() +# Author Name : Akshay Jain +#!/bin/python3 + +import os +import sys + +# +# Complete the timeConversion function below. +# +def timeConversion(s): + # + # Write your code here. + # + hh, mm, ssNu = s.split(':') + ss = ssNu[:2] + u = ssNu[2:] + + if u == 'AM' : + if hh == '12' : + hh = '00' + else : + if hh != '12' : + hh = (int(hh) + 12 ) + return ("{}:{}:{}".format(hh, mm, ss)) +if __name__ == '__main__': + f = open(os.environ['OUTPUT_PATH'], 'w') + + s = input() + + result = timeConversion(s) + + f.write(result + '\n') + + f.close() diff --git a/Hackerrank/Python/athleteSort.py b/Hackerrank/Python/athleteSort.py new file mode 100644 index 00000000..9014ba7a --- /dev/null +++ b/Hackerrank/Python/athleteSort.py @@ -0,0 +1,12 @@ +# URL: https://www.hackerrank.com/challenges/python-sort-sort/ + +from __future__ import print_function + +n,m = [ int(i) for i in raw_input().split() ] +arr = [ map(int, raw_input().split()) for _ in xrange(n) ] +k = int(raw_input()) + +arr.sort(key = lambda x: x[k]) + +for a in arr: + print (*a) \ No newline at end of file diff --git a/Hackerrank/Python/birthdayCakeCandles.py b/Hackerrank/Python/birthdayCakeCandles.py new file mode 100644 index 00000000..1124417e --- /dev/null +++ b/Hackerrank/Python/birthdayCakeCandles.py @@ -0,0 +1,24 @@ +#This code is contributed by Shreevatsa N, @vatsa287 +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the birthdayCakeCandles function below. +def birthdayCakeCandles(ar): + return(ar.count(max(ar))) +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + ar_count = int(input()) + + ar = list(map(int, input().rstrip().split())) + + result = birthdayCakeCandles(ar) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Hackerrank/Python/compareTheTriplets.py b/Hackerrank/Python/compareTheTriplets.py new file mode 100644 index 00000000..97fd8f95 --- /dev/null +++ b/Hackerrank/Python/compareTheTriplets.py @@ -0,0 +1,35 @@ +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the compareTriplets function below. +def compareTriplets(a, b): + count_a=0 + count_b=0 + for i in range(3): + + if(a[i]>b[i]): + count_a+=1 + elif(a[i]= 38 and n <= 100: #check if marks is within this range + if n%5 == 3 or n%5==4 : #if the remainder with 5 is either 3 or 4 since 5rem is treated as 0 + if n%10 > 5: #unit place is greater > 5 + temp = 10-n%10 + n = n + temp #add the required difference for round off + list1.append(n) + elif n%10 < 5: + temp = 5 - n%10 + n = n + temp + list1.append(n) + elif n%5 == 0 or n%5 == 1 or n%5 == 2: #if the difference between the marks and next multiple is less than 3 + list1.append(n) + else: #if marks is out of range then no rounding up + list1.append(n) + return(list1) + + + + + + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + grades_count = int(input().strip()) + + grades = [] + + for _ in range(grades_count): + grades_item = int(input().strip()) + grades.append(grades_item) + + result = gradingStudents(grades) + + fptr.write('\n'.join(map(str, result))) + fptr.write('\n') + + fptr.close() diff --git a/Hackerrank/Python/hashTablesRansomNote.py b/Hackerrank/Python/hashTablesRansomNote.py new file mode 100644 index 00000000..e1a565cd --- /dev/null +++ b/Hackerrank/Python/hashTablesRansomNote.py @@ -0,0 +1,55 @@ +#Author: turtlejump +#Issue: Hash Tables: Ransom Note: https://www.hackerrank.com/challenges/ctci-ransom-note/ + +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the checkMagazine function below. +def store(array, word): + # Hash the word (then squeeze it down to a smaller size) + # Append it to the hashed location (assuming its a linked list) + array[hash(word) % len(array)].append(word) + + +def retrieve(array, word): + # Hash the word (squeeze it down to a smaller size) + loc = hash(word) % len(array) + # Loop through the particular hashed location, check for the word + for i in range(len(array[loc])): + if array[loc][i] == word: + array[loc].pop(i) + return True + return False + +def checkMagazine(magazine, note): + # Implement a hash table + # Our actual hash table + magSize = len(magazine) + mag = [[] for i in range(magSize)] + for i in magazine: + store(mag, i) + for i in note: + if retrieve(mag, i) == True: + continue + else: + print('No') + return + print('Yes') + return +if __name__ == '__main__': + mn = input().split() + + m = int(mn[0]) + + n = int(mn[1]) + + magazine = input().rstrip().split() + + note = input().rstrip().split() + + checkMagazine(magazine, note) diff --git a/Hackerrank/Python/leftRotation.py b/Hackerrank/Python/leftRotation.py new file mode 100644 index 00000000..61d07976 --- /dev/null +++ b/Hackerrank/Python/leftRotation.py @@ -0,0 +1,24 @@ +#!/bin/python3 + +import math +import os +import random +import re +import sys + + + +if __name__ == '__main__': + nd = input().split() + + n = int(nd[0]) + + d = int(nd[1]) + + a = list(map(int, input().rstrip().split())) + b=a[0:d] + c=a[d:n] + e=c+b + for i in e: + print(i,end=' ') + diff --git a/Hackerrank/Python/listComprehensions.py b/Hackerrank/Python/listComprehensions.py new file mode 100644 index 00000000..879a4229 --- /dev/null +++ b/Hackerrank/Python/listComprehensions.py @@ -0,0 +1,9 @@ +#This code is contributed by Shreevatsa N, @vatsa287 +if __name__ == '__main__': + x = int(input()) + y = int(input()) + z = int(input()) + n = int(input()) + + lis = [ [i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if((i+j+k)!=n) ] + print(lis) diff --git a/Hackerrank/Python/mini-max-sum.py b/Hackerrank/Python/mini-max-sum.py new file mode 100644 index 00000000..a51f37b3 --- /dev/null +++ b/Hackerrank/Python/mini-max-sum.py @@ -0,0 +1,18 @@ +#This code is contributed by Shreevatsa N, @vatsa287 +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the miniMaxSum function below. +def miniMaxSum(arr): + min_int = sum(arr) - max(arr) + max_int = sum(arr) - min(arr) + print(min_int, max_int) +if __name__ == '__main__': + arr = list(map(int, input().rstrip().split())) + + miniMaxSum(arr) diff --git a/Hackerrank/Python/plus-minus.py b/Hackerrank/Python/plus-minus.py new file mode 100644 index 00000000..7d89a288 --- /dev/null +++ b/Hackerrank/Python/plus-minus.py @@ -0,0 +1,32 @@ +#This code is contributed by Shreevatsa N, @vatsa287 +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the plusMinus function below. +def plusMinus(arr): + length = len(arr) + cpos , cneg ,czer = 0, 0, 0 + for i in range(0,length): + if arr[i] > 0: #counters for pos,neg and zero nus. + cpos+=1 + elif arr[i] < 0: + cneg+=1 + else: + czer+=1 + print(cpos/length) #no of pos/neg/zero nos divided by total nos. + print(cneg/length) + print(czer/length) + + + +if __name__ == '__main__': + n = int(input()) + + arr = list(map(int, input().rstrip().split())) + + plusMinus(arr) diff --git a/Hackerrank/Python/sherlockAndAnagrams.py b/Hackerrank/Python/sherlockAndAnagrams.py new file mode 100644 index 00000000..e99e3ad1 --- /dev/null +++ b/Hackerrank/Python/sherlockAndAnagrams.py @@ -0,0 +1,47 @@ +#Author: turtlejump +#Issue: Sherlock and Anagrams: https://www.hackerrank.com/challenges/sherlock-and-anagrams/ + +#!/bin/python3 + +import math +import os +import random +import re +import sys +from string import ascii_lowercase +# Complete the sherlockAndAnagrams function below. + +def sherlockAndAnagrams(s): + ALPHABET = ascii_lowercase + + sigs = {} + + sig = [0 for _ in ALPHABET] + for letter in s: + sig[ord(letter) - ord(ALPHABET[0])] += 1 + + for i in range(len(s)): + for j in range(i, len(s)): + sig = [0 for _ in ALPHABET] + for letter in s[i:j+1]: + sig[ord(letter) - ord(ALPHABET[0])] += 1 + sig = tuple(sig) + sigs[sig] = sigs.get(sig, 0) + 1 + res = 0 + for count in sigs.values(): + res += count * (count - 1)/2 + return int(res) + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + q = int(input()) + + for q_itr in range(q): + s = input() + + result = sherlockAndAnagrams(s) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Hackerrank/Python/timeConversion.py b/Hackerrank/Python/timeConversion.py new file mode 100644 index 00000000..96c33b34 --- /dev/null +++ b/Hackerrank/Python/timeConversion.py @@ -0,0 +1,35 @@ +#!/bin/python3 + +import os +import sys + +# +# Complete the timeConversion function below. +# +def timeConversion(s): + a=s[0:2] + b=int(a) + if(s[8]=="P"): + if b<12: + b+=12 + if(s[8]=="A"): + if b==12: + b = 0 + c=s[2:8] + d = str(b) + if b <10: + d = '0'+d + out=d+c + return out + + +if __name__ == '__main__': + f = open(os.environ['OUTPUT_PATH'], 'w') + + s = input() + + result = timeConversion(s) + + f.write(result + '\n') + + f.close() diff --git a/Hackerrank/Python/twoStrings.py b/Hackerrank/Python/twoStrings.py new file mode 100644 index 00000000..f6f4ac46 --- /dev/null +++ b/Hackerrank/Python/twoStrings.py @@ -0,0 +1,49 @@ +#Author: turtlejump +#Issue: Two Strings: https://www.hackerrank.com/challenges/two-strings/ + +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the twoStrings function below. +def store(array, char): + loc = hash(char) % len(array) + array[loc].append(char) + +def search(array, char): + loc = hash(char) % len(array) + for i in array[loc]: + if i == char: + return True + return False + +def twoStrings(s1, s2): + map1 = [[] for i in range(len(s1))] + # store all characters into a hash table + for i in s1: + store(map1, i) + # if any of the characters inside s1 matches s2, then return 'YES' + for i in s2: + if search(map1, i) == True: + return 'YES' + return 'NO' + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + q = int(input()) + + for q_itr in range(q): + s1 = input() + + s2 = input() + + result = twoStrings(s1, s2) + + fptr.write(result + '\n') + + fptr.close() diff --git a/Hackerrank/Ruby/Gemstones.rb b/Hackerrank/Ruby/Gemstones.rb new file mode 100644 index 00000000..63c278e3 --- /dev/null +++ b/Hackerrank/Ruby/Gemstones.rb @@ -0,0 +1,22 @@ +# URL: https://www.hackerrank.com/challenges/gem-stones/ + +n = gets.strip.to_i +arr = Array.new +n.times do + arr << gets.strip +end + +result = 0 + +arr[0].chars.to_a.uniq.to_s.each_char do |chr| + common = true + arr.each do |x| + unless x.index(chr) + common = false + break + end + end + result += 1 if common +end + +print result diff --git a/Hackerrank/compareTheTriplets.cpp b/Hackerrank/compareTheTriplets.cpp new file mode 100644 index 00000000..fa777540 --- /dev/null +++ b/Hackerrank/compareTheTriplets.cpp @@ -0,0 +1,108 @@ +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/compare-the-triplets/problem + +string ltrim(const string &); +string rtrim(const string &); +vector split(const string &); + +// Complete the compareTriplets function below. +vector compareTriplets(vector a, vector b) { + + int iAliceScore = 0, iBobScore = 0; + + for (int i = 0; i < 3; ++i){ + if (a[i] > b[i]) ++iAliceScore; + else if (a[i] < b[i]) ++iBobScore; + } + + return {iAliceScore, iBobScore}; +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + string a_temp_temp; + getline(cin, a_temp_temp); + + vector a_temp = split(rtrim(a_temp_temp)); + + vector a(3); + + for (int i = 0; i < 3; i++) { + int a_item = stoi(a_temp[i]); + + a[i] = a_item; + } + + string b_temp_temp; + getline(cin, b_temp_temp); + + vector b_temp = split(rtrim(b_temp_temp)); + + vector b(3); + + for (int i = 0; i < 3; i++) { + int b_item = stoi(b_temp[i]); + + b[i] = b_item; + } + + vector result = compareTriplets(a, b); + + for (int i = 0; i < result.size(); i++) { + fout << result[i]; + + if (i != result.size() - 1) { + fout << " "; + } + } + + fout << "\n"; + + fout.close(); + + return 0; +} + +string ltrim(const string &str) { + string s(str); + + s.erase( + s.begin(), + find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) + ); + + return s; +} + +string rtrim(const string &str) { + string s(str); + + s.erase( + find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), + s.end() + ); + + return s; +} + +vector split(const string &str) { + vector tokens; + + string::size_type start = 0; + string::size_type end = 0; + + while ((end = str.find(" ", start)) != string::npos) { + tokens.push_back(str.substr(start, end - start)); + + start = end + 1; + } + + tokens.push_back(str.substr(start)); + + return tokens; +} diff --git a/HelloWorld/Algo.py b/HelloWorld/Algo.py new file mode 100644 index 00000000..ef67deb1 --- /dev/null +++ b/HelloWorld/Algo.py @@ -0,0 +1,32 @@ +# Python 3.x code to demonstrate star pattern + +# Function to demonstrate printing pattern triangle +def triangle(n): + + # number of spaces + k = 2*n - 2 + + # outer loop to handle number of rows + for i in range(0, n): + + # inner loop to handle number spaces + # values changing acc. to requirement + for j in range(0, k): + print(end=" ") + + # decrementing k after each loop + k = k - 1 + + # inner loop to handle number of columns + # values changing acc. to outer loop + for j in range(0, i+1): + + # printing stars + print("* ", end="") + + # ending line after each row + print("\r") + +# Driver Code +n = 5 +triangle(n) diff --git a/HelloWorld/Factorial.kt b/HelloWorld/Factorial.kt new file mode 100644 index 00000000..e2e3e72b --- /dev/null +++ b/HelloWorld/Factorial.kt @@ -0,0 +1,10 @@ +# Finidng factorial using recursion in kotlin + fun main(args: Array) { + val number = 4 + val result: Long + result = factorial(number) + println("Factorial of $number = $result") + } + fun factorial(n: Int): Long { + return if (n == 1) n.toLong() else n*factorial(n-1) + } diff --git a/HelloWorld/Factorial_DoWhileLoop.kt b/HelloWorld/Factorial_DoWhileLoop.kt new file mode 100644 index 00000000..fe9b1f57 --- /dev/null +++ b/HelloWorld/Factorial_DoWhileLoop.kt @@ -0,0 +1,11 @@ +# Kotlin program to find the factorial of a number using do-while loop +fun main(args: Array) { + var number = 6 + var factorial = 1 + + do { + factorial *= number + number-- + }while(number > 0) + println("Factorial of 6 is $factorial") +} diff --git a/HelloWorld/HanoiTower.c b/HelloWorld/HanoiTower.c index d21e04bf..7f20ee5b 100644 --- a/HelloWorld/HanoiTower.c +++ b/HelloWorld/HanoiTower.c @@ -1,21 +1,21 @@ -#include - -// C recursive function to solve tower of hanoi puzzle -void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) -{ - if (n == 1) - { - printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod); - return; - } - towerOfHanoi(n-1, from_rod, aux_rod, to_rod); - printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod); - towerOfHanoi(n-1, aux_rod, to_rod, from_rod); -} - -int main() -{ - int n = 4; // Number of disks - towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods - return 0; -} +#include + +// C recursive function to solve tower of hanoi puzzle +void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) +{ + if (n == 1) + { + printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod); + return; + } + towerOfHanoi(n-1, from_rod, aux_rod, to_rod); + printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod); + towerOfHanoi(n-1, aux_rod, to_rod, from_rod); +} + +int main() +{ + int n = 4; // Number of disks + towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods + return 0; +} diff --git a/HelloWorld/HelloWordC b/HelloWorld/HelloWordC new file mode 100644 index 00000000..ebb92cef --- /dev/null +++ b/HelloWorld/HelloWordC @@ -0,0 +1,7 @@ +#include +#include + +int main(){ + printf("Hello World\n"); + return(0); +} diff --git a/HelloWorld/HelloWorld.Scala b/HelloWorld/HelloWorld.Scala new file mode 100644 index 00000000..04ee421d --- /dev/null +++ b/HelloWorld/HelloWorld.Scala @@ -0,0 +1,11 @@ + +// Scala program to print Hello World! +object Geeks +{ + // Main Method + def main(args: Array[String]) + { + // prints Hello World + println("Hello World!") + } +} diff --git a/HelloWorld/HelloWorld.cs b/HelloWorld/HelloWorld.cs new file mode 100644 index 00000000..a68542dc --- /dev/null +++ b/HelloWorld/HelloWorld.cs @@ -0,0 +1,12 @@ +using System; + +namespace HelloWorld +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("Hello World!"); + } + } +} diff --git a/HelloWorld/HelloWorld.java b/HelloWorld/HelloWorld.java new file mode 100644 index 00000000..6c31ff73 --- /dev/null +++ b/HelloWorld/HelloWorld.java @@ -0,0 +1,9 @@ +/* HelloWorld.java + */ + +public class HelloWorld +{ + public static void main(String[] args) { + System.out.println("Hello World!"); + } +} diff --git a/HelloWorld/HelloWorld.pl b/HelloWorld/HelloWorld.pl new file mode 100644 index 00000000..07cb7698 --- /dev/null +++ b/HelloWorld/HelloWorld.pl @@ -0,0 +1,10 @@ +#!/usr/bin/perl +# usage perl HelloWorld.pl + +# Modules used +use strict; +use warnings; + +# Print function +print("Hello World!\n"); + diff --git a/HelloWorld/HelloWorldInGerman b/HelloWorld/HelloWorldInGerman new file mode 100644 index 00000000..30fa8fac --- /dev/null +++ b/HelloWorld/HelloWorldInGerman @@ -0,0 +1,6 @@ +public class HelloWorld +{ + public static void main(String[] args) { + System.out.println("Hallo Welt"); + } +} diff --git a/HelloWorld/RandomArrayGenerator.java b/HelloWorld/RandomArrayGenerator.java new file mode 100644 index 00000000..e0bfecd0 --- /dev/null +++ b/HelloWorld/RandomArrayGenerator.java @@ -0,0 +1,13 @@ +import java.util.concurrent.ThreadLocalRandom; + +// Generate a random Java int array with ThreadLocalRandom. Specify the minimum value, maximum value, and desired length of the array. +public class RandomArrayGenerator { + public static int[] randomArrayGenerator(int minValue, int maxValue, int arrayLength) { + int[] arr = new int[arrayLength]; + for (int i = 0; i < arrayLength; i++) { + int randomInt = ThreadLocalRandom.current().nextInt(minValue, maxValue); + arr[i] = randomInt; + } + return arr; + } +} \ No newline at end of file diff --git a/HelloWorld/factorial_tail_rec.kt b/HelloWorld/factorial_tail_rec.kt new file mode 100644 index 00000000..7ff10a7e --- /dev/null +++ b/HelloWorld/factorial_tail_rec.kt @@ -0,0 +1,8 @@ + # Factorial Using Tail Recursion + fun main(args: Array) { + val number = 5 + println("Factorial of $number = ${factorial(number)}") + } + tailrec fun factorial(n: Int, run: Int = 1): Long { + return if (n == 1) run.toLong() else factorial(n-1, run*n) + } diff --git a/HelloWorld/hello world b/HelloWorld/hello world new file mode 100644 index 00000000..50216b96 --- /dev/null +++ b/HelloWorld/hello world @@ -0,0 +1,8 @@ +#include + +int main() +{ + printf("Hello world!\n"); + printf("Happy Hacking!\n"); + return 0; +} diff --git a/HelloWorld/hello.c b/HelloWorld/hello.c index 059c5a0f..50216b96 100644 --- a/HelloWorld/hello.c +++ b/HelloWorld/hello.c @@ -2,6 +2,7 @@ int main() { - printf("Hello World!\n"); + printf("Hello world!\n"); + printf("Happy Hacking!\n"); return 0; } diff --git a/HelloWorld/hello.cpp b/HelloWorld/hello.cpp index 5bc3b38b..e8864b2b 100644 --- a/HelloWorld/hello.cpp +++ b/HelloWorld/hello.cpp @@ -3,6 +3,7 @@ using namespace std; int main() { - cout << "Hello World!" << endl; + cout << "Hello World!" ; + cout<< endl; return 0; } diff --git a/HelloWorld/helloHack.c b/HelloWorld/helloHack.c new file mode 100644 index 00000000..93b31ba6 --- /dev/null +++ b/HelloWorld/helloHack.c @@ -0,0 +1,7 @@ +#include + +int main() +{ + printf("Hello Hactoberfest 2019\n"); + return 0; +} diff --git a/HelloWorld/helloWorldSpanish.java b/HelloWorld/helloWorldSpanish.java new file mode 100644 index 00000000..9deb563c --- /dev/null +++ b/HelloWorld/helloWorldSpanish.java @@ -0,0 +1,9 @@ +/* HelloWorld.java + */ + +public class HelloWorldSpanish +{ + public static void main(String[] args) { + System.out.println("Hola Mundo!!"); + } +} \ No newline at end of file diff --git a/HelloWorld/hello_world.rb b/HelloWorld/hello_world.rb new file mode 100644 index 00000000..95dc0692 --- /dev/null +++ b/HelloWorld/hello_world.rb @@ -0,0 +1,2 @@ +#Hello World in Ruby +puts "Hello World!" diff --git a/HelloWorld/hellohack.py b/HelloWorld/hellohack.py new file mode 100644 index 00000000..c3c83042 --- /dev/null +++ b/HelloWorld/hellohack.py @@ -0,0 +1 @@ +print("Hello hacktoberfest") \ No newline at end of file diff --git a/HelloWorld/helloworld.cpp b/HelloWorld/helloworld.cpp new file mode 100644 index 00000000..9fcd9252 --- /dev/null +++ b/HelloWorld/helloworld.cpp @@ -0,0 +1,10 @@ +#include + +using namespace std; + +int main() +{ + cout<<"Hello World"; + + return 0; +} diff --git a/HelloWorld/helloworld.d b/HelloWorld/helloworld.d new file mode 100644 index 00000000..c353d70a --- /dev/null +++ b/HelloWorld/helloworld.d @@ -0,0 +1,5 @@ +import std.stdio; +void main() +{ + writeln("Hello, world!"); +} diff --git a/HelloWorld/helloworld.go b/HelloWorld/helloworld.go new file mode 100644 index 00000000..cf22b5e5 --- /dev/null +++ b/HelloWorld/helloworld.go @@ -0,0 +1,8 @@ +package main + +import "fmt" + +func main() { + + fmt.Println("Hello, World!") +} diff --git a/HelloWorld/helloworld.html b/HelloWorld/helloworld.html new file mode 100644 index 00000000..321fd2a7 --- /dev/null +++ b/HelloWorld/helloworld.html @@ -0,0 +1,9 @@ + + + + Hello World + + +

Hello World!
This is an example of a simple HTML page with Hello World at the Title.

+ + diff --git a/HelloWorld/helloworld.jl b/HelloWorld/helloworld.jl new file mode 100644 index 00000000..e55bd904 --- /dev/null +++ b/HelloWorld/helloworld.jl @@ -0,0 +1 @@ +println("Hello, World!") diff --git a/HelloWorld/helloworld.kt b/HelloWorld/helloworld.kt new file mode 100644 index 00000000..277db964 --- /dev/null +++ b/HelloWorld/helloworld.kt @@ -0,0 +1,3 @@ +fun main() { + println("Hello, World!") +} diff --git a/HelloWorld/helloworld.php b/HelloWorld/helloworld.php new file mode 100644 index 00000000..b30e5a0d --- /dev/null +++ b/HelloWorld/helloworld.php @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/HelloWorld/helloworld.rs b/HelloWorld/helloworld.rs new file mode 100644 index 00000000..0672e510 --- /dev/null +++ b/HelloWorld/helloworld.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, World!"); +} diff --git a/HelloWorld/movies_tvshows.py b/HelloWorld/movies_tvshows.py new file mode 100644 index 00000000..7519e437 --- /dev/null +++ b/HelloWorld/movies_tvshows.py @@ -0,0 +1,14 @@ +from selenium import webdriver +from selenium.webdriver.support.ui import WebDriverWait +from selenium.webdriver.support import expected_conditions as EC +from selenium.webdriver.common.keys import Keys +from selenium.webdriver.common.by import By +import time +c=2 +driver=webdriver.Chrome(r"C:\Users\Ayush\.spyder-py3/chromedriver") +driver.get("https://www.pirateproxy.space/") +search= driver.find_element_by_xpath("//input[@name='q']") +TVshow=input("Enter a movie or tv show") +search.send_keys(TVshow) +enter=driver.find_element_by_xpath("//input[@type='submit' and @title='Pirate Search']") +enter.click() diff --git a/HelloWorld/randomIntArrayGenerator.js b/HelloWorld/randomIntArrayGenerator.js new file mode 100644 index 00000000..9e87899e --- /dev/null +++ b/HelloWorld/randomIntArrayGenerator.js @@ -0,0 +1,8 @@ +// Generate a psuedo-random integer array of a given length and maximum value for rapid testing purposes. +function makeArrayN(length, max) { + const arr = []; + for (let i = 0; i < length; i++) { + arr.push(Math.round(Math.random() * max)); + } + return arr; +} \ No newline at end of file diff --git a/HelloWorld/sharing_of_files.py b/HelloWorld/sharing_of_files.py new file mode 100644 index 00000000..8eae8cda --- /dev/null +++ b/HelloWorld/sharing_of_files.py @@ -0,0 +1,7 @@ +import http.server +import socketserver +PORT = 8080 +Handler = http.server.SimpleHTTPRequestHandler +with socketserver.TCPServer(("", PORT), Handler) as httpd: + print("serving at port", PORT) + httpd.serve_forever() diff --git a/HelloWorld/vs_hello.py b/HelloWorld/vs_hello.py new file mode 100644 index 00000000..f0b303f3 --- /dev/null +++ b/HelloWorld/vs_hello.py @@ -0,0 +1 @@ +print('Hello World!') \ No newline at end of file diff --git "a/HelloWorld/\320\272\320\260\320\272_\320\262\320\260\321\210\320\270_\320\264\320\265\320\273\320\260.java" "b/HelloWorld/\320\272\320\260\320\272_\320\262\320\260\321\210\320\270_\320\264\320\265\320\273\320\260.java" new file mode 100644 index 00000000..5e28ec8f --- /dev/null +++ "b/HelloWorld/\320\272\320\260\320\272_\320\262\320\260\321\210\320\270_\320\264\320\265\320\273\320\260.java" @@ -0,0 +1,8 @@ +// HelloWorld.java.ru + +public class HelloWorld +{ + public static void main(String[] args) { + System.out.println("Привет, мир."); + } +} diff --git a/LeetCode/1137-nth-tribonacci-number.c b/LeetCode/1137-nth-tribonacci-number.c new file mode 100644 index 00000000..7c72d4ad --- /dev/null +++ b/LeetCode/1137-nth-tribonacci-number.c @@ -0,0 +1,24 @@ +//#1137 + int tribonacci(int n){ + + int first = 0; + int second = 1; + int third = 1; + int result = 0; + + if (n == 0) result = first; + if (n == 1) result = second; + if (n == 2) result = third; + + while(n > 2) + { + result = first + second + third; + first = second; + second = third; + third = result; + n--; + } + + return result; + +} diff --git a/LeetCode/303.py b/LeetCode/303.py index 8e607a0a..4874aa34 100644 --- a/LeetCode/303.py +++ b/LeetCode/303.py @@ -1,9 +1,7 @@ -''' -Problem: 303. Range Sum Query - Immutable -https://leetcode.com/problems/range-sum-query-immutable/ -Author: Luis Herrera -Summary: We use a prefix array to make the queries in constant time O(1). -''' +#Problem: 303. Range Sum Query - Immutable +#https://leetcode.com/problems/range-sum-query-immutable/ +#Author: Luis Herrera +#Summary: We use a prefix array to make the queries in constant time O(1). class NumArray(object): diff --git a/LeetCode/461HammingDistance.java b/LeetCode/461HammingDistance.java new file mode 100644 index 00000000..2d2d1ba0 --- /dev/null +++ b/LeetCode/461HammingDistance.java @@ -0,0 +1,18 @@ +class Solution { + public int hammingDistance(int x, int y) { + int count =0; + String newX=String.format("%32s", Integer.toBinaryString(x)).replaceAll(" ", "0"); + String newY = String.format("%32s", Integer.toBinaryString(y)).replaceAll(" ", "0"); + + for (int i=0;i List[int]: + outList = [] + for item in arr1: + if item in arr2 and item in arr3: + outList.append(item) + return(outList) diff --git a/LeetCode/5080-two-sum-bsts.py b/LeetCode/5080-two-sum-bsts.py new file mode 100644 index 00000000..0d0ae533 --- /dev/null +++ b/LeetCode/5080-two-sum-bsts.py @@ -0,0 +1,28 @@ +class Solution: + def twoSumBSTs(self, root1: TreeNode, root2: TreeNode, target: int) -> bool: + flag = 0 + listTemp = [] + def inOrderList(root) -> List[int]: + if not root: + return + inOrderList(root.left) + listTemp.append(root.val) + inOrderList(root.right) + return(listTemp) + + listTree1 = inOrderList(root1) + listTemp = [] + listTree2 = inOrderList(root2) + + for item1 in listTree1: + for item2 in listTree2: + result = item1 + item2 + if result == target: + flag = 1 + break + + if flag == 0: + return False + else: + return True + diff --git a/LeetCode/5205-uniq-no-occurence.py b/LeetCode/5205-uniq-no-occurence.py new file mode 100644 index 00000000..13dc8925 --- /dev/null +++ b/LeetCode/5205-uniq-no-occurence.py @@ -0,0 +1,21 @@ +class Solution(object): + def uniqueOccurrences(self, arr): + """ + :type arr: List[int] + :rtype: bool + """ + + uniqList = list(set(arr)) + countList = [] + + for x in uniqList: + count = arr.count(x) + if count not in countList: + countList.append(count) + + uniqCount = list(set(countList)) + + if (len(uniqList) == len(uniqCount)): + return True + else: + return False diff --git a/LeetCode/Add_Two_Numbers.java b/LeetCode/Add_Two_Numbers.java new file mode 100644 index 00000000..91b92d86 --- /dev/null +++ b/LeetCode/Add_Two_Numbers.java @@ -0,0 +1,47 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + + ListNode curr, dummy; + int l1Digit, l2Digit, sum, carry; + + sum = 0; + carry = 0; + + dummy = new ListNode(0); + curr = dummy; + + while (l1 != null || l2 != null) { + + // get the digit or treat it as 0 + l1Digit = (l1 != null) ? l1.val : 0; + l2Digit = (l2 != null) ? l2.val : 0; + + // calculate sum and carry + sum = carry + l1Digit + l2Digit; + carry = sum / 10; + + // assign the last digit of 'sum' and increment the 'curr' pointer + curr.next = new ListNode(sum % 10); + curr = curr.next; + + // in case l1 and l2 are not of the same length + if (l1 != null) l1 = l1.next; + if (l2 != null) l2 = l2.next; + } + + // there might be a carry still left + if (carry > 0) { + curr.next = new ListNode(carry); + } + + return dummy.next; + } +} \ No newline at end of file diff --git a/LeetCode/First_and_last_sorted_array.java b/LeetCode/First_and_last_sorted_array.java new file mode 100644 index 00000000..1c24da0f --- /dev/null +++ b/LeetCode/First_and_last_sorted_array.java @@ -0,0 +1,34 @@ +/* Problem 34. Find First and Last Position of Element in Sorted Array + * Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. + * + * Your algorithm's runtime complexity must be in the order of O(log n). + * + * If the target is not found in the array, return [-1, -1]. + */ + +public class First_and_last_sorted_array { + public int[] searchRange(int[] nums, int target) { + int[] targetRange = {-1, -1}; + + for(int i = 0; i=0; i--){ + if(nums[i] == target){ + targetRange[1] = i; + break; + } + } + + return targetRange; + + } +} diff --git a/LeetCode/ReverseInteger.cpp b/LeetCode/ReverseInteger.cpp new file mode 100644 index 00000000..f28d3a55 --- /dev/null +++ b/LeetCode/ReverseInteger.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int reverse(int x) { + long long rev = 0; + while(x){ + int d = x%10; + rev = rev*10 + d; + x = x/10; + } + return ((revINT_MAX)? 0: rev); + } +}; diff --git a/LeetCode/game-of-life.cpp b/LeetCode/game-of-life.cpp new file mode 100644 index 00000000..35369dd8 --- /dev/null +++ b/LeetCode/game-of-life.cpp @@ -0,0 +1,59 @@ +class Solution { +public: + void gameOfLife(vector>& board) { + // Neighbors array to find 8 neighboring cells for a given cell + int neighbors[3] = { 0, 1, -1 }; + + int rows = board.size(); + int cols = board[0].size(); + + // Iterate through board cell by cell. + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + + // For each cell count the number of live neighbors. + int liveNeighbors = 0; + + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + + if (!(neighbors[i] == 0 && neighbors[j] == 0)) { + int r = (row + neighbors[i]); + int c = (col + neighbors[j]); + + // Check the validity of the neighboring cell. + // and whether it was originally a live cell. + if ((r < rows && r >= 0) && (c < cols && c >= 0) && (abs(board[r][c]) == 1)) { + liveNeighbors += 1; + } + } + } + } + + // Rule 1 or Rule 3 + if ((board[row][col] == 1) && (liveNeighbors < 2 || liveNeighbors > 3)) { + // -1 signifies the cell is now dead but originally was live. + board[row][col] = -1; + } + // Rule 4 + if (board[row][col] == 0 && liveNeighbors == 3) { + // 2 signifies the cell is now live but was originally dead. + board[row][col] = 2; + } + } + } + + // Get the final representation for the newly updated board. + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + if (board[row][col] > 0) { + board[row][col] = 1; + } + else { + board[row][col] = 0; + } + } + } + + } +}; \ No newline at end of file diff --git a/LeetCode/twoSum.cpp b/LeetCode/twoSum.cpp new file mode 100644 index 00000000..adac5e35 --- /dev/null +++ b/LeetCode/twoSum.cpp @@ -0,0 +1,21 @@ +vector twoSum(vector &numbers, int target) +{ + //Key is the number and value is its index in the vector. + unordered_map hash; + vector result; + for (int i = 0; i < numbers.size(); i++) { + int numberToFind = target - numbers[i]; + + //if numberToFind is found in map, return them + if (hash.find(numberToFind) != hash.end()) { + //+1 because indices are NOT zero based + result.push_back(hash[numberToFind] + 1); + result.push_back(i + 1); + return result; + } + + //number was not found. Put it in the map. + hash[numbers[i]] = i; + } + return result; +} diff --git a/README.md b/README.md index 52c72f9e..9e61eb68 100644 --- a/README.md +++ b/README.md @@ -14,3 +14,6 @@ You can also contribute to problem solutions of problems available on various pl - Do follow the convention mentioned. ### PS: Do not pick a problem from an ongoing contest. + +## Note: This repo is not eligible for Hacktoberfest 2025 new contributions. +