From 6848fff65e51dc4545a8be05c27cad77ed6f8b51 Mon Sep 17 00:00:00 2001 From: Annex5061 <113541822+Annex5061@users.noreply.github.com> Date: Wed, 14 Sep 2022 22:00:31 +0530 Subject: [PATCH 001/278] new --- heapsort.java | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 heapsort.java diff --git a/heapsort.java b/heapsort.java new file mode 100644 index 0000000..3d31a22 --- /dev/null +++ b/heapsort.java @@ -0,0 +1,74 @@ +package Sorting; + +public class heapify { + + public void sort(int a[]) + { + int n=a.length; + for(int i=(n/2)-1;i>=0;i--) + { + hepify(a,n,i); + } + for(int i=n-1;i>=0;i--) { + + int temp=a[0]; + a[0]=a[i]; + a[i]=temp; + + hepify(a,i,0); + } + } + + + + + + static void hepify(int a[],int n,int i) + { + int larest; + + int left=(2*i)+1; + int right=(2*i)+2; + + if(lefta[i]) + { + larest=left; + } + else{ + larest=i; + } + if(righta[larest]) + { + larest=right; + } + if(larest!=i) + { + int temp; + temp=a[i]; + a[i]=a[larest]; + a[larest]=temp; + + hepify(a,n,larest); + } + } + + static void display(int a[]) + { + for(int i=0;i Date: Tue, 27 Sep 2022 19:05:09 +0700 Subject: [PATCH 002/278] Triangle --- triangle.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 triangle.py diff --git a/triangle.py b/triangle.py new file mode 100644 index 0000000..5ba10fd --- /dev/null +++ b/triangle.py @@ -0,0 +1,6 @@ +rows = int(input("Enter number of rows: ")) + +for i in range(rows): + for j in range(i+1): + print(j+1, end=" ") + print("\n") \ No newline at end of file From 01c7f730c0f87d23d9dc54e9181b1787eb539854 Mon Sep 17 00:00:00 2001 From: VISHNU GOVIND <109946029+VISHNUGOVIND007@users.noreply.github.com> Date: Tue, 27 Sep 2022 19:59:42 +0530 Subject: [PATCH 003/278] Bike helmet tilt This code is developed to find accident detection in two-wheelers by finding the angle of tilt in the helmet. --- Bike helmet tilt.dev | 51 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Bike helmet tilt.dev diff --git a/Bike helmet tilt.dev b/Bike helmet tilt.dev new file mode 100644 index 0000000..c6a18be --- /dev/null +++ b/Bike helmet tilt.dev @@ -0,0 +1,51 @@ +[Project] +filename=Bike helmet tilt.dev +name=Project1 +Type=1 +Ver=2 +ObjFiles= +Includes= +Libs= +PrivateResource= +ResourceIncludes= +MakeIncludes= +Compiler= +CppCompiler= +Linker= +IsCpp=1 +Icon= +ExeOutput= +ObjectOutput= +LogOutput= +LogOutputEnabled=0 +OverrideOutput=0 +OverrideOutputName= +HostApplication= +UseCustomMakefile=0 +CustomMakefile= +CommandLine= +Folders= +IncludeVersionInfo=0 +SupportXPThemes=0 +CompilerSet=0 +CompilerSettings=0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;8;0;0;0 + +[VersionInfo] +Major=1 +Minor=0 +Release=0 +Build=0 +LanguageID=1033 +CharsetID=1252 +CompanyName= +FileVersion= +FileDescription=Developed using the Dev-C++ IDE +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion= +AutoIncBuildNr=0 +SyncProduct=1 + From 2c6f01ef07882697e0d53c2f86f02db9e6cdfe58 Mon Sep 17 00:00:00 2001 From: VISHNU GOVIND <109946029+VISHNUGOVIND007@users.noreply.github.com> Date: Tue, 27 Sep 2022 20:16:38 +0530 Subject: [PATCH 004/278] Add files via upload --- Binary search.dev | 51 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Binary search.dev diff --git a/Binary search.dev b/Binary search.dev new file mode 100644 index 0000000..c0142f8 --- /dev/null +++ b/Binary search.dev @@ -0,0 +1,51 @@ +[Project] +filename=Binary search.dev +name=Project1 +Type=1 +Ver=2 +ObjFiles= +Includes= +Libs= +PrivateResource= +ResourceIncludes= +MakeIncludes= +Compiler= +CppCompiler= +Linker= +IsCpp=1 +Icon= +ExeOutput= +ObjectOutput= +LogOutput= +LogOutputEnabled=0 +OverrideOutput=0 +OverrideOutputName= +HostApplication= +UseCustomMakefile=0 +CustomMakefile= +CommandLine= +Folders= +IncludeVersionInfo=0 +SupportXPThemes=0 +CompilerSet=0 +CompilerSettings=0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;8;0;0;0 + +[VersionInfo] +Major=1 +Minor=0 +Release=0 +Build=0 +LanguageID=1033 +CharsetID=1252 +CompanyName= +FileVersion= +FileDescription=Developed using the Dev-C++ IDE +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion= +AutoIncBuildNr=0 +SyncProduct=1 + From 58e9fb19e839e7a6854a279d008113fe14fe4982 Mon Sep 17 00:00:00 2001 From: VISHNU GOVIND <109946029+VISHNUGOVIND007@users.noreply.github.com> Date: Tue, 27 Sep 2022 20:17:46 +0530 Subject: [PATCH 005/278] Delete Binary search.dev --- Binary search.dev | 51 ----------------------------------------------- 1 file changed, 51 deletions(-) delete mode 100644 Binary search.dev diff --git a/Binary search.dev b/Binary search.dev deleted file mode 100644 index c0142f8..0000000 --- a/Binary search.dev +++ /dev/null @@ -1,51 +0,0 @@ -[Project] -filename=Binary search.dev -name=Project1 -Type=1 -Ver=2 -ObjFiles= -Includes= -Libs= -PrivateResource= -ResourceIncludes= -MakeIncludes= -Compiler= -CppCompiler= -Linker= -IsCpp=1 -Icon= -ExeOutput= -ObjectOutput= -LogOutput= -LogOutputEnabled=0 -OverrideOutput=0 -OverrideOutputName= -HostApplication= -UseCustomMakefile=0 -CustomMakefile= -CommandLine= -Folders= -IncludeVersionInfo=0 -SupportXPThemes=0 -CompilerSet=0 -CompilerSettings=0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;8;0;0;0 - -[VersionInfo] -Major=1 -Minor=0 -Release=0 -Build=0 -LanguageID=1033 -CharsetID=1252 -CompanyName= -FileVersion= -FileDescription=Developed using the Dev-C++ IDE -InternalName= -LegalCopyright= -LegalTrademarks= -OriginalFilename= -ProductName= -ProductVersion= -AutoIncBuildNr=0 -SyncProduct=1 - From c22f7b08cae8f301d628e78600b3536e150e0cfb Mon Sep 17 00:00:00 2001 From: VISHNU GOVIND <109946029+VISHNUGOVIND007@users.noreply.github.com> Date: Tue, 27 Sep 2022 20:18:01 +0530 Subject: [PATCH 006/278] Delete Bike helmet tilt.dev --- Bike helmet tilt.dev | 51 -------------------------------------------- 1 file changed, 51 deletions(-) delete mode 100644 Bike helmet tilt.dev diff --git a/Bike helmet tilt.dev b/Bike helmet tilt.dev deleted file mode 100644 index c6a18be..0000000 --- a/Bike helmet tilt.dev +++ /dev/null @@ -1,51 +0,0 @@ -[Project] -filename=Bike helmet tilt.dev -name=Project1 -Type=1 -Ver=2 -ObjFiles= -Includes= -Libs= -PrivateResource= -ResourceIncludes= -MakeIncludes= -Compiler= -CppCompiler= -Linker= -IsCpp=1 -Icon= -ExeOutput= -ObjectOutput= -LogOutput= -LogOutputEnabled=0 -OverrideOutput=0 -OverrideOutputName= -HostApplication= -UseCustomMakefile=0 -CustomMakefile= -CommandLine= -Folders= -IncludeVersionInfo=0 -SupportXPThemes=0 -CompilerSet=0 -CompilerSettings=0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;8;0;0;0 - -[VersionInfo] -Major=1 -Minor=0 -Release=0 -Build=0 -LanguageID=1033 -CharsetID=1252 -CompanyName= -FileVersion= -FileDescription=Developed using the Dev-C++ IDE -InternalName= -LegalCopyright= -LegalTrademarks= -OriginalFilename= -ProductName= -ProductVersion= -AutoIncBuildNr=0 -SyncProduct=1 - From 61b08d436872682211fc43fbba54c9fcde4513e8 Mon Sep 17 00:00:00 2001 From: VISHNU GOVIND <109946029+VISHNUGOVIND007@users.noreply.github.com> Date: Tue, 27 Sep 2022 20:21:02 +0530 Subject: [PATCH 007/278] Create Binary search --- Binary search | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Binary search diff --git a/Binary search b/Binary search new file mode 100644 index 0000000..086e1d7 --- /dev/null +++ b/Binary search @@ -0,0 +1,42 @@ +#include +using namespace std; +int binarySearch(int array[], int size, int value) +{ + int first = 0, + last = size - 1, + middle, + position = -1; + bool found = false; + while (!found && first <= last) + { + middle = (first + last) / 2; + if (array[middle] == value) + { + found = true; + position = middle; + } + else if (array[middle] > value) + last = middle - 1; + else + first = middle + 1; + } + return position; +} +int main () +{ + const int size = 5; + int array[size] = {1, 2, 3, 4, 5}; + int value; + int result; + + cout << "What value would you like to search for? "; + cin >> value; + result = binarySearch(array, size, value); + + if (result == -1) + cout << "Not found\n"; + else + cout << "Your value is in the array.\n"; + + return 0; +} From 9352947d740382b3735b50db9931cc2bcbae1652 Mon Sep 17 00:00:00 2001 From: VISHNU GOVIND <109946029+VISHNUGOVIND007@users.noreply.github.com> Date: Tue, 27 Sep 2022 20:32:42 +0530 Subject: [PATCH 008/278] Bike helmet tilt This code is developed to find accident detection in two-wheelers using helmet tilt. --- Bike helmet tilt.dev | 51 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Bike helmet tilt.dev diff --git a/Bike helmet tilt.dev b/Bike helmet tilt.dev new file mode 100644 index 0000000..c6a18be --- /dev/null +++ b/Bike helmet tilt.dev @@ -0,0 +1,51 @@ +[Project] +filename=Bike helmet tilt.dev +name=Project1 +Type=1 +Ver=2 +ObjFiles= +Includes= +Libs= +PrivateResource= +ResourceIncludes= +MakeIncludes= +Compiler= +CppCompiler= +Linker= +IsCpp=1 +Icon= +ExeOutput= +ObjectOutput= +LogOutput= +LogOutputEnabled=0 +OverrideOutput=0 +OverrideOutputName= +HostApplication= +UseCustomMakefile=0 +CustomMakefile= +CommandLine= +Folders= +IncludeVersionInfo=0 +SupportXPThemes=0 +CompilerSet=0 +CompilerSettings=0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;8;0;0;0 + +[VersionInfo] +Major=1 +Minor=0 +Release=0 +Build=0 +LanguageID=1033 +CharsetID=1252 +CompanyName= +FileVersion= +FileDescription=Developed using the Dev-C++ IDE +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion= +AutoIncBuildNr=0 +SyncProduct=1 + From 62012012840324ec8bad6f618e3110cd31ee46b4 Mon Sep 17 00:00:00 2001 From: vxnshhh <107761698+vxnshhh@users.noreply.github.com> Date: Wed, 28 Sep 2022 01:51:56 +0530 Subject: [PATCH 009/278] 1.cpp --- 1.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 1.cpp diff --git a/1.cpp b/1.cpp new file mode 100644 index 0000000..652d402 --- /dev/null +++ b/1.cpp @@ -0,0 +1,16 @@ +#include +using namespace std; + +int main() +{ + string str; + cout << "enter string"<> str; + string str_rev; + for (int i = str.size() - 1; i >= 0; i--) + { + str_rev.push_back(str[i]); + } + cout< Date: Wed, 28 Sep 2022 12:42:38 +0530 Subject: [PATCH 010/278] Merge Sort --- merge.java | 106 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 merge.java diff --git a/merge.java b/merge.java new file mode 100644 index 0000000..0741042 --- /dev/null +++ b/merge.java @@ -0,0 +1,106 @@ +// C++ program for Merge Sort +#include +using namespace std; + +// Merges two subarrays of array[]. +// First subarray is arr[begin..mid] +// Second subarray is arr[mid+1..end] +void merge(int array[], int const left, int const mid, + int const right) +{ + auto const subArrayOne = mid - left + 1; + auto const subArrayTwo = right - mid; + + // Create temp arrays + auto *leftArray = new int[subArrayOne], + *rightArray = new int[subArrayTwo]; + + // Copy data to temp arrays leftArray[] and rightArray[] + for (auto i = 0; i < subArrayOne; i++) + leftArray[i] = array[left + i]; + for (auto j = 0; j < subArrayTwo; j++) + rightArray[j] = array[mid + 1 + j]; + + auto indexOfSubArrayOne + = 0, // Initial index of first sub-array + indexOfSubArrayTwo + = 0; // Initial index of second sub-array + int indexOfMergedArray + = left; // Initial index of merged array + + // Merge the temp arrays back into array[left..right] + while (indexOfSubArrayOne < subArrayOne + && indexOfSubArrayTwo < subArrayTwo) { + if (leftArray[indexOfSubArrayOne] + <= rightArray[indexOfSubArrayTwo]) { + array[indexOfMergedArray] + = leftArray[indexOfSubArrayOne]; + indexOfSubArrayOne++; + } + else { + array[indexOfMergedArray] + = rightArray[indexOfSubArrayTwo]; + indexOfSubArrayTwo++; + } + indexOfMergedArray++; + } + // Copy the remaining elements of + // left[], if there are any + while (indexOfSubArrayOne < subArrayOne) { + array[indexOfMergedArray] + = leftArray[indexOfSubArrayOne]; + indexOfSubArrayOne++; + indexOfMergedArray++; + } + // Copy the remaining elements of + // right[], if there are any + while (indexOfSubArrayTwo < subArrayTwo) { + array[indexOfMergedArray] + = rightArray[indexOfSubArrayTwo]; + indexOfSubArrayTwo++; + indexOfMergedArray++; + } + delete[] leftArray; + delete[] rightArray; +} + +// begin is for left index and end is +// right index of the sub-array +// of arr to be sorted */ +void mergeSort(int array[], int const begin, int const end) +{ + if (begin >= end) + return; // Returns recursively + + auto mid = begin + (end - begin) / 2; + mergeSort(array, begin, mid); + mergeSort(array, mid + 1, end); + merge(array, begin, mid, end); +} + +// UTILITY FUNCTIONS +// Function to print an array +void printArray(int A[], int size) +{ + for (auto i = 0; i < size; i++) + cout << A[i] << " "; +} + +// Driver code +int main() +{ + int arr[] = { 12, 11, 13, 5, 6, 7 }; + auto arr_size = sizeof(arr) / sizeof(arr[0]); + + cout << "Given array is \n"; + printArray(arr, arr_size); + + mergeSort(arr, 0, arr_size - 1); + + cout << "\nSorted array is \n"; + printArray(arr, arr_size); + return 0; +} + +// This code is contributed by Mayank Tyagi +// This code was revised by Joshua Estes From fdbba03a976cdac7f6334b8aeedef40a107c4233 Mon Sep 17 00:00:00 2001 From: shrikant kosariya <44123823+shrikant2233@users.noreply.github.com> Date: Wed, 28 Sep 2022 12:43:05 +0530 Subject: [PATCH 011/278] Merge Sort From 3053f4d7bf2ff646d5745dac3a6c20a8bce45485 Mon Sep 17 00:00:00 2001 From: megha-vishwakarma <70430389+megha-vishwakarma@users.noreply.github.com> Date: Wed, 28 Sep 2022 19:44:56 +0530 Subject: [PATCH 012/278] Bucketsort --- bucketsort.java | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 bucketsort.java diff --git a/bucketsort.java b/bucketsort.java new file mode 100644 index 0000000..44a0d91 --- /dev/null +++ b/bucketsort.java @@ -0,0 +1,39 @@ +import java.util.*; +public class Main +{ +public static int[] bucketsort(int[] array, int maximum_value) +{ +//creating an empty array called newbucket which is considered as bucket array +int[] newbucket = new int[maximum_value + 1]; +//creating another empty array called sorted_array to store the result array +int[] sorted_array = new int[array.length]; +//traversing through the input array to add each element to the bucket array +for (int a= 0; a maximum_value) +maximum_value = array[d]; +return maximum_value; +} +//main function is called within which we display the resulting array +public static void main(String args[]) +{ +int[] array ={100, 90, 80, 70, 60, 50, 40, 30, 20, 10}; +int maximum_value = maximumValue(array); +System.out.print("\nThe elements of the array to be sorted are:\n "); +System.out.println(Arrays.toString(array)); +System.out.print("\nThe elements of the sorted array sorted using bucket sort algorithm are:\n "); +System.out.println(Arrays.toString(bucketsort(array,maximum_value))); +} +} From 104b42263b7f8210d64f099946a6b1cc5e53e9f3 Mon Sep 17 00:00:00 2001 From: megha-vishwakarma <70430389+megha-vishwakarma@users.noreply.github.com> Date: Wed, 28 Sep 2022 21:56:56 +0530 Subject: [PATCH 013/278] Bucket Sort --- bucketsort.java | 78 ++++++++++++++++++++++++------------------------- 1 file changed, 39 insertions(+), 39 deletions(-) diff --git a/bucketsort.java b/bucketsort.java index 44a0d91..ecd7e3a 100644 --- a/bucketsort.java +++ b/bucketsort.java @@ -1,39 +1,39 @@ -import java.util.*; -public class Main -{ -public static int[] bucketsort(int[] array, int maximum_value) -{ -//creating an empty array called newbucket which is considered as bucket array -int[] newbucket = new int[maximum_value + 1]; -//creating another empty array called sorted_array to store the result array -int[] sorted_array = new int[array.length]; -//traversing through the input array to add each element to the bucket array -for (int a= 0; a maximum_value) -maximum_value = array[d]; -return maximum_value; -} -//main function is called within which we display the resulting array -public static void main(String args[]) -{ -int[] array ={100, 90, 80, 70, 60, 50, 40, 30, 20, 10}; -int maximum_value = maximumValue(array); -System.out.print("\nThe elements of the array to be sorted are:\n "); -System.out.println(Arrays.toString(array)); -System.out.print("\nThe elements of the sorted array sorted using bucket sort algorithm are:\n "); -System.out.println(Arrays.toString(bucketsort(array,maximum_value))); -} -} +import java.util.*; +public class Main +{ +public static int[] bucketsort(int[] array, int maximum_value) +{ +//creating an empty array called newbucket which is considered as bucket array +int[] newbucket = new int[maximum_value + 1]; +//creating another empty array called sorted_array to store the result array +int[] sorted_array = new int[array.length]; +//traversing through the input array to add each element to the bucket array +for (int a= 0; a maximum_value) +maximum_value = array[d]; +return maximum_value; +} +//main function is called within which we display the resulting array +public static void main(String args[]) +{ +int[] array ={100, 90, 80, 70, 60, 50, 40, 30, 20, 10}; +int maximum_value = maximumValue(array); +System.out.print("\nThe elements of the array to be sorted are:\n "); +System.out.println(Arrays.toString(array)); +System.out.print("\nThe elements of the sorted array sorted using bucket sort algorithm are:\n "); +System.out.println(Arrays.toString(bucketsort(array,maximum_value))); +} +} \ No newline at end of file From f1deb398979550ee2674be08ec83208da11a1d86 Mon Sep 17 00:00:00 2001 From: 790hanu <86285710+790hanu@users.noreply.github.com> Date: Thu, 29 Sep 2022 01:08:42 +0530 Subject: [PATCH 014/278] Add files via upload --- algorithms.java | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 algorithms.java diff --git a/algorithms.java b/algorithms.java new file mode 100644 index 0000000..f98d595 --- /dev/null +++ b/algorithms.java @@ -0,0 +1,35 @@ +// Java program for implementation of Bubble Sort +class BubbleSort { + void bubbleSort(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n - 1; i++) + for (int j = 0; j < n - i - 1; j++) + if (arr[j] > arr[j + 1]) { + // swap arr[j+1] and arr[j] + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + + /* Prints the array */ + void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + System.out.println(); + } + + // Driver method to test above + public static void main(String args[]) + { + BubbleSort ob = new BubbleSort(); + int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; + ob.bubbleSort(arr); + System.out.println("Sorted array"); + ob.printArray(arr); + } +} +/* This code is contributed by Rajat Mishra */ From 8510b680db3d7867f2a83509bd6f375092594704 Mon Sep 17 00:00:00 2001 From: "M.Rizky Kurniawan" <90012569+mrizky-kur@users.noreply.github.com> Date: Fri, 30 Sep 2022 20:06:29 +0700 Subject: [PATCH 015/278] bubble sort --- BubbleSort.java | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 BubbleSort.java diff --git a/BubbleSort.java b/BubbleSort.java new file mode 100644 index 0000000..ae1ceaa --- /dev/null +++ b/BubbleSort.java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} \ No newline at end of file From a9a4698c1def7e806f8e220e52733f5337b10061 Mon Sep 17 00:00:00 2001 From: yolandu19 <114292876+yolandu19@users.noreply.github.com> Date: Fri, 30 Sep 2022 20:24:52 +0700 Subject: [PATCH 016/278] bubble_sort --- bubble_sort.java | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 bubble_sort.java diff --git a/bubble_sort.java b/bubble_sort.java new file mode 100644 index 0000000..ae1ceaa --- /dev/null +++ b/bubble_sort.java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} \ No newline at end of file From 4a907d9a6121ec8550f99659754598d66868e72c Mon Sep 17 00:00:00 2001 From: Walter Ferreira <69780634+FerreiraWalter@users.noreply.github.com> Date: Fri, 30 Sep 2022 11:52:40 -0300 Subject: [PATCH 017/278] feat: create new file --- LinearSearch.java | 66 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 LinearSearch.java diff --git a/LinearSearch.java b/LinearSearch.java new file mode 100644 index 0000000..a6aa4b7 --- /dev/null +++ b/LinearSearch.java @@ -0,0 +1,66 @@ +import javax.swing.*; + +public class BuscaLinear { + + public static void linearSearchNumber(int[] listaNum, int numDigitado) { + int i = 0; + + while(true) { + if (numDigitado == listaNum[i]) { + JOptionPane.showMessageDialog(null, "O número " + numDigitado + " está na posição: " + i); + break; + } else if(numDigitado != listaNum[i]) { + i++; + } + } + } + + + public static void linearSearchString(String[] listaString, String strDigitada) { + int i = 0; + + while(!listaString[i].equals(strDigitada)) { + i++; + } + + if(listaString[i].equals(strDigitada)) { + JOptionPane.showMessageDialog(null, "A palavra '"+ strDigitada + "' está na posição: " + i); + } + } + + + public static void main(String[] args) { + int opc; + + int[] listaNum = new int[5]; + String[] listaString = new String[5]; + Object[] options = {"Número", "String"}; + + opc = JOptionPane.showOptionDialog(null, "Escolha o tipo de lista que deseja criar:", "Busca Linear", + JOptionPane.DEFAULT_OPTION, JOptionPane.DEFAULT_OPTION, null, options, options[0]); + + switch (opc){ + case 0: + + for(int i = 0; i < listaNum.length; i++) { + listaNum[i] = Integer.parseInt(JOptionPane.showInputDialog("Digite o " + (i+1) +"/5 número: ")); + } + int numDigitado = Integer.parseInt(JOptionPane.showInputDialog("Qual número deseja Buscar: ")); + + linearSearchNumber(listaNum, numDigitado); + + break; + + case 1: + + for(int i = 0; i < listaString.length; i++) { + listaString[i] = JOptionPane.showInputDialog("Digite a " + (i+1) +"/5 palavra: "); + } + String strDigitada = JOptionPane.showInputDialog("Qual palavra deseja Buscar: "); + + linearSearchString(listaString, strDigitada); + + break; + } + } +} From a29740c304466e9d3e5958adfa5b87d1cfcf2304 Mon Sep 17 00:00:00 2001 From: Walter Ferreira <69780634+FerreiraWalter@users.noreply.github.com> Date: Fri, 30 Sep 2022 12:03:06 -0300 Subject: [PATCH 018/278] Create tree.cpp --- tree.cpp | 264 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 264 insertions(+) create mode 100644 tree.cpp diff --git a/tree.cpp b/tree.cpp new file mode 100644 index 0000000..610f2f9 --- /dev/null +++ b/tree.cpp @@ -0,0 +1,264 @@ +#include +using namespace std; + +class Node { +private: + int data; + Node *left; + Node * right; + +public: + Node(int data) { + this->data = data; + left = NULL; + right = NULL; + } + + int getData() { + return data; + } + + Node *getLeft() { + return left; + } + + Node *setLeft(Node *node) { + return left = node; + } + + Node *getRight() { + return right; + } + + Node *setRight(Node *node) { + return right = node; + } +}; + +class Tree { +private: + Node *root; +public: + Tree() { + root = NULL; + } + + Node *getRoot() { + return root; + } + + void insert(int data) { + if (root == NULL) { + root = new Node(data); + } else { + auxInsert(root, data); + } + } + + void auxInsert(Node *node, int data) { + if (data < node->getData()) { + if (node->getLeft() == NULL) { + Node *new_node = new Node(data); + node->setLeft(new_node); + } else { + auxInsert(node->getLeft(), data); + } + } else { + if (node->getRight() == NULL) { + Node *new_node = new Node(data); + node->setRight(new_node); + } else { + auxInsert(node->getRight(), data); + } + } + } + + void pre_order(Node *node) { + cout << node->getData() << " "; + if (node->getLeft() != NULL) { + pre_order(node->getLeft()); + } + if (node->getRight() != NULL) { + pre_order(node->getRight()); + } + } + + Node *findNode(Node *node, int element) { + if (node == nullptr) return nullptr; + if (node->getData() == element) return node; + + Node *nodeFound = findNode(node->getLeft(), element); + if (nodeFound != nullptr) return nodeFound; + + return findNode(node->getRight(), element); + } + + void getLeaf(Node *node) { + if (node->getLeft() == NULL && node->getRight() == NULL) { + cout << node->getData() << endl; + } else { + if (node->getLeft() != NULL) { + getLeaf(node->getLeft()); + } + if (node->getRight() != NULL) { + getLeaf(node->getRight()); + } + } + } + + void getGrade(Node *node, int element) { + Node *nodeFound = findNode(node, element); + + if (nodeFound == 0) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + if (nodeFound->getLeft() == NULL && nodeFound->getRight() == NULL ) { + cout << "Grade is 0"; + } else if (nodeFound->getLeft() != NULL && nodeFound->getRight() != NULL) { + cout << "Grade is 2"; + } else { + cout << "Grade is 1"; + } + } + } + + void getAllGrade(Node *node) { + if (node->getRight() == NULL && node->getLeft() == NULL) { + cout << node->getData() << ": 0" << endl; + } else if (node->getRight() != NULL && node->getLeft() != NULL) { + cout << node->getData() << ": 2" << endl; + if (node->getLeft() != NULL) { + getAllGrade(node->getLeft()); + } + if (node->getRight() != NULL) { + getAllGrade(node->getRight()); + } + } else { + cout << node->getData() << ": 1" << endl; + if(node->getRight() != NULL) { + getAllGrade(node->getRight()); + } else { + getAllGrade(node->getLeft()); + } + } + } + + int getNodeHeight(Node *node) { + int leftHeigt = -1; + int rightHeigt = -1; + + if(root != NULL) { + if (node->getLeft() != NULL) { + leftHeigt = getNodeHeight(node->getLeft()); + } + if (node->getRight() != NULL) { + rightHeigt = getNodeHeight(node->getRight()); + } + + return max(leftHeigt, rightHeigt) + 1; + } + return 0; + } + + int getHeight(Node *node, int element) { + Node *nodeFound = findNode(node, element); + + if (nodeFound == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + return getNodeHeight(nodeFound); + } + return 0; + } + + void getAllHeights(Node *node) { + if (node == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + cout << node->getData() << ": " << getNodeHeight(node) << endl; + if (node->getLeft() != NULL) { + getAllHeights(node->getLeft()); + } + if (node->getRight() != NULL) { + getAllHeights(node->getRight()); + } + + } + } + + void getAncestors(Node *node, int ancestors) { + if (node == NULL) { + cout << ""; + } else { + cout << node->getData() << ": " << ancestors << endl; + + if (node->getLeft() != NULL || node->getRight() != NULL) { + getAncestors(node->getLeft(), ancestors + 1); + getAncestors(node->getRight(), ancestors + 1); + } + } + } + + void getAllDepths(Node *node) { + if (node == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + getAncestors(node, 0); + } + } + + void getSubtree(Node *node) { + if (node == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + pre_order(node); + } + } + + void getAllSubtrees(Node *node) { + if (node == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + pre_order(node); + cout << endl; + if (node->getLeft()) { + getAllSubtrees(node->getLeft()); + } + if (node->getRight()) { + getAllSubtrees(node->getRight()); + } + } + } +}; + +int main() { + Tree t = Tree(); + + t.insert(10); + t.insert(8); + t.insert(9); + t.insert(12); + t.insert(11); + t.insert(14); + t.insert(20); + t.insert(13); + t.insert(7); + + cout << "a) "; + t.pre_order(t.getRoot()); + cout << endl << "b) "; + t.getLeaf(t.getRoot()); + cout << endl << "c) "; + //t.getGrade(t.getRoot(), 10); + t.getAllGrade(t.getRoot()); + cout << endl << "d) "; + t.getAllHeights(t.getRoot()); + cout << endl << "e,f) "; + //cout << t.getDepth(t.getRoot()); + t.getAllDepths(t.getRoot()); + cout << endl << "g) "; + //t.getSubtree(t.getRoot(), 14); + t.getAllSubtrees(t.getRoot()); + + return 0; +} From 45df29a501628069fe0777c3c62f11ae574a3815 Mon Sep 17 00:00:00 2001 From: Vaghela Ajitkumar <91899491+ajitkumar1264@users.noreply.github.com> Date: Fri, 30 Sep 2022 23:31:10 +0530 Subject: [PATCH 019/278] CONTRIBUTING file --- CONTRIBUTING.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..d6613c8 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,2 @@ +this repository is only for algorithms in which you can upload any language's algorithms which will useful for many other people. +happy coading 👨‍💻. From 57a88681616d3efc611b62b5d6f03e60735ea196 Mon Sep 17 00:00:00 2001 From: ShalabhDevliyal <76624340+ShalabhDevliyal@users.noreply.github.com> Date: Fri, 30 Sep 2022 23:59:11 +0530 Subject: [PATCH 020/278] SortingusingSort.java --- SortingusingSort.java | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 SortingusingSort.java diff --git a/SortingusingSort.java b/SortingusingSort.java new file mode 100644 index 0000000..f5248c7 --- /dev/null +++ b/SortingusingSort.java @@ -0,0 +1,21 @@ +import java.util.ArrayList; +import java.util.Collections; + +class Main { + public static void main(String[] args) { + + + ArrayList numbers = new ArrayList<>(); + + + numbers.add(4); + numbers.add(2); + numbers.add(3); + System.out.println("Unsorted ArrayList: " + numbers); + + + Collections.sort(numbers); + System.out.println("Sorted ArrayList: " + numbers); + + } +} From 53afe2337c9d61cc94440797ff659df70851871e Mon Sep 17 00:00:00 2001 From: Ankit <79972184+Ankit-gurjar@users.noreply.github.com> Date: Sat, 1 Oct 2022 00:48:35 +0530 Subject: [PATCH 021/278] Multiply_two_matrices --- multiply_two_matrix.cpp | 160 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 multiply_two_matrix.cpp diff --git a/multiply_two_matrix.cpp b/multiply_two_matrix.cpp new file mode 100644 index 0000000..d7381c1 --- /dev/null +++ b/multiply_two_matrix.cpp @@ -0,0 +1,160 @@ +#include +using namespace std; + +#define ROW_1 4 +#define COL_1 4 + +#define ROW_2 4 +#define COL_2 4 + +void print(string display, vector> matrix, + int start_row, int start_column, int end_row, + int end_column) +{ + cout << endl + << display << " =>" << endl; + for (int i = start_row; i <= end_row; i++) + { + for (int j = start_column; j <= end_column; j++) + { + cout << setw(10); + cout << matrix[i][j]; + } + cout << endl; + } + cout << endl; + return; +} + +void add_matrix(vector> matrix_A, + vector> matrix_B, + vector> &matrix_C, + int split_index) +{ + for (auto i = 0; i < split_index; i++) + for (auto j = 0; j < split_index; j++) + matrix_C[i][j] = matrix_A[i][j] + matrix_B[i][j]; +} + +vector> +multiply_matrix(vector> matrix_A, + vector> matrix_B) +{ + int col_1 = matrix_A[0].size(); + int row_1 = matrix_A.size(); + int col_2 = matrix_B[0].size(); + int row_2 = matrix_B.size(); + + if (col_1 != row_2) + { + cout << "\nError: The number of columns in Matrix " + "A must be equal to the number of rows in " + "Matrix B\n"; + return {}; + } + + vector result_matrix_row(col_2, 0); + vector> result_matrix(row_1, + result_matrix_row); + + if (col_1 == 1) + result_matrix[0][0] = matrix_A[0][0] * matrix_B[0][0]; + else + { + int split_index = col_1 / 2; + + vector row_vector(split_index, 0); + vector> result_matrix_00(split_index, + row_vector); + vector> result_matrix_01(split_index, + row_vector); + vector> result_matrix_10(split_index, + row_vector); + vector> result_matrix_11(split_index, + row_vector); + + vector> a00(split_index, row_vector); + vector> a01(split_index, row_vector); + vector> a10(split_index, row_vector); + vector> a11(split_index, row_vector); + vector> b00(split_index, row_vector); + vector> b01(split_index, row_vector); + vector> b10(split_index, row_vector); + vector> b11(split_index, row_vector); + + for (auto i = 0; i < split_index; i++) + for (auto j = 0; j < split_index; j++) + { + a00[i][j] = matrix_A[i][j]; + a01[i][j] = matrix_A[i][j + split_index]; + a10[i][j] = matrix_A[split_index + i][j]; + a11[i][j] = matrix_A[i + split_index] + [j + split_index]; + b00[i][j] = matrix_B[i][j]; + b01[i][j] = matrix_B[i][j + split_index]; + b10[i][j] = matrix_B[split_index + i][j]; + b11[i][j] = matrix_B[i + split_index] + [j + split_index]; + } + + add_matrix(multiply_matrix(a00, b00), + multiply_matrix(a01, b10), + result_matrix_00, split_index); + add_matrix(multiply_matrix(a00, b01), + multiply_matrix(a01, b11), + result_matrix_01, split_index); + add_matrix(multiply_matrix(a10, b00), + multiply_matrix(a11, b10), + result_matrix_10, split_index); + add_matrix(multiply_matrix(a10, b01), + multiply_matrix(a11, b11), + result_matrix_11, split_index); + + for (auto i = 0; i < split_index; i++) + for (auto j = 0; j < split_index; j++) + { + result_matrix[i][j] = result_matrix_00[i][j]; + result_matrix[i][j + split_index] = result_matrix_01[i][j]; + result_matrix[split_index + i][j] = result_matrix_10[i][j]; + result_matrix[i + split_index] + [j + split_index] = result_matrix_11[i][j]; + } + + result_matrix_00.clear(); + result_matrix_01.clear(); + result_matrix_10.clear(); + result_matrix_11.clear(); + a00.clear(); + a01.clear(); + a10.clear(); + a11.clear(); + b00.clear(); + b01.clear(); + b10.clear(); + b11.clear(); + } + return result_matrix; +} + +int main() +{ + vector> matrix_A = {{1, 1, 1, 1}, + {2, 2, 2, 2}, + {3, 3, 3, 3}, + {2, 2, 2, 2}}; + + print("Array A", matrix_A, 0, 0, ROW_1 - 1, COL_1 - 1); + + vector> matrix_B = {{1, 1, 1, 1}, + {2, 2, 2, 2}, + {3, 3, 3, 3}, + {2, 2, 2, 2}}; + + print("Array B", matrix_B, 0, 0, ROW_2 - 1, COL_2 - 1); + + vector> result_matrix( + multiply_matrix(matrix_A, matrix_B)); + + print("Result Array", result_matrix, 0, 0, ROW_1 - 1, + COL_2 - 1); +} From 53c978893005aca767d974c2f221833c997b307c Mon Sep 17 00:00:00 2001 From: JatinBisht2308 Date: Sat, 1 Oct 2022 00:56:18 +0530 Subject: [PATCH 022/278] :fire: created the radix sort implementation in java --- RadixSort.java | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 RadixSort.java diff --git a/RadixSort.java b/RadixSort.java new file mode 100644 index 0000000..baa82a0 --- /dev/null +++ b/RadixSort.java @@ -0,0 +1,66 @@ +class RadixSort { + + int getMax(int a[], int n) { + int max = a[0]; + for(int i = 1; i max) + max = a[i]; + } + return max; //maximum element from the array + } + + void countingSort(int a[], int n, int place) // function to implement counting + + sort + { + int[] output = new int[n+1]; + int[] count = new int[10]; + + // Calculate count of elements + for (int i = 0; i < n; i++) + count[(a[i] / place) % 10]++; + + // Calculate cumulative frequency + for (int i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Place the elements in sorted order + for (int i = n - 1; i >= 0; i--) { + output[count[(a[i] / place) % 10] - 1] = a[i]; + count[(a[i] / place) % 10]--; + } + + for (int i = 0; i < n; i++) + a[i] = output[i]; + } + + // function to implement radix sort + void radixsort(int a[], int n) { + + // get maximum element from array + int max = getMax(a, n); + + // Apply counting sort to sort elements based on place value + for (int place = 1; max / place > 0; place *= 10) + countingSort(a, n, place); + } + + // function to print array elements + void printArray(int a[], int n) { + for (int i = 0; i < n; ++i) + System.out.print(a[i] + " "); + } + + public static void main(String args[]) { + int a[] = {151, 259, 360, 91, 115, 706, 34, 858, 2}; + int n = a.length; + RadixSort r1 = new RadixSort(); + System.out.print("Before sorting array elements are - \n"); + r1.printArray(a,n); + r1.radixsort(a, n); + System.out.print("\n\nAfter applying Radix sort, the array elements are - + + \n"); + r1.printArray(a, n); + } + } \ No newline at end of file From 50ae1ce3c438fba1733cb30a30c42b2d8bb6323e Mon Sep 17 00:00:00 2001 From: Mayank Arora Date: Sat, 1 Oct 2022 01:16:19 +0530 Subject: [PATCH 023/278] Create complex-string.java --- complex-string.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 complex-string.java diff --git a/complex-string.java b/complex-string.java new file mode 100644 index 0000000..690c8b0 --- /dev/null +++ b/complex-string.java @@ -0,0 +1,19 @@ +public class StringComparison { + public static void main(String a[]){ + String str = "JavaTpoint is a great website to acquire knowledge"; + StringBuffer obj = + new StringBuffer("JavaTpoint is a great website to acquire knowledge"); + if(str.contentEquals(obj)){ + System.out.println("The content of the string is equal"); + } else { + System.out.println("The content of the string is not equal"); + } + StringBuffer obj1 = + new StringBuffer("It is another string"); + if(str.contentEquals(obj1)){ + System.out.println("The content of the string is equal"); + } else { + System.out.println("The content of the string is not equal"); + } + } +} From 863fb89a683e72d28707dd82c091dac6cdf5f530 Mon Sep 17 00:00:00 2001 From: Tilak Sovan Khatua <62074842+tilak-codes@users.noreply.github.com> Date: Sat, 1 Oct 2022 01:18:58 +0530 Subject: [PATCH 024/278] Subarray --- Subarray sum equal to k.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Subarray sum equal to k.cpp diff --git a/Subarray sum equal to k.cpp b/Subarray sum equal to k.cpp new file mode 100644 index 0000000..6c7a9ea --- /dev/null +++ b/Subarray sum equal to k.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int subarraySum(vector& nums, int k) { + unordered_map mp; + int sum=0; + int ans =0 ; + for(int i=0;i Date: Sat, 1 Oct 2022 01:34:18 +0530 Subject: [PATCH 025/278] Added mergeSort --- Main.class | Bin 0 -> 1167 bytes mergeSort.class | Bin 0 -> 1128 bytes mergeSort.java | 68 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 Main.class create mode 100644 mergeSort.class create mode 100644 mergeSort.java diff --git a/Main.class b/Main.class new file mode 100644 index 0000000000000000000000000000000000000000..bbba9269ab0d67c6acefda66a28d274f3e882280 GIT binary patch literal 1167 zcmZuwOKTHh6g^)u??hW$r)_GYwGW#|O{&!RRun*nRl3Cz87&$;iLFF#+u12BPc3l{nSbfxZHXxHYw=BztkrA4iI z%|%KhIXA^ea<>#(?!wI(_m)p#9vyoGOrKb2G+P3?Pxj;1+)7=bCpkBL!(DQ7RkyyF zE3}%G`r=WETZKlux!|3v$Xr|hgvd&A6cI$D*bY024s^1}83xla8buN*SqGDO<$+Vp zrn`JZM>>iO#&qnBB8!|r=SD_n{)V@}!a{RXo9u<<+byrgAvD@V?V!d=BX^Mnwpga; z){Y8v`++u_+2k!rsg6{p9Or`#H!~nNuaiySy90AxW zwFIT0RMRgZo>Sq#_||-5m>Oq9om6obD&2t3iFjElox6M-4Suw?vU*7^qTSZUIAe2x_8{k)h;k*^kM*{Cdwq=vKPX@`7Ze<^# zD`Q9eZ$BP7&JYSHm2#N2A{e(dv6;b>8=)>y`mV#?s zib_i|o>;|5JW*1sc_q!!D{Ba)Gq$3X623+YmGDN-{amulu3|seI>DF+_@_RIQ5^Q` z3PX&-L=RgGPNhMryokw8F1r{uoT8#SMOAZ(n(h>J#VHz{nlt?dO7SJsnXybb^G+!< q`3q=W`Wg(%%qy7GHV!SQ;y5#(#2%btJ(DYmFv*7B2w)|#iHVn`t5Y2|8lM?m#7J*O3`R2AqB|9lJv6wGE<%pIoVynP+AW^RunWErE8= z(b;RVTXU7lq-7-k&&p3=!zqTK_d&QVd{cFh9Xl$LkB);ShfiO=ANjKz`5HsG<{WElXJk4C0Cr=khnL2(&;wgHtjX0js*K_pY1+8CV2(K}Ww;Zi^9HWm&;Q(oT zuCdEFd{#dpyg zix=ebR63T}Lm-`y3UOD)5){D((;jvfxWrCgA;$@{;u>?m&hfbEWfO$x=bUtqoIf8+ zj1Zv7WJKB5^FhtbOR|}l6*I4>W?q%dycSW+xzXV0fmCF~50KjAPf#dF_n`9B7^+T& Y1q<1WyBNVVGPuXEGmO;9`vAIr0|PV5jsO4v literal 0 HcmV?d00001 diff --git a/mergeSort.java b/mergeSort.java new file mode 100644 index 0000000..e41958d --- /dev/null +++ b/mergeSort.java @@ -0,0 +1,68 @@ +import java.util.Arrays; + +class mergeSort { + + static void merge(int array[], int p, int q, int r) { + + int n1 = q - p + 1; + int n2 = r - q; + + int L[] = new int[n1]; + int M[] = new int[n2]; + + for (int i = 0; i < n1; i++) + L[i] = array[p + i]; + for (int j = 0; j < n2; j++) + M[j] = array[q + 1 + j]; + + int i, j, k; + i = 0; + j = 0; + k = p; + + while (i < n1 && j < n2) { + if (L[i] <= M[j]) { + array[k] = L[i]; + i++; + } else { + array[k] = M[j]; + j++; + } + k++; + } + + while (i < n1) { + array[k] = L[i]; + i++; + k++; + } + + while (j < n2) { + array[k] = M[j]; + j++; + k++; + } + } + + static void mergeSort(int array[], int left, int right) { + if (left < right) { + + int mid = (left + right) / 2; + + mergeSort(array, left, mid); + mergeSort(array, mid + 1, right); + + merge(array, left, mid, right); + } + } + + public static void main(String args[]) { + + int[] array = { 5, 2, 3, 4, 1, 6 }; + + mergeSort(array, 0, array.length - 1); + + System.out.println("Sorted Array:"); + System.out.println(Arrays.toString(array)); + } +} From 310ad87e5029ef5d8f93c77efba17f541740640c Mon Sep 17 00:00:00 2001 From: bhumika-ag <93240372+bhumika-ag@users.noreply.github.com> Date: Sat, 1 Oct 2022 01:51:53 +0530 Subject: [PATCH 026/278] StudentDBMS.cpp --- Student DBMS.cpp | 4144 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 4144 insertions(+) create mode 100644 Student DBMS.cpp diff --git a/Student DBMS.cpp b/Student DBMS.cpp new file mode 100644 index 0000000..495fd12 --- /dev/null +++ b/Student DBMS.cpp @@ -0,0 +1,4144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + My-caption-Cpp/Student DBMS.cpp at main · Ankit-gurjar/My-caption-Cpp + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Skip to content + + + + + + + + + + + + + + +
+ +
+ + + + + + + +
+ + + + + +
+ + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + +
+ +
+ + + + Ankit-gurjar  /   + My-caption-Cpp  /   + +
+
+ + + +
+ + +
+
+ Clear Command Palette +
+
+ + + +
+
+ Tip: + Type # to search pull requests +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type # to search issues +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type # to search discussions +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type ! to search projects +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type @ to search teams +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type @ to search people and organizations +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type > to activate command mode +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Go to your accessibility settings to change your keyboard shortcuts +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type author:@me to search your content +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:pr to filter to pull requests +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:issue to filter to issues +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:project to filter to projects +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:open to filter to open content +
+
+ Type ? for help and tips +
+
+
+ +
+ +
+
+ We’ve encountered an error and some results aren't available at this time. Type a new search or try again later. +
+
+ + No results matched your search + + + + + + + + + + +
+ + + + + Search for issues and pull requests + + # + + + + Search for issues, pull requests, discussions, and projects + + # + + + + Search for organizations, repositories, and users + + @ + + + + Search for projects + + ! + + + + Search for files + + / + + + + Activate command mode + + > + + + + Search your issues, pull requests, and discussions + + # author:@me + + + + Search your issues, pull requests, and discussions + + # author:@me + + + + Filter to pull requests + + # is:pr + + + + Filter to issues + + # is:issue + + + + Filter to discussions + + # is:discussion + + + + Filter to projects + + # is:project + + + + Filter to open issues, pull requests, and discussions + + # is:open + + + + + + + + + + + + + + + + +
+
+
+ +
+ + + + + + + + + + +
+ + +
+
+
+ + + + + + + + + +
+ +
+ +
+ +
+ + + + / + + My-caption-Cpp + + + Public +
+ + +
+ +
    + +
  • +
    +
    +
    +
  • + + +
  • + +
    + + + + + Unwatch + + + + + 1 + + + +
    +
    +

    Notifications

    + +
    + +
    +
    + + + + + + + + +
    + + +
    + + + + + Get push notifications on iOS or Android. + +
    +
    +
    +
    + + + + +
    +
    +
    + + + +
  • + +
  • +
    + +
    + + + +
    + +
    +
    + + + + + + + +
    + +
    +
    +
    +
    +
  • + +
  • + + +
    +
    + + +
    +
    + +
    + + + +
    + +
    +
    + + + + + + + +
    + +
    +
    +
    +
    +
    +
  • + + + +
+ +
+ +
+
+ + + + +
+ + + + + +
+ Open in github.dev + Open in a new github.dev tab + + + + + + +
+ + +
+ + + + + + + + +Permalink + +
+ +
+
+ + + main + + + + +
+
+
+ Switch branches/tags + +
+ + + +
+ +
+ +
+ + +
+ +
+ + + + + + + + + + + + + + + +
+ + +
+
+
+
+ +
+ +
+ + + Go to file + +
+ + + + +
+
+
+ + + + + + + + + +
+ +
+
+ + + + +
+ + Latest commit + ff210a6 + Oct 24, 2021 + + + + + + History + + +
+
+ +
+ +
+
+ + + 1 + + contributor + + +
+ +

+ Users who have contributed to this file +

+
+ + + + + + +
+
+
+
+ + + + + + + + + + + + + +
+ +
+ + +
+ + 286 lines (245 sloc) + + 6.34 KB +
+ +
+ + + + +
+ +
+
+
+
+ +
+ +
+
+
+ + + +
+ + + + + + + + + +
+ + +
+ +
+
+ +
+ +
+
+ + + +
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
// Include all the necessary libraries.
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <string.h>
+
using namespace std;
+
int main()
{
// Considering the max length of data entered (name) to
// be 15.
char data[15];
int n = 0, option = 0, count_n = 0;
// This is the initial mark alloted to a subject.
string empty = "00";
string proctor = "";
// Name of the file in which DB is stored.
ifstream f("Example.txt");
string line;
+
// The following for loop counts the total number of
// lines in the file.
for (int i = 0; std::getline(f, line); ++i) {
count_n++;
}
+
while (option != 6) {
// This prints out all the available options in the
// DB
cout << "\nAvailable operations: \n1. Add New "
"Students\n2."
<< "Student Login\n3. Faculty Login\n4. "
"Proctor Login\n5. Admin View\n"
<< "6. Exit\nEnter option: ";
cin >> option;
+
if (option == 1) {
cout << "Enter the number of students: ";
cin >> n;
+
count_n = count_n + n;
+
for (int i = 0; i < n; i++) {
ofstream outfile;
outfile.open("Example.txt", ios::app);
// The entire data of a single student is
// stored line-by-line.
cout << "Enter your registration number: ";
cin >> data;
outfile << data << "\t";
+
cout << "Enter your name: ";
cin >> data;
int len = strlen(data);
+
while (len < 15) {
data[len] = ' ';
len = len + 1;
}
outfile << data << "\t";
// Inserting empty data initially into the
// file
outfile << empty << "\t";
outfile << empty << "\t";
+
cout << "Enter your proctor ID: ";
cin >> proctor;
+
outfile << proctor << endl;
}
}
+
else if (option == 2) {
char regno[9];
cout << "Enter your registration number: ";
cin >> regno;
ifstream infile;
int check = 0;
infile.open("Example.txt", ios::in);
+
// This loop prints out the data according to
// the registration number specified.
while (infile >> data) {
if (strcmp(data, regno) == 0) {
cout
<< "\nRegistration Number: " << data
<< endl;
infile >> data;
cout << "Name: " << data << endl;
+
infile >> data;
cout << "CSE1001 mark: " << data
<< endl;
+
infile >> data;
cout << "CSE1002 mark: " << data
<< endl;
+
infile >> data;
cout << "Proctor ID: " << data << endl;
+
infile.close();
check = 1;
}
}
+
if (check == 0) {
cout << "No such registration number found!"
<< endl;
}
}
+
// This loop is used to view and add marks to the
// database of a student.
else if (option == 3) {
char subcode[7];
cout << "Enter your subject code: ";
cin >> subcode;
string code1 = "CSE1001", code2 = "CSE1002",
mark = "";
ifstream infile;
int check = 0;
+
cout << "\nAvailable operations: \n1. Add data "
"about marks\n"
<< "2. View data\nEnter option: ";
cin >> option;
+
if (option == 1) {
cout
<< "Warning! You would need to add mark"
<< "details for all the students!"
<< endl;
for (int i = 0; i < count_n; i++) {
fstream file("Example.txt");
+
// The seek in file has been done
// according to the length
// of the data being inserted. It needs
// to adjusted accordingly for diffferent
// lengths of data.
+
if (strcmp(subcode, code1.c_str())
== 0) {
file.seekp(26 + 37 * i,
std::ios_base::beg);
cout << "Enter the mark of student#"
<< (i + 1) << " : ";
cin >> mark;
file.write(mark.c_str(), 2);
}
+
if (strcmp(subcode, code2.c_str())
== 0) {
file.seekp(29 + 37 * i,
std::ios_base::beg);
cout << "Enter the mark of student#"
<< (i + 1) << " : ";
cin >> mark;
file.write(mark.c_str(), 2);
}
}
}
+
// This loop is used to view marks of a student.
// The extra infile commands have been used to
// get a specific mark only since the data has
// been seperated by a tabspace.
+
else if (option == 2) {
infile.open("Example.txt", ios::in);
if (strcmp(subcode, code1.c_str()) == 0) {
cout << "Registration number - Marks\n"
<< endl;
while (infile >> data) {
cout << data;
infile >> data;
infile >> data;
cout << " - " << data << endl;
infile >> data;
infile >> data;
check = 1;
}
}
+
infile.close();
infile.open("Example.txt", ios::in);
+
if (strcmp(subcode, code2.c_str()) == 0) {
cout << "Registration number - Marks\n"
<< endl;
while (infile >> data) {
cout << data;
infile >> data;
infile >> data;
infile >> data;
cout << " - " << data << endl;
infile >> data;
check = 1;
}
}
}
+
infile.close();
+
if (check == 0) {
cout << "No such subject code found!"
<< endl;
}
}
+
// This loop displays all the details of students
// under the same proctor ID.
+
else if (option == 4) {
char procid[7];
cout << "Enter your proctor ID: ";
cin >> procid;
int check = 0;
char temp1[100], temp2[100], temp3[100];
char temp4[100], id[100];
ifstream infile;
infile.open("Example.txt", ios::in);
+
while (infile >> temp1) {
infile >> temp2;
infile >> temp3;
infile >> temp4;
infile >> id;
+
if (strcmp(id, procid) == 0) {
cout << "\nRegistration Number: "
<< temp1 << endl;
cout << "Name: " << temp2 << endl;
cout << "CSE1001 Mark: " << temp3
<< endl;
cout << "CSE1002 Mark: " << temp4
<< endl;
check = 1;
}
}
+
if (check == 0) {
cout << "No such proctor ID found!" << endl;
}
}
+
// This loop acts as an admin view to see all the
// data in the file.
+
else if (option == 5) {
char password[25];
cout << "Enter the admin password: ";
cin >> password;
+
// This variable value can be changed according
// to your requirement of the administrator
// password.
+
string admin_pass = "admin";
+
if (strcmp(password, admin_pass.c_str()) == 0) {
cout << "Reg No. "
"\tName\tCSE1001\tCSE1002\tProctor "
"ID"
<< endl;
ifstream infile;
infile.open("Example.txt", ios::in);
char data[20];
+
while (infile >> data) {
cout << data << "\t";
infile >> data;
cout << data << "\t";
infile >> data;
cout << data << "\t";
infile >> data;
cout << data << "\t";
infile >> data;
cout << data << endl;
}
}
}
}
}
+
+ + + +
+ +
+ + + + +
+ + +
+ + +
+
+ + +
+ +
+ + +
+ +
+ + +
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + From d92b9ca80596041883cf41f34a9154620e827dd8 Mon Sep 17 00:00:00 2001 From: Malhar Kulkarni <97526274+malhar619@users.noreply.github.com> Date: Sat, 1 Oct 2022 02:32:38 +0530 Subject: [PATCH 027/278] hacktoberfest event --- Knapsack.java | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Knapsack.java diff --git a/Knapsack.java b/Knapsack.java new file mode 100644 index 0000000..b347204 --- /dev/null +++ b/Knapsack.java @@ -0,0 +1,26 @@ +class Knapsack { + static int max(int a, int b) + { + return (a > b) ? a : b; + } + static int knapSack(int W, int wt[], int val[], int n) + { + if (n == 0 || W == 0) + return 0; + if (wt[n - 1] > W) + return knapSack(W, wt, val, n - 1); + else + return max(val[n - 1] + + knapSack(W - wt[n - 1], wt, + val, n - 1), + knapSack(W, wt, val, n - 1)); + } + public static void main(String args[]) + { + int val[] = new int[] { 60, 100, 120 }; + int wt[] = new int[] { 10, 20, 30 }; + int W = 50; + int n = val.length; + System.out.println(knapSack(W, wt, val, n)); + } +} \ No newline at end of file From 5bda76e53a15495a0a5cd3a888b220cd81271b46 Mon Sep 17 00:00:00 2001 From: Malhar Kulkarni <97526274+malhar619@users.noreply.github.com> Date: Sat, 1 Oct 2022 02:33:34 +0530 Subject: [PATCH 028/278] hacktoberfest event From d4db1f1d5437dbb8d37f5a31fab30c33ea4d18b8 Mon Sep 17 00:00:00 2001 From: Ved Prakash Bhaskar <56016547+iamvpbhaskar@users.noreply.github.com> Date: Sat, 1 Oct 2022 02:59:30 +0530 Subject: [PATCH 029/278] Added a functional Knapsack program Added a C++ program to solve fractional Knapsack Problem, please add and merge it to your repository and give hacktoberfest label that help in sucessfull PR. Thanks --- FractionalKnapsack.cpp | 87 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 FractionalKnapsack.cpp diff --git a/FractionalKnapsack.cpp b/FractionalKnapsack.cpp new file mode 100644 index 0000000..b010496 --- /dev/null +++ b/FractionalKnapsack.cpp @@ -0,0 +1,87 @@ +// C++ program to solve fractional Knapsack Problem +#include + +using namespace std; + +// Structure for an item which stores weight & corresponding value of Item +struct Item { + int value, weight; + + // Constructor + Item(int value, int weight) + : value(value), weight(weight) + { + } +}; + +// Comparison function to sort Item according to val/weight ratio +bool cmp(struct Item a, struct Item b) +{ + double r1 = (double)a.value / a.weight; + double r2 = (double)b.value / b.weight; + return r1 > r2; +} + +// Main greedy function to solve problem +double fractionalKnapsack(struct Item arr[], + int N, int size) +{ + // Sort Item on basis of ratio + sort(arr, arr + size, cmp); + + // Current weight in knapsack + int curWeight = 0; + + // Result (value in Knapsack) + double finalvalue = 0.0; + + // Looping through all Items + for (int i = 0; i < size; i++) { + + // If adding Item won't overflow, + // add it completely + if (curWeight + arr[i].weight <= N) { + curWeight += arr[i].weight; + finalvalue += arr[i].value; + } + + // If we can't add current Item, + // add fractional part of it + else { + int remain = N - curWeight; + finalvalue += arr[i].value + * ((double)remain + / arr[i].weight); + + break; + } + } + + // Returning final value + return finalvalue; +} + +// Driver Code +int main() +{ + // Weight of knapsack + int N = 60; + + // Given weights and values as a pairs + Item arr[] = { { 100, 10 }, + { 280, 40 }, + { 120, 20 }, + { 120, 24 } }; + + int size = sizeof(arr) / sizeof(arr[0]); + + // Function Call + cout << "Maximum profit earned = " + << fractionalKnapsack(arr, N, size); + return 0; +} + + +Output: +Maximum profit earned = 440 + From 07b36307587da4a395fa1f567160835ad6704967 Mon Sep 17 00:00:00 2001 From: Malhar Kulkarni <97526274+malhar619@users.noreply.github.com> Date: Sat, 1 Oct 2022 03:04:04 +0530 Subject: [PATCH 030/278] Update and rename Knapsack.java to poi_dyn_str.cpp --- Knapsack.java | 26 -------------------------- poi_dyn_str.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 26 deletions(-) delete mode 100644 Knapsack.java create mode 100644 poi_dyn_str.cpp diff --git a/Knapsack.java b/Knapsack.java deleted file mode 100644 index b347204..0000000 --- a/Knapsack.java +++ /dev/null @@ -1,26 +0,0 @@ -class Knapsack { - static int max(int a, int b) - { - return (a > b) ? a : b; - } - static int knapSack(int W, int wt[], int val[], int n) - { - if (n == 0 || W == 0) - return 0; - if (wt[n - 1] > W) - return knapSack(W, wt, val, n - 1); - else - return max(val[n - 1] - + knapSack(W - wt[n - 1], wt, - val, n - 1), - knapSack(W, wt, val, n - 1)); - } - public static void main(String args[]) - { - int val[] = new int[] { 60, 100, 120 }; - int wt[] = new int[] { 10, 20, 30 }; - int W = 50; - int n = val.length; - System.out.println(knapSack(W, wt, val, n)); - } -} \ No newline at end of file diff --git a/poi_dyn_str.cpp b/poi_dyn_str.cpp new file mode 100644 index 0000000..b98eff1 --- /dev/null +++ b/poi_dyn_str.cpp @@ -0,0 +1,47 @@ +//Dynamic memory allocation for strings +#include +#include +using namespace std; +int main() +{ + char name[20]; + char *p;//char pointer + int l,i; + + cout<<"\n enter string :"; + cin>> name; + l=strlen(name); + p = new char[l+1]; //dynamic memory allocation (Base address of memory) + + for(i=0;name[i]!='\0';i++) + { + p[i]=name[i]; + //*(p+i)= name[i]; + + }//end of for + + p[i]='\0';//end of string + + cout<<"\n Copied Sring :"< Date: Sat, 1 Oct 2022 08:27:51 +0700 Subject: [PATCH 031/278] add bubblesort algorithm with javascript --- bubbleSort.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 bubbleSort.js diff --git a/bubbleSort.js b/bubbleSort.js new file mode 100644 index 0000000..76c82ba --- /dev/null +++ b/bubbleSort.js @@ -0,0 +1,32 @@ +function bubbleSort(arr){ + + let i, j; + let len = arr.length; + + let isSwapped = false; + + for(i =0; i < len; i++){ + + isSwapped = false; + + for(j = 0; j < len; j++){ + if(arr[j] > arr[j + 1]){ + var temp = arr[j] + arr[j] = arr[j+1]; + arr[j+1] = temp; + isSwapped = true; + } + } + + if(!isSwapped){ + break; + } + } + + console.log(arr) +} + + +const arr = [243, 45, 23, 356, 3, 5346, 35, 5]; + +bubbleSort(arr) From cfc1e566e91e14f3c1bdf27bb4d65b3edf276d4f Mon Sep 17 00:00:00 2001 From: Samraj R <51151216+samraj-freak@users.noreply.github.com> Date: Sat, 1 Oct 2022 07:24:16 +0530 Subject: [PATCH 032/278] BinarySearch --- BinarySearch.java | 65 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 BinarySearch.java diff --git a/BinarySearch.java b/BinarySearch.java new file mode 100644 index 0000000..eeffdf1 --- /dev/null +++ b/BinarySearch.java @@ -0,0 +1,65 @@ +import java.util.Scanner; + +/* + * Java Program to implement binary search without using recursion + */ +public class BinarySearch { + + public static void main(String[] args) { + + Scanner commandReader = new Scanner(System.in); + System.out.println("Welcome to Java Program to perform + binary search on int array"); + System.out.println("Enter total number of elements : "); + int length = commandReader.nextInt(); + int[] input = new int[length]; + + System.out.printf("Enter %d integers %n", length); + for (int i = 0; i < length; i++) { + input[i] = commandReader.nextInt(); + } + + System.out.println("Please enter number to be searched in array + (sorted order)"); + int key = commandReader.nextInt(); + + int index = performBinarySearch(input, key); + + if (index == -1) { + System.out.printf("Sorry, %d is not found in array %n", key); + } else { + System.out.printf("%d is found in array at index %d %n", key, + index); + } + + commandReader.close(); + + } + + /** + * Java method to perform binary search. It accept an integer array and a + * number and return the index of number in the array. If number doesn't + * exists in array then it return -1 + * + * @param input + * @param number + * @return index of given number in array or -1 if not found + */ + public static int performBinarySearch(int[] input, int number) { + int low = 0; + int high = input.length - 1; + + while (high >= low) { + int middle = (low + high) / 2; + if (input[middle] == number) { + return middle; + } else if (input[middle] < number) { + low = middle + 1; + } else if (input[middle] > number) { + high = middle - 1; + } + } + return -1; + } + +} From 2e8b2b18e55e449dcf4762755fc8343dcc6e405d Mon Sep 17 00:00:00 2001 From: ev1lclow3n <87696230+ev1lclow3n@users.noreply.github.com> Date: Sat, 1 Oct 2022 08:32:58 +0530 Subject: [PATCH 033/278] bubblesort --- bubblesort.java | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 bubblesort.java diff --git a/bubblesort.java b/bubblesort.java new file mode 100644 index 0000000..436662e --- /dev/null +++ b/bubblesort.java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} From 71d1f9fb36de038a528b38b234bf5cd49c278492 Mon Sep 17 00:00:00 2001 From: Kaustubh Mishra <73981577+kaustubh589@users.noreply.github.com> Date: Sat, 1 Oct 2022 08:51:26 +0530 Subject: [PATCH 034/278] QuickSortAlgorithm --- QuickSortAlogorithem.java | 73 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 QuickSortAlogorithem.java diff --git a/QuickSortAlogorithem.java b/QuickSortAlogorithem.java new file mode 100644 index 0000000..b91430b --- /dev/null +++ b/QuickSortAlogorithem.java @@ -0,0 +1,73 @@ +import java.util.Arrays; + +class Quicksort { + + // method to find the partition position + static int partition(int array[], int low, int high) { + + // choose the rightmost element as pivot + int pivot = array[high]; + + // pointer for greater element + int i = (low - 1); + + // traverse through all elements + // compare each element with pivot + for (int j = low; j < high; j++) { + if (array[j] <= pivot) { + + // if element smaller than pivot is found + // swap it with the greater element pointed by i + i++; + + // swapping element at i with element at j + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + } + + // swapt the pivot element with the greater element specified by i + int temp = array[i + 1]; + array[i + 1] = array[high]; + array[high] = temp; + + // return the position from where partition is done + return (i + 1); + } + + static void quickSort(int array[], int low, int high) { + if (low < high) { + + // find pivot element such that + // elements smaller than pivot are on the left + // elements greater than pivot are on the right + int pi = partition(array, low, high); + + // recursive call on the left of pivot + quickSort(array, low, pi - 1); + + // recursive call on the right of pivot + quickSort(array, pi + 1, high); + } + } +} + +// Main class +class Main { + public static void main(String args[]) { + + int[] data = { 8, 7, 2, 1, 0, 9, 6 }; + System.out.println("Unsorted Array"); + System.out.println(Arrays.toString(data)); + + int size = data.length; + + // call quicksort() on array data + Quicksort.quickSort(data, 0, size - 1); + + System.out.println("Sorted Array in Ascending Order "); + System.out.println(Arrays.toString(data)); + } +} From 89498582a63b812e3805104b95370f0bd4e46c9a Mon Sep 17 00:00:00 2001 From: HARSH-VATS-6 <73696588+HARSH-VATS-6@users.noreply.github.com> Date: Sat, 1 Oct 2022 09:16:14 +0530 Subject: [PATCH 035/278] Create LONGEST-INCREASING-SUBSEQUENCE.cpp --- LONGEST-INCREASING-SUBSEQUENCE.cpp | 40 ++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 LONGEST-INCREASING-SUBSEQUENCE.cpp diff --git a/LONGEST-INCREASING-SUBSEQUENCE.cpp b/LONGEST-INCREASING-SUBSEQUENCE.cpp new file mode 100644 index 0000000..63965e1 --- /dev/null +++ b/LONGEST-INCREASING-SUBSEQUENCE.cpp @@ -0,0 +1,40 @@ +/* Dynamic Programming C/C++ implementation of LIS problem */ +#include +#include + +/* lis() returns the length of the longest increasing + subsequence in arr[] of size n */ +int lis(int arr[], int n) +{ + int *lis, i, j, max = 0; + lis = (int*)malloc(sizeof(int) * n); + + /* Initialize LIS values for all indexes */ + for (i = 0; i < n; i++) + lis[i] = 1; + + /* Compute optimized LIS values in bottom up manner */ + for (i = 1; i < n; i++) + for (j = 0; j < i; j++) + if (arr[i] > arr[j] && lis[i] < lis[j] + 1) + lis[i] = lis[j] + 1; + + /* Pick maximum of all LIS values */ + for (i = 0; i < n; i++) + if (max < lis[i]) + max = lis[i]; + + /* Free memory to avoid memory leak */ + free(lis); + + return max; +} + +/* Driver program to test above function */ +int main() +{ + int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; + int n = sizeof(arr) / sizeof(arr[0]); + printf("Length of lis is %d\n", lis(arr, n)); + return 0; +} From d30ac6ce0959e5e8a0e92975ce2487aa9b3aea53 Mon Sep 17 00:00:00 2001 From: fabian-prog <76981856+fabian-prog@users.noreply.github.com> Date: Sat, 1 Oct 2022 09:46:13 +0530 Subject: [PATCH 036/278] Count total number of occurances of a character algorithm --- ...ces of element in the sorted array in java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 count total number of occurances of element in the sorted array in java diff --git a/count total number of occurances of element in the sorted array in java b/count total number of occurances of element in the sorted array in java new file mode 100644 index 0000000..06c0ff0 --- /dev/null +++ b/count total number of occurances of element in the sorted array in java @@ -0,0 +1,30 @@ +public int count(int[] arr, int target) { + int left = binarySearch(arr, target, true); + if (left < 0) return 0; + int right = binarySearch(arr, target, false); + return right - left + 1; +} + +private int binarySearch(int[] arr, int target, boolean leftmost) { + int lo = 0; + int hi = arr.length - 1; + int idx = -1; + while (lo <= hi) { + int mid = (lo + hi) >>> 1; // avoid overflow. same as (lo + hi) / 2 + + if (target > arr[mid]) { + lo = mid + 1; + } else if (target < arr[mid]) { + hi = mid - 1; + } else { + idx = mid; + if (leftmost) { + hi = mid - 1; + } else { + lo = mid + 1; + } + } + } + return idx; +} + From fca92e99ffa7b48008dbc69b4453f9bcb2b183de Mon Sep 17 00:00:00 2001 From: fabian-prog <76981856+fabian-prog@users.noreply.github.com> Date: Sat, 1 Oct 2022 09:49:08 +0530 Subject: [PATCH 037/278] First and last occurance binary search --- First and last occurance binary search | 56 ++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 First and last occurance binary search diff --git a/First and last occurance binary search b/First and last occurance binary search new file mode 100644 index 0000000..57770ef --- /dev/null +++ b/First and last occurance binary search @@ -0,0 +1,56 @@ +#include +using namespace std; +int firstOcc(vector& arr, int n, int key) { + + int s = 0, e = n-1; + int mid = s + (e-s)/2; + int ans = -1; + while(s<=e) { + + if(arr[mid] == key){ + ans = mid; + e = mid - 1; + } + else if(key > arr[mid]) {//Right me jao + s = mid + 1; + } + else if(key < arr[mid]) {//left me jao + e = mid - 1; + } + + mid = s + (e-s)/2; + } + return ans; +} + +int lastOcc(vector& arr, int n, int key) { + + int s = 0, e = n-1; + int mid = s + (e-s)/2; + int ans = -1; + while(s<=e) { + + if(arr[mid] == key){ + ans = mid; + s = mid + 1; + } + else if(key > arr[mid]) {//Right me jao + s = mid + 1; + } + else if(key < arr[mid]) {//left me jao + e = mid - 1; + } + + mid = s + (e-s)/2; + } + return ans; +} + +pair firstAndLastPosition(vector& arr, int n, int k) +{ + pair p; + p.first = firstOcc(arr, n, k); + p.second = lastOcc(arr, n, k); + + return p; +} From bd28e52fdd8ba027d58764e142593b7c4508b910 Mon Sep 17 00:00:00 2001 From: Novan Aziz Ramadhan Date: Sat, 1 Oct 2022 11:41:21 +0700 Subject: [PATCH 038/278] Create matrix.java --- matrix.java | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 matrix.java diff --git a/matrix.java b/matrix.java new file mode 100644 index 0000000..052189d --- /dev/null +++ b/matrix.java @@ -0,0 +1,25 @@ +// Java program to print the elements of +// a 2 D array or matrix using toString() +import java.io.*; +import java.util.*; +class GFG { + + public static void print2D(int mat[][]) + { + // Loop through all rows + for (int[] row : mat) + + // converting each row as string + // and then printing in a separate line + System.out.println(Arrays.toString(row)); + } + + public static void main(String args[]) + throws IOException + { + int mat[][] = { { 1, 2, 3, 4 }, + { 5, 6, 7, 8 }, + { 9, 10, 11, 12 } }; + print2D(mat); + } +} From a72a204f6a68e9ec86ce77cb6224ebba056a009d Mon Sep 17 00:00:00 2001 From: Shannonmarie <69419374+Shanonbaker@users.noreply.github.com> Date: Sat, 1 Oct 2022 10:36:38 +0530 Subject: [PATCH 039/278] Create Sedgwik.cpp --- Sedgwik.cpp | 2506 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 2506 insertions(+) create mode 100644 Sedgwik.cpp diff --git a/Sedgwik.cpp b/Sedgwik.cpp new file mode 100644 index 0000000..548f08e --- /dev/null +++ b/Sedgwik.cpp @@ -0,0 +1,2506 @@ + +C++ Programs from Algorithms 2nd edition + +Copyright 1992. Addison-Wesley Publishing Company, Inc. +All Rights Reserved. + + +-------------------------------- +CHAPTER 1 Introduction + + +-------------------------------- +CHAPTER 2 C++ (and C) + +#include +int gcd(int u, int v) + { + int t; + while (u > 0) + { + if (u < v) { t = u; u = v; v = t; } + u = u - v; + } + return v; + } +main() + { + int x, y; + while (cin >> x && cin >> y) + if (x>0 && y>0) cout << x << ' ' << y << ' ' + << gcd(x,y) << '\n'; + } + +-------------------------------- +CHAPTER 3 Elementary Data Structures + +const int N = 1000; +main() + { + int i, j, a[N+1]; + for (a[1] = 0, i = 2; i <= N; i++) a[i] = 1; + for (i = 2; i <= N/2; i++) + for (j = 2; j <= N/i; j++) + a[i*j] = 0; + for (i = 1; i <= N; i++) + if (a[i]) cout << i << ' '; + cout << '\n'; + } + + struct node + { int key; struct node *next; }; + + struct node *head, *z; + head = new node; z = new node; + head->next = z; z->next = z; + +struct node + { int key; struct node *next; }; +main() + { + int i, N, M; + struct node *t, *x; + cin >> N >> M; + t = new node; t->key = 1; x = t; + for (i = 2; i <= N; i++) + { + t->next = new node; + t = t->next; t->key = i; + } + t->next = x; + while (t != t->next) + { + for (i = 1; i < M; i++) t = t->next; + cout << t->next->key << ' '; + x = t->next; t->next = x->next; + delete x; + } + cout << t->key << '\n'; + } + + key[x] = v; next[x] = next[t]; next[t] = x++; + +class Stack + { + private: + itemType *stack; + int p; + public: + Stack(int max=100) + { stack = new itemType[max]; p = 0; } + ~Stack() + { delete stack; } + inline void push(itemType v) + { stack[p++] = v; } + inline itemType pop() + { return stack[--p]; } + inline int empty() + { return !p; } + }; + + char c; Stack acc(50); int x; + while (cin.get(c)) + { + x = 0; + while (c == ' ') cin.get(c); + if (c == '+') x = acc.pop() + acc.pop(); + if (c == '*') x = acc.pop() * acc.pop(); + while (c>='0' && c<='9') + { x = 10*x + (c-'0'); cin.get(c); } + acc.push(x); + } + cout << acc.pop() << '\n'; + + char c; Stack save(50); + while (cin.get(c)) + { + if (c == ')') cout.put(save.pop()); + if (c == '+') save.push(c); + if (c == '*') save.push(c); + while (c>='0' && c<='9') + { cout.put(c); cin.get(c); } + if (c != '(') cout << ' '; + } + cout << '\n'; + +class Stack + { + public: + Stack(int max); + ~Stack(); + void push(itemType v); + itemType pop(); + int empty(); + private: + struct node + { itemType key; struct node *next; }; + struct node *head, *z; + }; + +Stack::Stack(int max) + { + head = new node; z = new node; + head->next = z; z->next = z; + } +Stack::~Stack() + { + struct node *t = head; + while (t != z) + { head = t; t = t->next; delete head; } + } + +void Stack::push(itemType v) + { + struct node *t = new node; + t->key = v; t->next = head->next; + head->next = t; + } +itemType Stack::pop() + { + itemType x; + struct node *t = head->next; + head->next = t->next; x = t->key; + delete t; return x; + } +int Stack::empty() + { return head->next == z; } + +void Queue::put(itemType v) + { + queue[tail++] = v; + if (tail > size) tail = 0; + } +itemType Queue::get() + { + itemType t = queue[head++]; + if (head > size) head = 0; + return t; + } +int Queue::empty() + { return head == tail; } + + +-------------------------------- +CHAPTER 4 Trees + + struct node + { char info; struct node *l, *r; }; + struct node *x, *z; + + char c; Stack stack(50); + z = new node; z->l = z; z->r = z; + while (cin.get(c)) + { + while (c == ' ') cin.get(c); + x = new node; + x->info = c; x->l = z; x->r = z; + if (c=='+' || c=='*') + { x->r = stack.pop(); x->l = stack.pop(); } + stack.push(x); + } + +traverse(struct node *t) + { + stack.push(t); + while (!stack.empty()) + { + t = stack.pop(); visit(t); + if (t->r != z) stack.push(t->r); + if (t->l != z) stack.push(t->l); + } + } + +traverse(struct node *t) + { + queue.put(t); + while (!queue.empty()) + { + t = queue.get(); visit(t); + if (t->l != z) queue.put(t->l); + if (t->r != z) queue.put(t->r); + } + } + + +-------------------------------- +CHAPTER 5 Recursion + +int factorial(int N) + { + if (N == 0) return 1; + return N * factorial(N-1); + } + +int fibonacci(int N) + { + if (N <= 1) return 1; + return fibonacci(N-1) + fibonacci(N-2); + } + +const int max = 25; +int fibonacci(int N) + { + int i, F[max]; + F[0] = 1; F[1] = 1; + for (i = 2; i <= max; i++) + F[i] = F[i-1] + F[i-2]; + return F[N]; + } + +rule(int l, int r, int h) + { + int m = (l+r)/2; + if (h > 0) + { + mark(m,h); + rule(l,m,h-1); + rule(m,r,h-1); + } + } + +rule(0,8,3) + mark(4,3 ) + rule(0,4,2) + mark(2,2) + rule(0,2,1) + mark(1,1) + rule(0,1,0) + rule(1,2,0) + rule(2,4,1) + mark(3,1) + rule(2,3,0) + rule(3,4,0) + rule(4,8,2) + mark(6,2) + rule(4,6,1) + mark(5,1) + rule(4,5,0) + rule(5,6,0) + rule(6,8,1) + mark(7,1) + rule(6,7,0) + +rule(0,8,3) + rule(0,4,2) + rule(0,2,1) + rule(0,1,0) + mark(1,1) + rule(1,2,0) + mark(2,2) + rule(2,4,1) + rule(2,3,0) + mark(3,1) + rule(3,4,0) + mark(4,3 ) + rule(4,8,2) + rule(4,6,1) + rule(4,5,0) + mark(5,1) + rule(5,6,0) + mark(6,2) + rule(6,8,1) + rule(6,7,0) + mark(7,1) + +rule(int l, int r, int h) + { + int i, j, t; + for (i = 1,j = 1; i <= h; i++,j+=j) + for (t = 0; t <= (l+r)/j; t++) + mark(l+j+t*(j+j),i); + } + +star(int x, int y, int r) + { + if (r > 0) + { + star(x-r,y+r,r/2); + star(x+r,y+r,r/2); + star(x-r,y-r,r/2); + star(x+r,y-r,r/2); + box(x,y,r); + } + } + +traverse(struct node *t) + { + if (t != z) + { + traverse(t->l); + visit(t); + traverse(t->r); + } + } + +visit(struct node *t) + { t->x = ++x; t->y = y; } +traverse(struct node *t) + { + y++; + if (t != z) + { + traverse(t->l); + visit(t); + traverse(t->r) + } + y--; + } + +traverse(struct node *t) + { + if (t != z) + { + visit(t); + traverse(t->l); + traverse(t->r); + } + } + +traverse(struct node *t) + { + l: if (t == z) goto x; + visit(t); + traverse(t->l); + t = t->r; + goto l; + x: ; + } + +traverse(struct node *t) + { + l: if (t == z) goto s; + visit(t); + stack.push(t); t = t->l; goto l; + r: t = t->r; goto l; + s: if (stack.empty()) goto x; + t = stack.pop(); goto r; + x: ; + } + +traverse(struct node *t) + { + l: while (t != z) + { + visit(t); + stack.push(t->r); t = t->l; + } + if (stack.empty()) goto x; + t = stack.pop(); goto l; + x: ; + } + +traverse(struct node *t) + { + stack.push(t); + while (!stack.empty()) + { + t = stack.pop(); + while (t != z) + { + visit(t); + stack.push(t->r); + t = t->l; + } + } + } + +traverse(struct node *t) + { + stack.push(t); + while (!stack.empty()) + { + t = stack.pop(); + if (t != z) + { + visit(t); + stack.push(t->r); + stack.push(t->l); + } + } + } + +traverse(struct node *t) + { + stack.push(t); + while (!stack.empty()) + { + t = stack.pop(); visit(t); + if (t->r != z) stack.push(t->r); + if (t->l != z) stack.push(t->l); + } + } + + +-------------------------------- +CHAPTER 6 Analysis of Algorithms + + +-------------------------------- +CHAPTER 7 Implementation of Algorithms + + +-------------------------------- +CHAPTER 8 Elementary Sorting Methods + +inline void swap(itemType a[], int i, int j) + { itemType t = a[i]; a[i] = a[j]; a[j] = t; } +sort3(itemType a[], int N) + { + if (a[1] > a[2]) swap(a, 1, 2); + if (a[1] > a[3]) swap(a, 1, 3); + if (a[2] > a[3]) swap(a, 2, 3); + } +const int maxN = 100; +main() + { + int N, i; itemType v, a[maxN+1]; + N = 0; while (cin >> v) a[++N] = v; + a[0] = 0; + sort3(a, N); + for (i = 1; i <= N; i++) cout << a[i] << ' '; + cout << '\n'; + } + +void selection(itemType a[], int N) + { + int i, j, min; + for (i = 1; i < N; i++) + { + min = i; + for (j = i+1; j <= N; j++) + if (a[j] < a[min]) min = j; + swap(a, min, i); + } + } + +void insertion(itemType a[], int N) + { + int i, j; itemType v; + for (i = 2; i <= N; i++) + { + v = a[i]; j = i; + while (a[j-1] > v) + { a[j] = a[j-1]; j--; } + a[j] = v; + } + } + +void bubble(itemType a[], int N) + { + int i, j; + for (i = N; i >= 1; i--) + for (j = 2; j <= i; j++) + if (a[j-1] > a[j]) swap(a, j-1, j); + } + +void insertion(itemType a[], int p[], int N) + { + int i, j; itemType v; + for (i = 0; i <= N; i++) p[i] = i; + for (i = 2; i <= N; i++) + { + v = p[i]; j = i; + while (a[p[j-1]] > a[v]) + { p[j] = p[j-1]; j--; } + p[j] = v; + } + } + +void insitu(itemType a[], int p[], int N) + { + int i, j, k; itemType t; + for (i = 1; i <= N; i++) + if (p[i] != i) + { + t = a[i]; k = i; + do + { + j = k; a[j] = a[p[j]]; + k = p[j]; p[j] = j; + } + while (k != i); + a[j] = t; + } + } + +void insertion(itemType a[], itemType *p[], int N) + { + int i, j; itemType *v; + for (i = 0; i <= N; i++) p[i] = &a[i]; + for (i = 2; i <= N; i++) + { + v = p[i]; j = i; + while (*p[j-1] > *v) + { p[j] = p[j-1]; j--; } + p[j] = v; + } + } + +void shellsort(itemType a[], int N) + { + int i, j, h; itemType v; + for (h = 1; h <= N/9; h = 3*h+1) ; + for ( ; h > 0; h /= 3) + for (i = h+1; i <= N; i += 1) + { + v = a[i]; j = i; + while (j>h && a[j-h]>v) + { a[j] = a[j-h]; j -= h; } + a[j] = v; + } + } + +for (j = 0; j < M; j++) count[j] = 0; +for (i = 1; i <= N; i++) count[a[i]]++; +for (j = 1; j < M; j++) count[j] += count[j-1]; +for (i = N; i >= 1; i--) b[count[a[i]]--] = a[i]; +for (i = 1; i <= N; i++) a[i] = b[i]; + + +-------------------------------- +CHAPTER 9 Quicksort + +void quicksort(itemType a[], int l, int r) + { + int i; + if (r > l) + { + i = partition(a, l, r); + quicksort(a, l, i-1); + quicksort(a, i+1, r); + } + } + +void quicksort(itemType a[], int l, int r) + { + int i, j; itemType v; + if (r > l) + { + v = a[r]; i = l-1; j = r; + for (;;) + { + while (a[++i] < v) ; + while (a[--j] > v) ; + if (i >= j) break; + swap(a, i, j); + } + swap(a, i, r); + quicksort(a, l, i-1); + quicksort(a, i+1, r); + } + } + +void quicksort(itemType a[], int l, int r) + { + int i; Stack sf(50); + for (;;) + { + while (r > l) + { + i = partition(a, l, r); + if (i-l > r-i) + { sf.push(l); sf.push(i-1); l = i+1; } + else + { sf.push(i+1); sf.push(r); r = i-1; } + } + if (sf.empty()) break; + r = sf.pop(); l = sf.pop(); + } + } + +void select(itemType a[], int l, int r, int k) + { + int i; + if (r > l) + { + i = partition(a, l, r); + if (i > l+k-1) select(a, l, i-1, k); + if (i < l+k-1) select(a, i+1, r, k-i); + } + } + +void select(itemType a[], int N, int k) + { + int i, j, l, r; itemType v; + l = 1; r = N; + while (r > l) + { + v = a[r]; i = l-1; j = r; + for (;;) + { + while (a[++i] < v) ; + while (a[--j] > v) ; + if (i >= j) break; + swap(a, i, j); + } + swap(a, i, r); + if (i >= k) r = i-1; + if (i <= k) l = i+1; + } + } + + +-------------------------------- +CHAPTER 10 Radix Sorting + +class bitskey + { + private: + int x; + public: + bitskey& operator=(int i) + { x = i; return *this; } + inline unsigned bits(int k, int j) + { return (x >> k) & ~(~0 << j); } + }; +typedef bitskey itemType; + +void radixexchange(itemType a[], int l, int r, int b) + { + int i, j; itemType t; + if (r>l && b>=0) + { + i = l; j = r; + while (j != i) + { + while (!a[i].bits(b, 1) && ii) j--; + swap(a, i, j); + } + if (!a[r].bits(b, 1)) j++; + radixexchange(a, l, j-1, b-1); + radixexchange(a, j, r, b-1); + } + } + +void straightradix(itemType a[], itemType b[], int N) + { + int i, j, pass, count[M-1]; + for (pass = 0; pass < w/m; pass++) + { + for (j = 0; j < M; j++) count[j] = 0; + for (i = 1; i <= N; i++) + count[a[i].bits(pass*m, m)]++; + for (j = 1; j < M; j++) + count[j] += count[j-1]; + for (i = N; i >= 1; i--) + b[count[a[i].bits(pass*m, m)]--] = a[i]; + for (i = 1; i <= N; i++) a[i] = b[i]; + } + } + + +-------------------------------- +CHAPTER 11 Priority Queues + +class PQ + { + private: + itemType *a; + int N; + public: + PQ(int max) + { a = new itemType[max]; N = 0; } + ~PQ() + { delete a; } + void insert(itemType v) + { a[++N] = v; } + itemType remove() + { + int j, max = 1; + for (j = 2; j <= N; j++) + if (a[j] > a[max]) max = j; + swap(a, max, N); + return a[N--]; + } + }; + +void PQ::upheap(int k) + { + itemType v; + v = a[k]; a[0] = itemMAX; + while (a[k/2] <= v) + { a[k] = a[k/2]; k = k/2; } + a[k] = v; + } +void PQ::insert(itemType v) + { a[++N] = v; upheap(N); } + +void PQ::downheap(int k) + { + int j; itemType v; + v = a[k]; + while (k <= N/2) + { + j = k+k; + if (j= a[j]) break; + a[k] = a[j]; k = j; + } + a[k] = v; + } + +itemType PQ::remove() + { + itemType v = a[1]; + a[1] = a[N--]; + downheap(1); + return v; + } + +itemType PQ::replace(itemType v) + { + a[0] = v; + downheap(0); + return a[0]; + } + +void heapsort(itemType a[], int N) + { + int i; PQ heap(N); + for (i = 1; i <= N; i++) heap.insert(a[i]); + for (i = N; i >= 1; i--) a[i] = heap.remove(); + } + +void heapsort(itemType a[], int N) + { + int k; + for (k = N/2; k >= 1; k--) + downheap(a, N, k); + while (N > 1) + { swap(a, 1, N); downheap(a, --N, 1); } + } + +class PQ + { + private: + itemType *a; int *p, *info; + int N; + public: + PQ(int size) + { a = new itemType[size]; + p = new int[size]; + info = new int[size]; N = 0; } + ~PQ() + { delete a; delete p; delete info; } + void insert(int x, itemType v) + { a[++N] = v; p[x] = N; info[N] = x; } + void change(int x, itemType v) + { a[p[x]] = v; } + int remove() // remove smallest + { + int j, min = 1; + for (j = 2; j <= N; j++) + if (a[j] < a[min]) min = j; + swap(a, min, N); swap(info, min, N); + p[info[min]] = min; + return info[N--]; + } + int empty() + { return (N <= 0); } + }; + +PQ::PQ(itemType *array, int size) + { + int k; + p = new itemType[size]; q = new itemType[size]; + a = array; N = size; + for (k = 1; k <= N; k++) { p[k] = k; q[k] = k; } + for (k = N/2; k >= 1; k--) downheap(k); + } + +void PQ::downheap(int k) + { + int j, v; + v = p[k]; + while (k <= N/2) + { + j = k+k; + if (j=a[p[j]]) break; + p[k] = p[j]; q[p[j]] = k; k = j; + } + p[k] = v; q[v] = k; + } + + +-------------------------------- +CHAPTER 12 Mergesort + +i = 1; j = 1; +a[M+1] = itemMAX; b[N+1] = itemMAX; +for (k = 1; k <= M+N; k++) + c[k] = (a[i]key <= b->key) + { c->next = a; c = a; a = a->next; } + else + { c->next = b; c = b; b = b->next; } + while (c != z); + c = z->next; z->next = z; + return c; + } + +void mergesort(itemType a[], int l, int r) + { + int i, j, k, m; + if (r > l) + { + m = (r+l)/2; + mergesort(a, l, m); + mergesort(a, m+1, r); + for (i = m+1; i > l; i--) b[i-1] = a[i-1]; + for (j = m; j < r; j++) b[r+m-j] = a[j+1]; + for (k = l; k <= r; k++) + a[k] = (b[i]next != z) + { + a = c; b = c->next->next->next; + while (b != z) + { c = c->next; b = b->next->next; } + b = c->next; c->next = z; + return merge(mergesort(a), mergesort(b)); + } + return c; + } + +struct node *mergesort(struct node *c) + { + int i, N; + struct node *a, *b, *head, *todo, *t; + head = new node; + head->next = c; a = z; + for (N = 1; a != head->next; N = N+N) + { + todo = head->next; c = head; + while (todo != z) + { + t = todo; a = t; + for (i = 1; i < N; i++) t = t->next; + b = t->next; t->next = z; t = b; + for (i = 1; i < N; i++) t = t->next; + todo = t->next; t->next = z; + c->next = merge(a, b); + for (i = 1; i <= N+N; i++) c = c->next; + } + } + return head->next; + } + + +-------------------------------- +CHAPTER 13 External Sorting + + +-------------------------------- +CHAPTER 14 Elementary Searching Methods + +class Dict + { + private: + struct node + { itemType key; infoType info; }; + struct node *a; + int N; + public: + Dict(int max) + { a = new node[max]; N = 0; } + ~Dict() + { delete a; } + infoType search(itemType v); + void insert(itemType v, infoType info); + }; +infoType Dict::search(itemType v) // Sequential + { + int x = N+1; + a[0].key = v; a[0].info = infoNIL; + while (v != a[--x].key) ; + return a[x].info; + } +void Dict::insert(itemType v, infoType info) + { a[++N].key = v; a[N].info = info; } + +class Dict + { + private: + struct node + { itemType key; infoType info; + struct node *next; + node(itemType k, infoType i, struct node *n) + { key = k; info = i; next = n; }; + }; + struct node *head, *z; + public: + Dict(int max) + { + z = new node(itemMAX, infoNIL, 0); + head = new node(0, 0, z); + } + ~Dict(); + infoType search(itemType v); + void insert(itemType v, infoType info); + }; + +infoType Dict::search(itemType v) // Sorted list + { + struct node *t = head; + while (v > t->key) t = t->next; + return (v = t->key) ? t->info : z->info; + } + +void Dict::insert(itemType v, infoType info) + { + struct node *x, *t = head; + while (v > t->next->key) t = t->next; + x = new node(v, info, t->next); + t->next = x; + } + +infoType Dict::search(itemType v) // Binary search + { + int l = 1; int r = N; int x; + while (r >= l) + { + x = (l+r)/2; + if (v == a[x].key) return a[x].info; + if (v < a[x].key) r = x-1; else l = x+1; + } + return infoNIL; + } + +class Dict + { + private: + struct node + { itemType key; infoType info; + struct node *l, *r; + node(itemType k, infoType i, + struct node *ll, struct node *rr) + { key = k; info = i; l = ll; r = rr; }; + }; + struct node *head, *z; + public: + Dict(int max) + { z = new node( 0, infoNIL, 0, 0); + head = new node(itemMIN, 0, 0, z); } + ~Dict(); + infoType search(itemType v); + void insert(itemType v, infoType info); + }; + +infoType Dict::search(itemType v) + { + struct node *x = head->r; + z->key = v; + while (v != x->key) + x = (v < x->key) ? x->l : x->r; + return x->info; + } + +void Dict::insert(itemType v, infoType info) + { + struct node *p, *x; + p = head; x = head->r; + while (x != z) + { p = x; x = (v < x->key) ? x->l : x->r; } + x = new node(v, info, z, z); + if (v < p->key) p->l = x; else p->r = x; + } + +void Dict::treeprint(struct node *x) + { + if (x != z) + { + treeprint(x->l); + printnode(x); + treeprint(x->r); + } + } + +void Dict::remove(itemType v) + { + struct node *c, *p, *x, *t; + z->key = v; + p = head; x = head->r; + while (v != x->key) + { p = x; x = (v < x->key) ? x->l : x->r; } + t = x; + if (t->r == z) x = x->l; + else if (t->r->l == z) { x = x->r; x->l = t->l; } + else + { + c = x->r; while (c->l->l != z) c = c->l; + x = c->l; c->l = x->r; + x->l = t->l; x->r = t->r; + } + delete t; + if (v < p->key) p->l = x; else p->r = x; + } + + +-------------------------------- +CHAPTER 15 Balanced Trees + +void Dict::insert(itemType v, infoType info) + { + x = head; p = head; g = head; + while (x != z) + { + gg = g; g = p; p = x; + x = (v < x->key) ? x->l : x->r; + if (x->l->b && x->r->b) split(v); + } + x = new node(v, info, 1, z, z); + if (v < p->key) p->l = x; else p->r = x; + split(v); head->r->b = black; + } + +struct node *rotate(itemType v, struct node *y) + { + struct node *c, *gc; + c = (v < y->key) ? y->l : y->r; + if (v < c->key) + { gc = c->l; c->l = gc->r; gc->r = c; } + else + { gc = c->r; c->r = gc->l; gc->l = c; } + if (v < y->key) y->l = gc; else y->r = gc; + return gc; + } + +void split(itemType v) + { + x->b = red; x->l->b = black; x->r->b = black; + if (p->b) + { + g->b = red; + if (vkey != vkey) p = rotate(v, g); + x = rotate(v, gg); + x->b = black; + } + } + + Dict(int max) + { + z = new node( 0, infoNIL, black, 0, 0); + z->l = z; z->r = z; + head = new node(itemMIN, 0, black, 0, z); + } + + +-------------------------------- +CHAPTER 16 Hashing + +unsigned stringkey::hash(int M) + { + int h; char *t = v; + for (h = 0; *t; t++) + h = (64*h + *t) % M; + return h; + } + +Dict::Dict(int sz) + { + M = sz; + z = new node; z->next = z; z->info = infoNIL; + heads = new node*[M]; + for (int i = 0; i < M; i++) + { heads[i] = new node; heads[i]->next = z; } + } + +class Dict + { + private: + struct node + { itemType key; infoType info; + node() { key = " "; info = infoNIL; } + }; + struct node *a; + int M; + public: + Dict(int sz) + { M = sz; a = new node[M]; } + int search(itemType v); + void insert(itemType v, infoType info) + { + int x = v.hash(M); + while (a[x].info != infoNIL) x = (x+1) % M; + a[x].key = v; a[x].info = info; + } + }; + + +-------------------------------- +CHAPTER 17 Radix Searching + +infoType Dict::search(itemType v) // Digital tree + { + struct node *x = head; + int b = itemType::maxb; + z->key = v; + while (v != x->key) + x = (v.bits(b--, 1)) ? x->r : x->l; + return x->info; + } + +void Dict::insert(itemType v, infoType info) + { + struct node *p, *x = head; + int b = itemType::maxb; + while (x != z) + { + p = x; + x = (v.bits(b--, 1)) ? x->r : x->l; + } + x = new node; + x->key = v; x->info = info; x->l = z; x->r = z; + if (v.bits(b+1, 1)) p->r = x; else p->l = x; + } + +infoType Dict::search(itemType v) // Patricia tree + { + struct node *p, *x; + p = head; x = head->l; + while (p->b > x->b) + { + p = x; + x = (bits(v, x->b, 1)) ? x->r : x->l; + } + if (v != x->key) return infoNIL; + return x->info; + } + +void Dict::insert(itemType v, infoType info) + { + struct node *p, *t, *x; + int i = maxb; + p = head; t = head->l; + while (p->b > t->b) + { p = t; t = (bits(v, t->b, 1)) ? t->r : t->l; } + if (v == t->key) return; + while (bits(t->key, i, 1) == bits(v, i, 1)) i--; + p = head; x = head->l; + while (p->b > x->b && x->b > i) + { p = x; x = (bits(v, x->b, 1)) ? x->r : x->l; } + t = new node; + t->key = v; t->info = info; t->b = i; + t->l = (bits(v, t->b, 1)) ? x : t; + t->r = (bits(v, t->b, 1)) ? t : x; + if (bits(v, p->b, 1)) p->r = t; else p->l = t; + } + + +-------------------------------- +CHAPTER 18 External Searching + + +-------------------------------- +CHAPTER 19 String Searching + +int brutesearch(char *p, char *a) + { + int i, j, M = strlen(p), N = strlen(a); + for (i = 0, j = 0; j < M && i < N; i++, j++) + if (a[i] != p[j]) { i -= j-1; j = -1; } + if (j == M) return i-M; else return i; + } + +int kmpsearch(char *p, char *a) + { + int i, j, M = strlen(p), N = strlen(a); + initnext(p); + for (i = 0, j = 0; j < M && i < N; i++, j++) + while ((j >= 0) && (a[i] != p[j])) j = next[j]; + if (j == M) return i-M; else return i; + } + +initnext(char *p) + { + int i, j, M = strlen(p); + next[0] = -1; + for (i = 0, j = -1; i < M; i++, j++, next[i] = j) + while ((j >= 0) && (p[i] != p[j])) j = next[j]; + } + +int kmpsearch(char *a) + { + int i = -1; +sm: i++; +s0: if (a[i] != '1') goto sm; i++; +s1: if (a[i] != '0') goto s0; i++; +s2: if (a[i] != '1') goto s0; i++; +s3: if (a[i] != '0') goto s1; i++; +s4: if (a[i] != '0') goto s2; i++; +s5: if (a[i] != '1') goto s0; i++; +s6: if (a[i] != '1') goto s1; i++; +s7: if (a[i] != '1') goto s1; i++; + return i-8; + } + +next[i] = (p[i] == p[j]) ? next[j] : j + +int mischarsearch(char *p, char *a) + { + int i, j, t, M = strlen(p), N = strlen(a); + initskip(p); + for (i = M-1, j = M-1; j > 0; i--, j--) + while (a[i] != p[j]) + { + t = skip[index(a[i])]; + i += (M-j > t) ? M-j : t; + if (i >= N) return N; + j = M-1; + } + return i; + } + +const int q = 33554393; +const int d = 32; +int rksearch(char *p, char *a) + { + int i, dM = 1, h1 = 0, h2 = 0; + int M = strlen(p), N = strlen(a); + for (i = 1; i < M; i++) dM = (d*dM) % q; + for (i = 0; i < M; i++) + { + h1 = (h1*d+index(p[i])) % q; + h2 = (h2*d+index(a[i])) % q; + } + for (i = 0; h1 != h2; i++) + { + h2 = (h2+d*q-index(a[i])*dM) % q; + h2 = (h2*d+index(a[i+M])) % q; + if (i > N-M) return N; + } + return i; + } + + +-------------------------------- +CHAPTER 20 Pattern Matching + +const int scan = -1; +int match(char *a) + { + int n1, n2; Deque dq(100); + int j = 0, N = strlen(a), state = next1[0]; + dq.put(scan); + while (state) + { + if (state == scan) { j++; dq.put(scan); } + else if (ch[state] == a[j]) + dq.put(next1[state]); + else if (ch[state] == ' ') + { + n1 = next1[state]; n2 = next2[state]; + dq.push(n1); if (n1 != n2) dq.push(n2); + } + if (dq.empty() || j==N) return 0; + state = dq.pop(); + } + return j; + } + + +-------------------------------- +CHAPTER 21 Parsing + +expression() + { + term(); + if (p[j] == '+') + { j++; expression(); } + } + +term() + { + factor(); + if ((p[j] == '(') || letter(p[j])) term(); + } + +factor() + { + if (p[j] == '(') + { + j++; expression(); + if (p[j] == ')') j++; else error(); + } + else if (letter(p[j])) j++; else error(); + if (p[j] == '*') j++; + } + +expression + term + factor + ( + expression + term + factor A * + term + factor B + + + expression + term + factor A + term + factor C + ) + term + factor D + +badexpression(); + { + if (letter(p[j])) j++; else + { + badexpression(); + if (p[j] == '+') { j++; term(); } + else error(); + } + } + + +int expression() + { + int t1,t2,r; + t1 = term(); r = t1; + if (p[j] == '+') + { + j++; state++; + t2 = state; r = t2; state++; + setstate(t2, ' ', expression(), t1); + setstate(t2-1, ' ', state, state); + } + return r; + } + +int term() + { + int t, r; + r = factor(); + if ((p[j] == '(') || letter(p[j])) t = term(); + return r; + } + +int factor() + { + int t1, t2, r; + t1 = state; + if (p[j] == '(') + { + j++; t2 = expression(); + if (p[j] == ')') j++; else error(); + } + else if (letter(p[j])) + { + setstate(state, p[j], state+1, state+1); + t2 = state; j++; state++; + } + else error(); + if (p[j] != '*') r = t2; else + { + setstate(state, ' ', state+1, t2); + r = state; next1[t1-1] = state; + j++; state++; + } + return r; + } + +void matchall(char *a) + { + j = 0; state = 1; + next1[0] = expression(); + setstate(0, ' ', next1[0], next1[0]); + setstate(state, ' ', 0, 0); + while (*a) cout << match(a++) << ' '; + cout << '\n'; + } + + +-------------------------------- +CHAPTER 22 File Compression + + for (i = 0; i <= 26; i++) count[i] = 0; + for (i = 0; i < M; i++) count[index(a[i])]++; + + for (i = 0; i <= 26; i++) + if (count[i]) pq.insert(count[i], i); + for ( ; !pq.empty(); i++) + { + t1 = pq.remove(); t2 = pq.remove(); + dad[i] = 0; dad[t1] = i; dad[t2] = -i; + count[i] = count[t1] + count[t2]; + if (!pq.empty()) pq.insert(count[i], i); + } + +for (k = 0; k <= 26; k++) + { + i = 0; x = 0; j = 1; + if (count[k]) + for (t=dad[k]; t; t=dad[t], j+=j, i++) + if (t < 0) { x += j; t = -t; } + code[k] = x; len[k] = i; + } + +for (j = 0; j < M; j++) + for (i = len[index(a[j])]; i > 0; i--) + cout << ((code[index(a[j])] >> i-1) & 1); + + +-------------------------------- +CHAPTER 23 Cryptology + + +-------------------------------- +CHAPTER 24 Elementary Geometric Methods + +struct point { int x, y; char c; }; +struct line { struct point p1, p2; }; +struct point polygon[Nmax]; + +int ccw(struct point p0, + struct point p1, + struct point p2 ) + { + int dx1, dx2, dy1, dy2; + dx1 = p1.x - p0.x; dy1 = p1.y - p0.y; + dx2 = p2.x - p0.x; dy2 = p2.y - p0.y; + if (dx1*dy2 > dy1*dx2) return +1; + if (dx1*dy2 < dy1*dx2) return -1; + if ((dx1*dx2 < 0) || (dy1*dy2 < 0)) return -1; + if ((dx1*dx1+dy1*dy1) < (dx2*dx2+dy2*dy2)) + return +1; + return 0; + } + +int intersect(struct line l1, struct line l2) + { + return ((ccw(l1.p1, l1.p2, l2.p1) + *ccw(l1.p1, l1.p2, l2.p2)) <= 0) + && ((ccw(l2.p1, l2.p2, l1.p1) + *ccw(l2.p1, l2.p2, l1.p2)) <= 0); + } + +float theta(struct point p1, struct point p2) + { + int dx, dy, ax, ay; + float t; + dx = p2.x - p1.x; ax = abs(dx); + dy = p2.y - p1.y; ay = abs(dy); + t = (ax+ay == 0) ? 0 : (float) dy/(ax+ay); + if (dx < 0) t = 2-t; else if (dy < 0) t = 4+t; + return t*90.0; + } + +int inside(struct point t, struct point p[], int N) + { + int i, count = 0, j = 0; + struct line lt,lp; + p[0] = p[N]; p[N+1] = p[1]; + lt.p1 = t; lt.p2 = t; lt.p2.x = INT_MAX; + for (i = 1; i <= N; i++) + { + lp.p1= p[i]; lp.p2 = p[i]; + if (!intersect(lp,lt)) + { + lp.p2 = p[j]; j = i; + if (intersect(lp,lt)) count++; + } + } + return count & 1; + } + + +-------------------------------- +CHAPTER 25 Finding the Convex Hull + +int wrap(point p[], int N) + { + int i, min, M; + float th, v; + for (min = 0, i = 1; i < N; i++) + if (p[i].y < p[min].y) min = i; + p[N] = p[min]; th = 0.0; + for (M = 0; M < N; M++) + { + swap(p, M, min); + min = N; v = th; th = 360.0; + for (i = M+1; i <= N; i++) + if (theta(p[M], p[i]) > v) + if (theta(p[M], p[i]) < th) + { min = i; th = theta(p[M], p[min]); } + if (min == N) return M; + } + } + +int grahamscan(point p[], int N) + { + int i, min, M; + for (min = 1, i = 2; i <= N; i++) + if (p[i].y < p[min].y) min = i; + for (i = 1; i <= N; i++) + if (p[i].y == p[min].y) + if (p[i].x > p[min].x) min = i; + swap(p, 1, min); + shellsort(p, N); + p[0] = p[N]; + for (M = 3, i = 4; i <= N; i++) + { + while (ccw(p[M], p[M-1], p[i]) >= 0) M--; + M++; swap(p, i, M); + } + return M; + } + + +-------------------------------- +CHAPTER 26 Range Searching + +int range(int v1, int v2) + { return ranger(head->r, v1, v2); } +int ranger(struct node *t, int v1, int v2) + { + int tx1, tx2, count = 0; + if (t == z) return 0; + tx1 = (t->key >= v1); + tx2 = (t->key <= v2); + if (tx1) count += ranger(t->l, v1, v2); + if (tx1 && tx2) count++; + if (tx2) count += ranger(t->r, v1, v2); + return count; + } + +class Range + { + private: + struct node + { struct point p; struct node *next; }; + struct node *grid[maxG][maxG]; + struct node *z; + public: + Range(); + void insert(struct point p); + int search(rect range); + }; +Range::Range() + { + int i, j; + z = new node; + for (i = 0; i <= maxG; i++) + for (j = 0; j <= maxG; j++) + grid[i][j] = z; + } +void Range::insert(struct point p) + { + struct node *t = new node; + t->p = p; t->next = grid[p.x/size][p.y/size]; + grid[p.x/size][p.y/size] = t; + } + +int Range::search(struct rect range) // Grid method + { + struct node *t; + int i, j, count = 0; + for (i = range.x1/size; i <= range.x2/size; i++) + for (j = range.y1/size; j <= range.y2/size; j++) + for (t = grid[i][j]; t != z; t = t->next) + if (insiderect(t->p, range)) count++; + return count; + } + +class Range + { + private: + struct node + { struct point p; struct node *l, *r; }; + struct node *z, *head; + struct point dummy; + int searchr(struct node *t, + struct rect range, int d); + public: + Range(); + void insert(struct point p); + int search(rect range); + }; + +void Range::insert(struct point p) // 2D tree + { + struct node *f, *t; int d, td; + for (d = 0, t = head; t != z; d !=d) + { + td = d ? (p.x < t->p.x) : (p.y < t->p.y); + f = t; t = td ? t->l : t->r; + } + t = new node; t->p = p; t->l = z; t->r = z; + if (td) f->l = t; else f->r = t; + } + +int Range::search(struct rect range) // 2D tree + { return searchr(head->r, range, 1); } +int Range::searchr(struct node *t, + struct rect range, int d) + { + int t1, t2, tx1, tx2, ty1, ty2, count = 0; + if (t == z) return 0; + tx1 = range.x1 < t->p.x; tx2 = t->p.x <= range.x2; + ty1 = range.y1 < t->p.y; ty2 = t->p.y <= range.y2; + t1 = d ? tx1 : ty1; t2 = d ? tx2 : ty2; + if (t1) count += searchr(t->l, range, !d); + if (insiderect(t->p, range)) count++; + if (t2) count += searchr(t->r, range, !d); + return count; + } + + +-------------------------------- +CHAPTER 27 Geometric Intersection + +Dict Xtree(Nmax), Ytree(Nmax); +struct line lines[Nmax]; +int count = 0; +int intersections() + { + int x1, y1, x2, y2, N; + for (N = 1; cin >> x1 >> y1 >> x2 >> y2; N++) + { + lines[N].p1.x = x1; lines[N].p1.y = y1; + lines[N].p2.x = x2; lines[N].p2.y = y2; + Ytree.insert(y1, N); + if (y2 != y1) Ytree.insert(y2, N); + } + Ytree.traverse(); + return count; + } + +void Dict::visit(itemType v, infoType info) + { + int t, x1, x2, y1, y2; + x1 = lines[info].p1.x; y1 = lines[info].p1.y; + x2 = lines[info].p2.x; y2 = lines[info].p2.y; + if (x2 < x1) { t = x2; x2 = x1; x1 = t; } + if (y2 < y1) { t = y2; y2 = y1; y1 = t; } + if (v == y1) + Xtree.insert(x1, info); + if (v == y2) + { + Xtree.remove(x1, info); + count += Xtree.range(x1, x2); + } + } + + +-------------------------------- +CHAPTER 28 Closest-Point Problems + +int comp(struct node *t) + { return (pass == 1) ? t->p.x : t->p.y; } +struct node *merge(struct node *a, struct node *b) + { + struct node *c; + c = z; + do + if (comp(a) < comp(b)) + { c->next = a; c = a; a = a->next; } + else + { c->next = b; c = b; b = b->next; } + while (c != z); + c = z->next; z->next = z; + return c; + } + +check(struct point p1, struct point p2) + { + float dist; + if ((p1.y != z->p.y) && (p2.y != z->p.y)) + { + dist = sqrt((p1.x-p2.x)*(p1.x-p2.x) + +(p1.y-p2.y)*(p1.y-p2.y)); + if (dist < min) + { min = dist; cp1 = p1; cp2 = p2; }; + } + } + +struct node *sort(struct node *c, int N) + { + int i; + struct node *a, *b; + float middle; + struct point p1, p2, p3, p4; + if (c->next == z) return c; + a = c; + for (i = 2; i <= N/2; i++) c = c->next; + b = c->next; c->next = z; + if (pass == 2) middle = b->p.x; + c = merge(sort(a, N/2), sort(b, N-(N/2))); + if (pass == 2) + { + p1 = z->p; p2 = z->p; p3 = z->p; p4 = z->p; + for (a = c; a != z; a = a->next) + if (fabs(a->p.x - middle) < min) + { + check(a->p, p1); + check(a->p, p2); + check(a->p, p3); + check(a->p, p4); + p1 = p2; p2 = p3; p3 = p4; p4 = a->p; + } + } + return c; + } + +z = new node; z->p.x = max; + z->p.y = max; z->next = z; +h = new node; h->next = readlist(); +min = max; +pass = 1; h->next = sort(h->next, N); +pass = 2; h->next = sort(h->next, N); + + +-------------------------------- +CHAPTER 29 Elementary Graph Algorithms + +int V, E; +int a[maxV][maxV]; + +void adjmatrix() + { + int j, x, y; + cin >> V >> E; + for (x = 1; x <= V; x++) + for (y = 1; y <= V; y++) a[x][y] = 0; + for (x = 1; x <= V; x++) a[x][x] = 1; + for (j = 1; j <= E; j++) + { + cin >> v1 >> v2; + x = index(v1); y = index(v2); + a[x][y] = 1; a[y][x] = 1; + } + } + +struct node + { int v; struct node *next; }; +int V, E; +struct node *adj[maxV], *z; + +void adjlist() + { + int j, x, y; struct node *t; + cin >> V >> E; + z = new node; z->next = z; + for (j = 1; j <= V; j++) adj[j] = z; + for (j = 1; j <= E; j++) + { + cin >> v1 >> v2; + x = index(v1); y = index(v2); + t = new node; + t->v = x; t->next = adj[y]; adj[y] = t; + t = new node; + t->v = y; t->next = adj[x]; adj[x] = t; + } + } + +void search() + { + int k; + for (k = 1; k <= V; k++) val[k] = unseen; + for (k = 1; k <= V; k++) + if (val[k] == unseen) visit(k); + } + +void visit(int k) // DFS, adjacency lists + { + struct node *t; + val[k] = ++id; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] == unseen) visit(t->v); + } + +void visit(int k) // DFS, adjacency matrix + { + int t; + val[k] = ++id; + for (t = 1; t <= V; t++) + if (a[k][t] != 0) + if (val[t] == unseen) visit(t); + } + +Stack stack(maxV); +void visit(int k) // non-recursive DFS, adj lists + { + struct node *t; + stack.push(k); + while (!stack.empty()) + { + k = stack.pop(); val[k] = ++id; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] == unseen) + { stack.push(t->v); val[t->v] = -1; } + } + } + +Queue queue(maxV); +void visit(int k) // BFS, adjacency lists + { + struct node *t; + queue.put(k); + while (!queue.empty()) + { + k = queue.get(); val[k] = ++id; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] == unseen) + { queue.put(t->v); val[t->v] = -1; } + } + } + + +-------------------------------- +CHAPTER 30 Connectivity + +int visit(int k) // DFS to find articulation points + { + struct node *t; + int m, min; + val[k] = ++id; + min = id; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] == unseen) + { + m = visit(t->v); + if (m < min) min = m; + if (m >= val[k]) cout << name(k); + } + else if (val[t->v] < min) min = val[t->v]; + return min; + } + +class EQ + { + private: + int *dad; + public: + EQ(int size); + int find(int x, int y, int doit); + }; + +int EQ::find(int x, int y, int doit) + { + int i = x, j = y; + while (dad[i] > 0) i = dad[i]; + while (dad[j] > 0) j = dad[j]; + if (doit && (i != j)) dad[j] = i; + return (i != j); + } + +int EQ::find(int x, int y, int doit) + { + int t, i = x, j = y; + while (dad[i] > 0) i = dad[i]; + while (dad[j] > 0) j = dad[j]; + while (dad[x] > 0) + { t = x; x = dad[x]; dad[t] = i; } + while (dad[y] > 0) + { t = y; y = dad[y]; dad[t] = j; } + if (doit && (i != j)) + if (dad[j] < dad[i]) + { dad[j] += dad[i] - 1; dad[i] = j; } + else + { dad[i] += dad[j] - 1; dad[j] = i; } + return (i != j); + } + + +-------------------------------- +CHAPTER 31 Weighted Graphs + +PQ pq(maxV); +visit(int k) // PFS, adjacency lists + { + struct node *t; + if (pq.update(k, -unseen) != 0) dad[k] = 0; + while (!pq.empty()) + { + id++; k = pq.remove(); val[k] = -val[k]; + if (val[k] == -unseen) val[k] = 0; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] < 0) + if (pq.update(t->v, priority)) + { + val[t->v] = -(priority); + dad[t->v] = k; + } + } + } + + +void kruskal() + { + int i, m, V, E; + struct edge + { char v1, v2; int w; }; + struct edge e[maxE]; + PQ pq(maxE); EQ eq(maxE); + cin >> V >> E; + for (i = 1; i <= E; i++) + cin >> e[i].v1 >> e[i].v2 >> e[i].w; + for (i = 1; i <= E; i++) + pq.insert(i, e[i].w); + for (i = 0; i < V-1; ) + { + if (pq.empty()) break; else m = pq.remove(); + if (eq.find(index(e[m].v1),index(e[m].v2),1)) + { cout << e[m].v1 << e[m].v2 << ' '; i++; }; + } + } + +void search() // PFS, adjacency matrix + { + int k, t, min = 0; + for (k = 1; k <= V; k++) + { val[k] = unseen; dad[k] = 0; } + val[0] = unseen-1; + for (k = 1; k != 0; k = min, min = 0) + { + val[k] = -val[k]; + if (val[k] == -unseen) val[k] = 0; + for (t = 1; t <= V; t++) + if (val[t] < 0) + { + if (a[k][t] && (val[t] < -priority)) + { val[t] = -priority; dad[t] = k; } + if (val[t] > val[min]) min = t; + } + } + } + + +-------------------------------- +CHAPTER 32 Directed Graphs + +for (k = 1; k <= V; k++) + { + id = 0; + for (j = 1; j <= V; j++) val[j] = 0; + visit(k); + cout >> '\n'; + } + +for (y = 1; y <= V; y++) + for (x = 1; x <= V; x++) + if (a[x][y]) + for (j = 1; j <= V; j++) + if (a[y][j]) a[x][j] = 1; + +for (y = 1; y <= V; y++) + for (x = 1; x <= V; x++) + if (a[x][y]) + for (j = 1; j <= V; j++) + if (a[y][j] > 0) + if (!a[x][j] || (a[x][y]+a[y][j] < a[x][j])) + a[x][j] = a[x][y] + a[y][j]; + +Stack stack(maxV); +int visit(int k) // DFS to find strong components + { + struct node *t; int m, min; + val[k] = ++id; min = id; + stack.push(k); + for (t = adj[k]; t != z; t = t->next) + { + m = (!val[t->v]) ? visit(t->v) : val[t->v]; + if (m < min) min = m; + } + if (min == val[k]) + { + do + { + m = stack.pop(); cout << m; + val[m] = V+1; + } + while (m != k); + cout << '\n'; + } + return min; + } + + +-------------------------------- +CHAPTER 33 Network Flow + + priority = -flow[k][t]; + if (size[k][t] > 0) priority += size[k][t]; + if (priority > val[k]) priority = val[k]; + +for (;;) + { + if (!search(1,V)) break; + y = V; x = dad[V]; + while (x != 0) + { + flow[x][y] = flow[x][y]+val[V]; + flow[y][x] = -flow[x][y]; + y = x; x = dad[y]; + } + } + + +-------------------------------- +CHAPTER 34 Matching + +for (m = 1; m <= N; m++) + { + for (s = m; s != 0;) + { + next[s]++; w = prefer[s][next[s]]; + if (rank[w][s] < rank[w][fiancee[w]]) + { t = fiancee[w]; fiancee[w] = s; s = t; } + } + } + + +-------------------------------- +CHAPTER 35 Random Numbers + +a[0] = seed; +for (i = 1; i <= N; i++) + a[i] = (a[i-1]*b+1) % m; + +#include +const int m = 100000000; +const int m1 = 10000; +int mult(int p, int q) + { + int p1, p0, q1, q0; + p1 = p/m1; p0 = p%m1; + q1 = q/m1; q0 = q%m1; + return (((p0*q1+p1*q0) % m1)*m1+p0*q0) % m; + } +class Random + { + private: + int a; + public: + Random(int seed) + { a = seed; } + int next() + { const int b = 31415821; + a = (mult(a, b) + 1) % m; + return a; + } + }; +main() + { + int i, N; Random x(1234567); + cin >> N; + for (i = 1; i <= N; i++) + cout << x.next() << ' '; + cout << '\n'; + } + + + int badnext(int r) + { const int b = 31415821; + a = (mult(a, b) + 1) % m; + return a % r; + } + + int next(int r) + { const int b = 31415821; + a = (mult(a, b) + 1) % m; + return ((a/m1)*r)/m1; + } + +class Random + { + private: + int a[55], j; + public: + Random(int seed); + int next(int r) + { + j = (j+1) % 55; + a[j] = (a[(j+23) % 55]+a[(j+54) % 55]) % m; + return ((a[j]/m1)*r)/m1; + } + }; + +Random:: Random(int seed) + { const int b = 31415821; + a[0] = seed; + for (j = 1; j <= 54; j++) + a[j] = (mult(a[j-1], b) + 1) % m; + } + +float chisquare(int N, int r) + { + int i, t, f[rmax]; Random x(1234567); + for (i = 0; i < r; i++) f[i] = 0; + for (i = 0; i < N; i++) f[x.next(r)]++; + for (i = 0, t = 0; i < r; i++) t += f[i]*f[i]; + return (float) ((r*t/N) - N); + } + + +-------------------------------- +CHAPTER 36 Arithmetic + +for (i = 0; i < N; i++) r[i] = p[i]+q[i]; + +for (i = 0; i < 2*N-1; i++) r[i] = 0; +for (i = 0; i < N; i++) + for (j = 0; j < N; j++) + r[i+j] += p[i]*q[j]; + +struct node *add(struct node *p, struct node *q) + { + struct node *t; + t = z; z->c = 0; + while ((p != z) && (q != z)) + { + t->next = new node; + t = t->next; t->c = p->c + q->c; + p = p->next; q = q->next; + } + t->next = z; t = z->next; z->next = z; + return t; + } + +struct node + { int c; int j; struct node *next; }; + +struct node *insert(struct node *t, int c, int j) + { + t->next = new node; + t = t->next; t->c = c; t->j = j; + return t; + } + +struct node *add(struct node *p, struct node *q) + { + struct node *t; + t = z; z->c = 0; z->j = maxN; + while ((p !=z) || (q != z)) + { + if ((p->j == q->j) && ((p->c + q->c) != 0)) + { + t = insert(t, p->c+q->c, p->j); + p = p->next; q = q->next; + } + else if (p->j < q->j) + { t = insert(t, p->c, p->j); p = p->next; } + else if (q->j < p->j) + { t = insert(t, q->c, q->j); q = q->next; } + } + t->next = z; t = z->next; z->next = z; + return t; + } + +y = p[N]; +for (i = N-1; i >= 0; i--) y = x*y + p[i]; + +float *mult(float p[], float q[], int N) + { + float pl[N/2], ql[N/2], ph[N/2], qh[N/2], + t1[N/2], t2[N/2]; + float r[2*N-2], rl[N], rm[N], rh[N]; + int i, N2; + if (N == 1) + { r[0] = p[0]*q[0]; return (float *) r; } + for (i = 0; i < N/2; i++) + { pl[i] = p[i]; ql[i] = q[i]; } + for (i = N/2; i < N; i++) + { ph[i-N/2] = p[i]; qh[i-N/2] = q[i]; } + for (i = 0; i < N/2; i++) t1[i] = pl[i]+ph[i]; + for (i = 0; i < N/2; i++) t2[i] = ql[i]+qh[i]; + rm = mult(t1, t2, N/2); + rl = mult(pl, ql, N/2); + rh = mult(ph, qh, N/2); + for (i = 0; i < N-1; i++) r[i] = rl[i]; + r[N-1] = 0; + for (i = 0; i < N-1; i++) r[N+i] = rh[i]; + for (i = 0; i < N-1; i++) + r[N/2+i] += rm[i] - (rl[i]+rh[i]); + return (float *) r; + } + + for (i = 0; i < N; i++) + for (j = 0; j < N; j++) + for (k = 0, r[i][j] = 0; k < N; k++) + r[i][j] += p[i][k]*q[k][j]; + + +-------------------------------- +CHAPTER 37 Gaussian Elimination + +for (i = 1; i <= N; i++) + for (j = i+1; j <= N; j++) + for (k = N+1; k >= i; k--) + a[j][k] -= a[i][k]*a[j][i]/a[i][i]; + +eliminate() + { + int i, j, k, max; + float t; + for (i = 1; i <= N; i++) + { + max = i; + for (j = i+1; j <= N; j++) + if (abs(a[j][i]) > abs(a[max][i])) max = j; + for (k = i; k <= N+1; k++) + { t = a[i][k]; + a[i][k] = a[max][k]; + a[max][k] = t; } + for (j = i+1; j <= N; j++) + for (k = N+1; k >= i; k--) + a[j][k] -= a[i][k]*a[j][i]/a[i][i]; + } + } + +substitute() + { + int j, k; + float t; + for (j = N; j >= 1; j--) + { + t = 0.0; + for (k = j+1; k <= N; k++) t += a[j][k]*x[k]; + x[j] = (a[j][N+1]-t)/a[j][j]; + } + } + + for (i = 1; i < N; i++) + { + a[i+1][N+1] -= a[i][N+1]*a[i+1][i]/a[i][i]; + a[i+1][i+1] -= a[i][i+1]*a[i+1][i]/a[i][i]; + } + for (j = N; j >= 1; j--) + x[j] = (a[j][N+1]-a[j][j+1]*x[j+1])/a[j][j]; + + +-------------------------------- +CHAPTER 38 Curve Fitting + +makespline(float x[], float y[], int N) + { + for (i = 2; i < N; i++) d[i] = 2*(x[i+1]-x[i-1]); + for (i = 1; i < N; i++) u[i] = x[i+1]-x[i]; + for (i = 2; i < N; i++) + w[i] = 6.0*((y[i+1]-y[i])/u[i] + -(y[i]-y[i-1])/u[i-1]); + p[1] = 0.0; p[N] = 0.0; + for (i = 2; i < N-1; i++) + { + w[i+1] = w[i+1] - w[i]*u[i]/d[i]; + d[i+1] = d[i+1] - u[i]*u[i]/d[i]; + } + for (i = N-1; i > 1; i--) + p[i] = (w[i]-u[i]*p[i+1])/d[i]; + } + +float f(float x) + { return x*x*x - x; } +float eval(float v) + { + float t; int i = 1; + while (v > x[i+1]) i++; + t = (v-x[i])/u[i]; + return t*y[i+1]+(1-t)*y[i] + + u[i]*u[i]*(f(t)*p[i+1]+f(1-t)*p[i])/6.0; + } + +for (i = 1; i <= M; i++) + for (j = 1; j <= M+1; j++) + { + t = 0.0; + for (k = 1; k <= N; k++) + t += f[i][k]*f[j][k]; + a[i][j] = t; + } + + +-------------------------------- +CHAPTER 39 Integration + +for (i = N; i > 0; i--) p[i] = p[i-1]/i; p[0] = 0; + +double intrect(double a, double b, int N) + { + int i; double r = 0; double w = (b-a)/N; + for (i = 1; i <= N; i++) r += w*f(a-w/2+i*w); + return r; + } + +double inttrap(double a, double b, int N) + { + int i; double t = 0; double w = (b-a)/N; + for (i = 1; i <= N; i++) + t += w*(f(a+(i-1)*w)+f(a+i*w))/2; + return t; + } + +double intsimp(double a, double b, int N) + { + int i; double s = 0; double w = (b-a)/N; + for (i = 1; i <= N; i++) + s += w*(f(a+(i-1)*w) + + 4*f(a-w/2+i*w) + + f(a+i*w))/6; + return s; + } + +double adapt(double a, double b) + { + double x = intsimp(a, b, 10); + if (fabs(x - intsimp(a, b, 5)) > tolerance) + return adapt(a, (a+b)/2) + adapt((a+b)/2, b); + return x; + } + + +-------------------------------- +CHAPTER 40 Parallel Algorithms + + +-------------------------------- +CHAPTER 41 The Fast Fourier Transform + +eval(p, outN, 0); +eval(q, outN, 0); +for (i = 0; i <= outN; i++) r[i] = p[i]*q[i]; +eval(r, outN, 0); +for (i = 1; i <= N; i++) + { t = r[i]; r[i] = r[outN+1-i]; r[outN+1-i] = t; } +for (i = 0; i <= outN; i++) r[i] = r[i]/(outN+1); + +eval(complex p[], int N, int k) + { + int i, j; + if (N == 1) + { + p0 = p[k]; p1 = p[k+1]; + p[k] = p0+p1; p[k+1] = p0-p1; + } + else + { + for (i = 0; i <= N/2; i++) + { + j = k+2*i; + t[i] = p[j]; t[i+1+N/2] = p[j+1]; + } + for (i = 0; i <= N; i++) p[k+i] = t[i]; + eval(p, N/2, k); + eval(p, N/2, (k+1+N)/2); + j = (outN+1)/(N+1); + for (i = 0; i <= N/2; i++) + { + p0 = w[i*j]*p[k+(N/2)+1+i]; + t[i] = p[k+i]+p0; + t[i+(N/2)+1] = p[k+i]-p0; + } + for (i = 0; i <= N; i++) p[k+i] = t[i]; + } + } + + +-------------------------------- +CHAPTER 42 Dynamic Programming + +for (j = 1; j <= N; j++) + { + for (i = 1; i <= M; i++) + if (i >= size[j]) + if (cost[i] < cost[i-size[j]]+val[j]) + { + cost[i] = cost[i-size[j]]+val[j]; + best[i] = j; + } + } + +for (i = 1; i <= N; i++) + for (j = i+1; j <= N; j++) cost[i][j] = INT_MAX; +for (i = 1; i <= N; i++) cost[i][i] = 0; +for (j = 1; j < N; j++) + for (i = 1; i <= N-j; i++) + for (k = i+1; k <= i+j; k++) + { + t = cost[i][k-1]+cost[k][i+j] + +r[i]*r[k]*r[i+j+1]; + if (t < cost[i][i+j]) + { cost[i][i+j] = t; best[i][i+j] = k; } + } + +order(int i, int j) + { + if (i == j) cout >> name(i); else + { + cout >> '('; + order(i, best[i][j]-1); order(best[i][j], j); + cout >> ')'; + } + } + +for (i = 1; i <= N; i++) + for (j = i+1; j <= N+1; j++) cost[i][j] = INT_MAX; +for (i = 1; i <= N; i++) cost[i][i] = f[i]; +for (i = 1; i <= N+1; i++) cost[i][i-1] = 0; +for (j = 1; j <= N-1; j++) + for (i = 1; i <= N-j; i++) + { + for (k = i; k <= i+j; k++) + { + t = cost[i][k-1]+cost[k+1][i+j]; + if (t < cost[i][i+j]) + { cost[i][i+j] = t; best[i][i+j] = k; } + } + for (k = i; k <= i+j; cost[i][i+j] += f[k++]) ; + } + + +-------------------------------- +CHAPTER 43 Linear Programming + +pivot(int p, int q) + { + int j, k; + for (j = 0; j <= N; j++) + for (k = M+1; k >= 1; k--) + if (j!=p && k!=q) + a[j][k] = a[j][k]-a[p][k]*a[j][q]/a[p][q]; + for (j = 0; j <= N; j++) + if (j != p) a[j][q] = 0; + for (k = 1; k <= M+1; k++) + if (k != q) a[p][k] = a[p][k]/a[p][q]; + a[p][q] = 1; + } + +for (;;) + { + for (q = 0; (q<=M+1) && (a[0][q]>=0); q++) ; + for (p = 0; (p<=N+1) && (a[p][q]<=0); p++) ; + if (q>M || p>N) break; + for (i = p+1; i <= N; i++) + if (a[i][q] > 0) + if (a[i][M+1]/a[i][q] < a[p][M+1]/a[p][q]) + p = i; + pivot(p,q); + } + + +-------------------------------- +CHAPTER 44 Exhaustive Search + +visit(int k) + { + int t; + val[k] = ++id; + for (t = 1; t <= V; t++) + if (a[k][t]) + if (val[t] == 0) visit(t); + id--; val[k] = 0; + } + +visit(int k) + { + int t; + val[k] = ++id; + if (id == V) writeperm(); + for (t = 1; t <= V; t++) + if (val[t] == 0) visit(t); + id--; val[k] = 0; + } + + +-------------------------------- +CHAPTER 45 NP-Complete Problems + From 89248d84f420187c94c67f7bcac3e1bef11134a9 Mon Sep 17 00:00:00 2001 From: Dharmanshu Singh <100850063+dharmanshu1921@users.noreply.github.com> Date: Sat, 1 Oct 2022 10:49:30 +0530 Subject: [PATCH 040/278] Add files via upload --- queue.cpp | 110 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 queue.cpp diff --git a/queue.cpp b/queue.cpp new file mode 100644 index 0000000..0bd1436 --- /dev/null +++ b/queue.cpp @@ -0,0 +1,110 @@ +#include +using namespace std; +#define endl "\n" +class Queue{ + private: + int front; + int rear; + char arr[4]; + + public: + Queue() { + front = -1; + rear = -1; + for (int i = 0; i < 5; i++) { + arr[i] = 0; + } + } + + bool isEmpty() { + if (front == -1 && rear == -1) + return true; + else + return false; + } + + bool isFull(){ + if(rear==4) + return true; + else + return false; + } + + void enqueue(int val){ + if(isFull()){ + cout<<"Queue Full"<> value; + s1.enqueue(value); + + cout<<"Enter second char"<> value; + s1.enqueue(value); + + cout<<"Enter third char"<> value; + s1.enqueue(value); + + cout<<"Enter fourth char"<> value; + s1.enqueue(value); + + s1.display(); + + s1.dequeue(); + s1.display(); + + s1.dequeue(); + s1.display(); + + s1.dequeue(); + s1.display(); + + s1.dequeue(); + s1.dequeue(); + + return 0; +} \ No newline at end of file From 42539b1c03f795a91cd5ace0c5db82c8877feabb Mon Sep 17 00:00:00 2001 From: Subham Roy <83629415+itssubhamroy23@users.noreply.github.com> Date: Sat, 1 Oct 2022 11:07:22 +0530 Subject: [PATCH 041/278] Add files via upload --- countingSort.java | 52 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 countingSort.java diff --git a/countingSort.java b/countingSort.java new file mode 100644 index 0000000..6dbd2da --- /dev/null +++ b/countingSort.java @@ -0,0 +1,52 @@ +// Java implementation of Counting Sort +class CountingSort { + void sort(char arr[]) + { + int n = arr.length; + + // The output character array that will have sorted arr + char output[] = new char[n]; + + // Create a count array to store count of individual + // characters and initialize count array as 0 + int count[] = new int[256]; + for (int i = 0; i < 256; ++i) + count[i] = 0; + + // store count of each character + for (int i = 0; i < n; ++i) + ++count[arr[i]]; + + // Change count[i] so that count[i] now contains actual + // position of this character in output array + for (int i = 1; i <= 255; ++i) + count[i] += count[i - 1]; + + // Build the output character array + // To make it stable we are operating in reverse order. + for (int i = n - 1; i >= 0; i--) { + output[count[arr[i]] - 1] = arr[i]; + --count[arr[i]]; + } + + // Copy the output array to arr, so that arr now + // contains sorted characters + for (int i = 0; i < n; ++i) + arr[i] = output[i]; + } + + // Driver method + public static void main(String args[]) + { + CountingSort ob = new CountingSort(); + char arr[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o', + 'r', 'g', 'e', 'e', 'k', 's' }; + + ob.sort(arr); + + System.out.print("Sorted character array is "); + for (int i = 0; i < arr.length; ++i) + System.out.print(arr[i]); + } +} +/*This code is contributed by Rajat Mishra */ From 1f11c8f7f42c287644f14b634c35e840d133f7e8 Mon Sep 17 00:00:00 2001 From: yashsinha2512 <71962198+yashsinha2512@users.noreply.github.com> Date: Sat, 1 Oct 2022 11:51:42 +0530 Subject: [PATCH 042/278] Update README.md Contributions section added --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 274352b..b27d37e 100644 --- a/README.md +++ b/README.md @@ -1 +1,7 @@ # Algorithms 🅰️^_^ + + +#Contributing: +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. + +Please make sure to update tests as appropriate. From 25a5e7f5bc116ca9b8eb3000edf13cfa284d3229 Mon Sep 17 00:00:00 2001 From: Tilak Sovan Khatua <62074842+tilak-codes@users.noreply.github.com> Date: Sat, 1 Oct 2022 11:52:40 +0530 Subject: [PATCH 043/278] minimum extraction --- minimum_extraction.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 minimum_extraction.cpp diff --git a/minimum_extraction.cpp b/minimum_extraction.cpp new file mode 100644 index 0000000..5cfd470 --- /dev/null +++ b/minimum_extraction.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; +#define MAX 10000 +#define ll long long +int main() { + int tt; + cin>>tt; + while(tt--) { + ll n; + cin>>n; + ll arr[n]; + for(int i=0;i>arr[i]; + } + sort(arr,arr+n); + ll curr = 0; + ll ans = arr[0]; + for(int i=0;i=0) + curr+=arr[i]; + else + curr += arr[i]; + ans = max(ans , arr[i+1] - curr); + arr[i+1] -= curr; + } + cout< Date: Sat, 1 Oct 2022 11:53:42 +0530 Subject: [PATCH 044/278] Sieve_algorithm --- Sieve_algorithm.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Sieve_algorithm.cpp diff --git a/Sieve_algorithm.cpp b/Sieve_algorithm.cpp new file mode 100644 index 0000000..aa44478 --- /dev/null +++ b/Sieve_algorithm.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; +#define pb push_back +typedef long long ll; +typedef unsigned long int ull; + +int main() +{ + int n = 1e5 + 10; + vector cp(n, true); + cp[0] = cp[1] = false; + + for (int i = 2; i < n; i++) + { + if (cp[i]) + { + for (int j = i * 2; j < n; j += i) + { + cp[j] = false; + } + } + } + + int num; + cin >> num; + + if (cp[num]) + cout << "prime"; + else if(!cp[num]) + cout << "not prime"; +} \ No newline at end of file From 21ab0b8ba2d9a8650a10de4f578d2b0d202aeaaa Mon Sep 17 00:00:00 2001 From: Ravi Lamkoti Date: Sat, 1 Oct 2022 12:02:07 +0530 Subject: [PATCH 045/278] chore: organize the folder structure --- Binary search | 42 ------------------ BubbleSort.java | 35 --------------- .../Bike helmet tilt.dev | 0 .../FractionalKnapsack.cpp | 0 Hanoi Algorithm => CPP/Hanoi Algorithm | 0 .../LONGEST-INCREASING-SUBSEQUENCE.cpp | 0 Student DBMS.cpp => CPP/Student DBMS.cpp | 0 .../Subarray sum equal to k.cpp | 0 1.cpp => CPP/basic-string.cpp | 0 binary tree => CPP/binary tree | 0 .../binary tree in order traversal | 0 .../binary tree postorder traversal | 0 binary search => CPP/binary-search.cpp | 0 bubble sort => CPP/bubble sort | 0 insertion sort => CPP/insertion sort | 0 linear search => CPP/linear search | 0 .../link list insertion operations | 0 Merge short algorithm => CPP/merge-sort.cpp | 0 .../multiply_two_matrix.cpp | 0 poi_dyn_str.cpp => CPP/poi_dyn_str.cpp | 0 .../preorder-traversal.cpp | 0 .../queue all operations | 0 Selection sort => CPP/selection-sort.cpp | 0 .../singly-linked-list.cpp | 0 .../stack all operation | 0 tree.cpp => CPP/tree.cpp | 0 BinarySearch.java => Java/BinarySearch.java | 0 LinearSearch.java => Java/LinearSearch.java | 0 Main.class => Java/Main.class | Bin .../QuickSortAlogorithem.java | 0 RadixSort.java => Java/RadixSort.java | 0 .../SortingusingSort.java | 0 algorithms.java => Java/algorithms.java | 0 bubble_sort.java => Java/bubble_sort.java | 0 bubblesort.java => Java/bubblesort.java | 0 bucketsort.java => Java/bucketsort.java | 0 .../complex-string.java | 0 heapsort.java => Java/heapsort.java | 0 merge.java => Java/merge.java | 0 mergeSort.class => Java/mergeSort.class | Bin mergeSort.java => Java/mergeSort.java | 0 bubbleSort.js => Javascript/bubbleSort.js | 0 practical1.py => Python/math-basic.py | 0 triangle.py => Python/triangle.py | 0 44 files changed, 77 deletions(-) delete mode 100644 Binary search delete mode 100644 BubbleSort.java rename Bike helmet tilt.dev => CPP/Bike helmet tilt.dev (100%) rename FractionalKnapsack.cpp => CPP/FractionalKnapsack.cpp (100%) rename Hanoi Algorithm => CPP/Hanoi Algorithm (100%) rename LONGEST-INCREASING-SUBSEQUENCE.cpp => CPP/LONGEST-INCREASING-SUBSEQUENCE.cpp (100%) rename Student DBMS.cpp => CPP/Student DBMS.cpp (100%) rename Subarray sum equal to k.cpp => CPP/Subarray sum equal to k.cpp (100%) rename 1.cpp => CPP/basic-string.cpp (100%) rename binary tree => CPP/binary tree (100%) rename binary tree in order traversal => CPP/binary tree in order traversal (100%) rename binary tree postorder traversal => CPP/binary tree postorder traversal (100%) rename binary search => CPP/binary-search.cpp (100%) rename bubble sort => CPP/bubble sort (100%) rename insertion sort => CPP/insertion sort (100%) rename linear search => CPP/linear search (100%) rename link list insertion operations => CPP/link list insertion operations (100%) rename Merge short algorithm => CPP/merge-sort.cpp (100%) rename multiply_two_matrix.cpp => CPP/multiply_two_matrix.cpp (100%) rename poi_dyn_str.cpp => CPP/poi_dyn_str.cpp (100%) rename binary tree preorder traversel => CPP/preorder-traversal.cpp (100%) rename queue all operations => CPP/queue all operations (100%) rename Selection sort => CPP/selection-sort.cpp (100%) rename singly link list => CPP/singly-linked-list.cpp (100%) rename stack all operation => CPP/stack all operation (100%) rename tree.cpp => CPP/tree.cpp (100%) rename BinarySearch.java => Java/BinarySearch.java (100%) rename LinearSearch.java => Java/LinearSearch.java (100%) rename Main.class => Java/Main.class (100%) rename QuickSortAlogorithem.java => Java/QuickSortAlogorithem.java (100%) rename RadixSort.java => Java/RadixSort.java (100%) rename SortingusingSort.java => Java/SortingusingSort.java (100%) rename algorithms.java => Java/algorithms.java (100%) rename bubble_sort.java => Java/bubble_sort.java (100%) rename bubblesort.java => Java/bubblesort.java (100%) rename bucketsort.java => Java/bucketsort.java (100%) rename complex-string.java => Java/complex-string.java (100%) rename heapsort.java => Java/heapsort.java (100%) rename merge.java => Java/merge.java (100%) rename mergeSort.class => Java/mergeSort.class (100%) rename mergeSort.java => Java/mergeSort.java (100%) rename bubbleSort.js => Javascript/bubbleSort.js (100%) rename practical1.py => Python/math-basic.py (100%) rename triangle.py => Python/triangle.py (100%) diff --git a/Binary search b/Binary search deleted file mode 100644 index 086e1d7..0000000 --- a/Binary search +++ /dev/null @@ -1,42 +0,0 @@ -#include -using namespace std; -int binarySearch(int array[], int size, int value) -{ - int first = 0, - last = size - 1, - middle, - position = -1; - bool found = false; - while (!found && first <= last) - { - middle = (first + last) / 2; - if (array[middle] == value) - { - found = true; - position = middle; - } - else if (array[middle] > value) - last = middle - 1; - else - first = middle + 1; - } - return position; -} -int main () -{ - const int size = 5; - int array[size] = {1, 2, 3, 4, 5}; - int value; - int result; - - cout << "What value would you like to search for? "; - cin >> value; - result = binarySearch(array, size, value); - - if (result == -1) - cout << "Not found\n"; - else - cout << "Your value is in the array.\n"; - - return 0; -} diff --git a/BubbleSort.java b/BubbleSort.java deleted file mode 100644 index ae1ceaa..0000000 --- a/BubbleSort.java +++ /dev/null @@ -1,35 +0,0 @@ -public class BubbleSortExample { - static void bubbleSort(int[] arr) { - int n = arr.length; - int temp = 0; - for(int i=0; i < n; i++){ - for(int j=1; j < (n-i); j++){ - if(arr[j-1] > arr[j]){ - //swap elements - temp = arr[j-1]; - arr[j-1] = arr[j]; - arr[j] = temp; - } - - } - } - - } - public static void main(String[] args) { - int arr[] ={3,60,35,2,45,320,5}; - - System.out.println("Array Before Bubble Sort"); - for(int i=0; i < arr.length; i++){ - System.out.print(arr[i] + " "); - } - System.out.println(); - - bubbleSort(arr);//sorting array elements using bubble sort - - System.out.println("Array After Bubble Sort"); - for(int i=0; i < arr.length; i++){ - System.out.print(arr[i] + " "); - } - - } -} \ No newline at end of file diff --git a/Bike helmet tilt.dev b/CPP/Bike helmet tilt.dev similarity index 100% rename from Bike helmet tilt.dev rename to CPP/Bike helmet tilt.dev diff --git a/FractionalKnapsack.cpp b/CPP/FractionalKnapsack.cpp similarity index 100% rename from FractionalKnapsack.cpp rename to CPP/FractionalKnapsack.cpp diff --git a/Hanoi Algorithm b/CPP/Hanoi Algorithm similarity index 100% rename from Hanoi Algorithm rename to CPP/Hanoi Algorithm diff --git a/LONGEST-INCREASING-SUBSEQUENCE.cpp b/CPP/LONGEST-INCREASING-SUBSEQUENCE.cpp similarity index 100% rename from LONGEST-INCREASING-SUBSEQUENCE.cpp rename to CPP/LONGEST-INCREASING-SUBSEQUENCE.cpp diff --git a/Student DBMS.cpp b/CPP/Student DBMS.cpp similarity index 100% rename from Student DBMS.cpp rename to CPP/Student DBMS.cpp diff --git a/Subarray sum equal to k.cpp b/CPP/Subarray sum equal to k.cpp similarity index 100% rename from Subarray sum equal to k.cpp rename to CPP/Subarray sum equal to k.cpp diff --git a/1.cpp b/CPP/basic-string.cpp similarity index 100% rename from 1.cpp rename to CPP/basic-string.cpp diff --git a/binary tree b/CPP/binary tree similarity index 100% rename from binary tree rename to CPP/binary tree diff --git a/binary tree in order traversal b/CPP/binary tree in order traversal similarity index 100% rename from binary tree in order traversal rename to CPP/binary tree in order traversal diff --git a/binary tree postorder traversal b/CPP/binary tree postorder traversal similarity index 100% rename from binary tree postorder traversal rename to CPP/binary tree postorder traversal diff --git a/binary search b/CPP/binary-search.cpp similarity index 100% rename from binary search rename to CPP/binary-search.cpp diff --git a/bubble sort b/CPP/bubble sort similarity index 100% rename from bubble sort rename to CPP/bubble sort diff --git a/insertion sort b/CPP/insertion sort similarity index 100% rename from insertion sort rename to CPP/insertion sort diff --git a/linear search b/CPP/linear search similarity index 100% rename from linear search rename to CPP/linear search diff --git a/link list insertion operations b/CPP/link list insertion operations similarity index 100% rename from link list insertion operations rename to CPP/link list insertion operations diff --git a/Merge short algorithm b/CPP/merge-sort.cpp similarity index 100% rename from Merge short algorithm rename to CPP/merge-sort.cpp diff --git a/multiply_two_matrix.cpp b/CPP/multiply_two_matrix.cpp similarity index 100% rename from multiply_two_matrix.cpp rename to CPP/multiply_two_matrix.cpp diff --git a/poi_dyn_str.cpp b/CPP/poi_dyn_str.cpp similarity index 100% rename from poi_dyn_str.cpp rename to CPP/poi_dyn_str.cpp diff --git a/binary tree preorder traversel b/CPP/preorder-traversal.cpp similarity index 100% rename from binary tree preorder traversel rename to CPP/preorder-traversal.cpp diff --git a/queue all operations b/CPP/queue all operations similarity index 100% rename from queue all operations rename to CPP/queue all operations diff --git a/Selection sort b/CPP/selection-sort.cpp similarity index 100% rename from Selection sort rename to CPP/selection-sort.cpp diff --git a/singly link list b/CPP/singly-linked-list.cpp similarity index 100% rename from singly link list rename to CPP/singly-linked-list.cpp diff --git a/stack all operation b/CPP/stack all operation similarity index 100% rename from stack all operation rename to CPP/stack all operation diff --git a/tree.cpp b/CPP/tree.cpp similarity index 100% rename from tree.cpp rename to CPP/tree.cpp diff --git a/BinarySearch.java b/Java/BinarySearch.java similarity index 100% rename from BinarySearch.java rename to Java/BinarySearch.java diff --git a/LinearSearch.java b/Java/LinearSearch.java similarity index 100% rename from LinearSearch.java rename to Java/LinearSearch.java diff --git a/Main.class b/Java/Main.class similarity index 100% rename from Main.class rename to Java/Main.class diff --git a/QuickSortAlogorithem.java b/Java/QuickSortAlogorithem.java similarity index 100% rename from QuickSortAlogorithem.java rename to Java/QuickSortAlogorithem.java diff --git a/RadixSort.java b/Java/RadixSort.java similarity index 100% rename from RadixSort.java rename to Java/RadixSort.java diff --git a/SortingusingSort.java b/Java/SortingusingSort.java similarity index 100% rename from SortingusingSort.java rename to Java/SortingusingSort.java diff --git a/algorithms.java b/Java/algorithms.java similarity index 100% rename from algorithms.java rename to Java/algorithms.java diff --git a/bubble_sort.java b/Java/bubble_sort.java similarity index 100% rename from bubble_sort.java rename to Java/bubble_sort.java diff --git a/bubblesort.java b/Java/bubblesort.java similarity index 100% rename from bubblesort.java rename to Java/bubblesort.java diff --git a/bucketsort.java b/Java/bucketsort.java similarity index 100% rename from bucketsort.java rename to Java/bucketsort.java diff --git a/complex-string.java b/Java/complex-string.java similarity index 100% rename from complex-string.java rename to Java/complex-string.java diff --git a/heapsort.java b/Java/heapsort.java similarity index 100% rename from heapsort.java rename to Java/heapsort.java diff --git a/merge.java b/Java/merge.java similarity index 100% rename from merge.java rename to Java/merge.java diff --git a/mergeSort.class b/Java/mergeSort.class similarity index 100% rename from mergeSort.class rename to Java/mergeSort.class diff --git a/mergeSort.java b/Java/mergeSort.java similarity index 100% rename from mergeSort.java rename to Java/mergeSort.java diff --git a/bubbleSort.js b/Javascript/bubbleSort.js similarity index 100% rename from bubbleSort.js rename to Javascript/bubbleSort.js diff --git a/practical1.py b/Python/math-basic.py similarity index 100% rename from practical1.py rename to Python/math-basic.py diff --git a/triangle.py b/Python/triangle.py similarity index 100% rename from triangle.py rename to Python/triangle.py From 1c96e06fb044d032155caf0f54bbc75d4f2727b2 Mon Sep 17 00:00:00 2001 From: Asmit Kumar <114564653+Asmit-Kumar0@users.noreply.github.com> Date: Sat, 1 Oct 2022 12:02:50 +0530 Subject: [PATCH 046/278] hactoberfest-2022 --- infix_to_postfix.c | 123 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 infix_to_postfix.c diff --git a/infix_to_postfix.c b/infix_to_postfix.c new file mode 100644 index 0000000..8edc19d --- /dev/null +++ b/infix_to_postfix.c @@ -0,0 +1,123 @@ +#include +#define MAX 100 +char st[100]; +int top = -1; +char str[100]; +char str1[100]; + +int findchar(char ch) +{ + if (ch == '-' || ch == '+' || ch == '*' || ch == '/' || ch == '%' || ch == '^' || ch == '&') + { + return 1; + } + else + return 0; +} + +int precedence(char ch) +{ + if (ch == '^' || ch == '&') + { + return 3; + } + else if (ch == '*' || ch == '/') + { + return 2; + } + else if (ch == '+' || ch == '-') + { + return 1; + } + else if (ch == '(') + { + return -1; + } + return 0; +} + +char pop() +{ + if (top == -1) + { + return -1; + } + else + { + return st[top--]; + // top--; + } +} + +void push(char ch) +{ + // top++; + st[++top] = ch; +} + +int main() +{ + int i, j = 0, k; + printf("Enter the infix expression :\n"); + scanf("%s", str); + printf("It's postfix Expression is :\n"); + + for (i = 0; str[i] != '\0'; i++) + { + if (str[i] == '(') + { + push(str[i]); + } + else if (str[i] == ')') + { + for (k = top; st[top] != '('; k--) + { + // str1[j] = pop(); + // j++; + printf("%c", pop()); + } + pop(); + } + else if (!findchar(str[i])) + { + // str1[j] = str[i]; + // j++; + + printf("%c", str[i]); + } + else if (precedence(str[i])) + { + if (precedence(st[top]) == -1) + { + push(str[i]); + } + else if ((top != -1) && (precedence(st[top]) != -1) && precedence(str[i]) <= precedence(st[top])) + { + printf("%c", pop()); + + if (precedence(str[i]) <= precedence(st[top])) + { + printf("%c", pop()); + } + if (precedence(str[i]) <= precedence(st[top])) + { + printf("%c", pop()); + } + push(str[i]); + } + + else if (precedence(str[i]) > precedence(st[top])) + { + push(str[i]); + } + } + } + + while (top >= 0) + { + printf("%c", pop()); + } + printf("\n"); + + return 0; +} From ea54dedba511c99e415be9ba9bf6603043087158 Mon Sep 17 00:00:00 2001 From: Anurag Dutt <62209181+anurag-compile@users.noreply.github.com> Date: Sat, 1 Oct 2022 12:31:50 +0530 Subject: [PATCH 047/278] StringIntro H --- javastringintro.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 javastringintro.java diff --git a/javastringintro.java b/javastringintro.java new file mode 100644 index 0000000..00afd91 --- /dev/null +++ b/javastringintro.java @@ -0,0 +1,22 @@ +package day3; + +import java.io.*; +import java.util.*; + +public class javastringintro { + + public static void main(String[] args) { + + Scanner sc=new Scanner(System.in); + String A=sc.next(); + String B=sc.next(); + /* Enter your code here. Print output to STDOUT. */ + System.out.println(A.length() + B.length()); + System.out.println(A.compareTo(B) > 0 ? "Yes" : "No"); + System.out.println(capitalize(A) + " " + capitalize(B)); + } + + private static String capitalize(String word) { + return word.substring(0, 1).toUpperCase() + word.substring(1, word.length()); + } +} \ No newline at end of file From ec9a6392a52cb46017e8e45e919ad995a723bf54 Mon Sep 17 00:00:00 2001 From: bhattji007 Date: Sat, 1 Oct 2022 12:43:47 +0530 Subject: [PATCH 048/278] hactoberfest-2022 The idea is to use Greedy Approach and try to bring elements having greater difference closer. --- maxSum.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 maxSum.cpp diff --git a/maxSum.cpp b/maxSum.cpp new file mode 100644 index 0000000..770fd46 --- /dev/null +++ b/maxSum.cpp @@ -0,0 +1,34 @@ +// C++ program to maximize the sum of difference +// between consecutive elements in circular array +#include +using namespace std; + +// Return the maximum Sum of difference between +// consecutive elements. +int maxSum(int arr[], int n) +{ + int sum = 0; + + // Sorting the array. + sort(arr, arr + n); + + // Subtracting a1, a2, a3,....., a(n/2)-1, an/2 + // twice and adding a(n/2)+1, a(n/2)+2, a(n/2)+3,. + // ...., an - 1, an twice. + for (int i = 0; i < n/2; i++) + { + sum -= (2 * arr[i]); + sum += (2 * arr[n - i - 1]); + } + + return sum; +} + +// Driver Program +int main() +{ + int arr[] = { 4, 2, 1, 8 }; + int n = sizeof(arr)/sizeof(arr[0]); + cout << maxSum(arr, n) << endl; + return 0; +} From 60790f18231d534d30c64852f76de2b41eadec2b Mon Sep 17 00:00:00 2001 From: Arie <91861324+ariear@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:28:49 +0700 Subject: [PATCH 049/278] add get provider name algorithm --- getProviderName.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 getProviderName.js diff --git a/getProviderName.js b/getProviderName.js new file mode 100644 index 0000000..5b3768d --- /dev/null +++ b/getProviderName.js @@ -0,0 +1,15 @@ +let input = 'arie@hacktober.com' +let provider = ''; + +for (let i = 0; i < input.length; i++) { + if (input[i - 1] === '@') { + for (let j = i; j < input.length; j++) { + if (input[j] === '.') { + break; + } + provider += input[j]; + } + break; + } +} +console.log(`Your email provider is ${provider}`); From d048bc4443241597bf48c60a165d54da9942c5a8 Mon Sep 17 00:00:00 2001 From: Dhiren Kokal <57043968+dhirenkokal@users.noreply.github.com> Date: Sat, 1 Oct 2022 13:30:56 +0530 Subject: [PATCH 050/278] Transpose_of_Matrix --- Transpose_of_Matrix.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Transpose_of_Matrix.cpp diff --git a/Transpose_of_Matrix.cpp b/Transpose_of_Matrix.cpp new file mode 100644 index 0000000..c067c73 --- /dev/null +++ b/Transpose_of_Matrix.cpp @@ -0,0 +1,28 @@ +#include +using namespace std; + +int main() { + int a[10][10], transpose[10][10], row, column, i, j; + + cout << "Enter rows and columns of matrix: "; + cin >> row >> column; + + cout << "\nEnter elements of matrix: " << endl; + + // Storing matrix elements + for (int i = 0; i < row; ++i) { + for (int j = 0; j < column; ++j) { + cout << "Enter element a" << i + 1 << j + 1 << ": "; + cin >> a[i][j]; + } + } + + // Printing the a matrix + cout << "\nEntered Matrix: " << endl; + for (int i = 0; i < row; ++i) { + for (int j = 0; j < column; ++j) { + cout << " " << a[i][j]; + if (j == column - 1) + cout << endl << endl; + } + } From e1be6aef4a59eb52b8df300f6f36a3daa9aac10e Mon Sep 17 00:00:00 2001 From: Dhiren Kokal <57043968+dhirenkokal@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:01:28 +0530 Subject: [PATCH 051/278] Determinant_of_Matrix --- Determinant_of_Matrix.java | 94 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 Determinant_of_Matrix.java diff --git a/Determinant_of_Matrix.java b/Determinant_of_Matrix.java new file mode 100644 index 0000000..bf856b9 --- /dev/null +++ b/Determinant_of_Matrix.java @@ -0,0 +1,94 @@ +// Java program to find Determinant of a matrix +class GFG { + + // Dimension of input square matrix + static final int N = 4; + + // Function to get determinant of matrix + static int determinantOfMatrix(int mat[][], int n) + { + int num1, num2, det = 1, index, + total = 1; // Initialize result + + // temporary array for storing row + int[] temp = new int[n + 1]; + + // loop for traversing the diagonal elements + for (int i = 0; i < n; i++) { + index = i; // initialize the index + + // finding the index which has non zero value + while (mat[index][i] == 0 && index < n) { + index++; + } + if (index == n) // if there is non zero element + { + // the determinant of matrix as zero + continue; + } + if (index != i) { + // loop for swaping the diagonal element row + // and index row + for (int j = 0; j < n; j++) { + swap(mat, index, j, i, j); + } + // determinant sign changes when we shift + // rows go through determinant properties + det = (int)(det * Math.pow(-1, index - i)); + } + + // storing the values of diagonal row elements + for (int j = 0; j < n; j++) { + temp[j] = mat[i][j]; + } + + // traversing every row below the diagonal + // element + for (int j = i + 1; j < n; j++) { + num1 = temp[i]; // value of diagonal element + num2 = mat[j] + [i]; // value of next row element + + // traversing every column of row + // and multiplying to every row + for (int k = 0; k < n; k++) { + // multiplying to make the diagonal + // element and next row element equal + mat[j][k] = (num1 * mat[j][k]) + - (num2 * temp[k]); + } + total = total * num1; // Det(kA)=kDet(A); + } + } + + // multiplying the diagonal elements to get + // determinant + for (int i = 0; i < n; i++) { + det = det * mat[i][i]; + } + return (det / total); // Det(kA)/k=Det(A); + } + + static int[][] swap(int[][] arr, int i1, int j1, int i2, + int j2) + { + int temp = arr[i1][j1]; + arr[i1][j1] = arr[i2][j2]; + arr[i2][j2] = temp; + return arr; + } + + // Driver code + public static void main(String[] args) + { + int mat[][] = { { 1, 0, 2, -1 }, + { 3, 0, 0, 5 }, + { 2, 1, 4, -3 }, + { 1, 0, 5, 0 } }; + + // Function call + System.out.printf( + "Determinant of the matrix is : %d", + determinantOfMatrix(mat, N)); + } +} From 315ddce1723a037f8ded18d5d29ac3219d6f8986 Mon Sep 17 00:00:00 2001 From: Palak Gupta <33149254+palaknaugriya@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:11:36 +0530 Subject: [PATCH 052/278] Hashing Hash Table is a data structure which stores data in an associative manner. In hash table, the data is stored in an array format where each data value has its own unique index value. Access of data becomes very fast, if we know the index of the desired data. --- hashing.cpp | 135 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 hashing.cpp diff --git a/hashing.cpp b/hashing.cpp new file mode 100644 index 0000000..4ff2033 --- /dev/null +++ b/hashing.cpp @@ -0,0 +1,135 @@ +#include +#include +#include +#include + +#define SIZE 20 + +struct DataItem { + int data; + int key; +}; + +struct DataItem* hashArray[SIZE]; +struct DataItem* dummyItem; +struct DataItem* item; + +int hashCode(int key) { + return key % SIZE; +} + +struct DataItem *search(int key) { + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty + while(hashArray[hashIndex] != NULL) { + + if(hashArray[hashIndex]->key == key) + return hashArray[hashIndex]; + + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + return NULL; +} + +void insert(int key,int data) { + + struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem)); + item->data = data; + item->key = key; + + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty or deleted cell + while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1) { + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + hashArray[hashIndex] = item; +} + +struct DataItem* delete(struct DataItem* item) { + int key = item->key; + + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty + while(hashArray[hashIndex] != NULL) { + + if(hashArray[hashIndex]->key == key) { + struct DataItem* temp = hashArray[hashIndex]; + + //assign a dummy item at deleted position + hashArray[hashIndex] = dummyItem; + return temp; + } + + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + return NULL; +} + +void display() { + int i = 0; + + for(i = 0; ikey,hashArray[i]->data); + else + printf(" ~~ "); + } + + printf("\n"); +} + +int main() { + dummyItem = (struct DataItem*) malloc(sizeof(struct DataItem)); + dummyItem->data = -1; + dummyItem->key = -1; + + insert(1, 20); + insert(2, 70); + insert(42, 80); + insert(4, 25); + insert(12, 44); + insert(14, 32); + insert(17, 11); + insert(13, 78); + insert(37, 97); + + display(); + item = search(37); + + if(item != NULL) { + printf("Element found: %d\n", item->data); + } else { + printf("Element not found\n"); + } + + delete(item); + item = search(37); + + if(item != NULL) { + printf("Element found: %d\n", item->data); + } else { + printf("Element not found\n"); + } +} From 061c6300934284d5642635c9d6b6f162c478df38 Mon Sep 17 00:00:00 2001 From: abhishek2384 <83118850+abhishek2384@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:18:01 +0530 Subject: [PATCH 053/278] Create Search_an_element_in_a_sorted_and_rotated_Array.cpp --- ..._element_in_a_sorted_and_rotated_Array.cpp | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Search_an_element_in_a_sorted_and_rotated_Array.cpp diff --git a/Search_an_element_in_a_sorted_and_rotated_Array.cpp b/Search_an_element_in_a_sorted_and_rotated_Array.cpp new file mode 100644 index 0000000..2912dc9 --- /dev/null +++ b/Search_an_element_in_a_sorted_and_rotated_Array.cpp @@ -0,0 +1,82 @@ +// C++ Program to search an element +// in a sorted and pivoted array + +#include +using namespace std; + +// Standard Binary Search function +int binarySearch(int arr[], int low, int high, int key) +{ + if (high < low) + return -1; + + int mid = (low + high) / 2; + if (key == arr[mid]) + return mid; + + if (key > arr[mid]) + return binarySearch(arr, (mid + 1), high, key); + + return binarySearch(arr, low, (mid - 1), key); +} + +// Function to get pivot. For array 3, 4, 5, 6, 1, 2 +// it returns 3 (index of 6) +int findPivot(int arr[], int low, int high) +{ + // Base cases + if (high < low) + return -1; + if (high == low) + return low; + + // low + (high - low)/2; + int mid = (low + high) / 2; + if (mid < high && arr[mid] > arr[mid + 1]) + return mid; + + if (mid > low && arr[mid] < arr[mid - 1]) + return (mid - 1); + + if (arr[low] >= arr[mid]) + return findPivot(arr, low, mid - 1); + + return findPivot(arr, mid + 1, high); +} + +// Searches an element key in a pivoted +// sorted array arr[] of size n +int pivotedBinarySearch(int arr[], int n, int key) +{ + int pivot = findPivot(arr, 0, n - 1); + + // If we didn't find a pivot, + // then array is not rotated at all + if (pivot == -1) + return binarySearch(arr, 0, n - 1, key); + + // If we found a pivot, then first compare with pivot + // and then search in two subarrays around pivot + if (arr[pivot] == key) + return pivot; + + if (arr[0] <= key) + return binarySearch(arr, 0, pivot - 1, key); + + return binarySearch(arr, pivot + 1, n - 1, key); +} + +// Driver program to check above functions +int main() +{ + // Let us search 3 in below array + int arr1[] = { 5, 6, 7, 8, 9, 10, 1, 2, 3 }; + int n = sizeof(arr1) / sizeof(arr1[0]); + int key = 3; + + // Function calling + cout << "Index of the element is : " + << pivotedBinarySearch(arr1, n, key); + + return 0; +} From 3cdb144ff8111856a781fa3b3afe3baf28f59adc Mon Sep 17 00:00:00 2001 From: Sayam Date: Sat, 1 Oct 2022 14:23:04 +0530 Subject: [PATCH 054/278] add sudoku solver --- CPP/Sudoku solver.cpp | 82 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 CPP/Sudoku solver.cpp diff --git a/CPP/Sudoku solver.cpp b/CPP/Sudoku solver.cpp new file mode 100644 index 0000000..6fbdda6 --- /dev/null +++ b/CPP/Sudoku solver.cpp @@ -0,0 +1,82 @@ +#include + +using namespace std; + +#define N 9 + +void print(int arr[N][N]) +{ + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + cout << arr[i][j] << " "; + cout << endl; + } +} + +bool isSafe(int grid[N][N], int row, + int col, int num) +{ + + for (int x = 0; x <= 8; x++) + if (grid[row][x] == num) + return false; + for (int x = 0; x <= 8; x++) + if (grid[x][col] == num) + return false; + int startRow = row - row % 3, + startCol = col - col % 3; + + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) + if (grid[i + startRow][j + + startCol] == num) + return false; + + return true; +} + +bool solveSudoku(int grid[N][N], int row, int col) +{ + if (row == N - 1 && col == N) + return true; + if (col == N) { + row++; + col = 0; + } + if (grid[row][col] > 0) + return solveSudoku(grid, row, col + 1); + + for (int num = 1; num <= N; num++) + { + if (isSafe(grid, row, col, num)) + { + grid[row][col] = num; + + if (solveSudoku(grid, row, col + 1)) + return true; + } + grid[row][col] = 0; + } + return false; +} + +int main() +{ + int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, + { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, + { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, + { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, + { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, + { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, + { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; + + if (solveSudoku(grid, 0, 0)) + print(grid); + else + cout << "no solution exists " << endl; + + return 0; +} From 85da306107018f29675342d76968bdf031abd6d7 Mon Sep 17 00:00:00 2001 From: Alia6922 <112715115+Alia6922@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:35:21 +0530 Subject: [PATCH 055/278] SortinganArray --- sotinganarray.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 sotinganarray.java diff --git a/sotinganarray.java b/sotinganarray.java new file mode 100644 index 0000000..2cdcbd5 --- /dev/null +++ b/sotinganarray.java @@ -0,0 +1,24 @@ +// Java program to demonstrate working of +// sort() method of Arrays class + +// Importing Arrays class from java.util package +import java.util.Arrays; + +// Main class +public class sorting { + + // Main driver method + public static void main(String[] args) + { + // Custom input array + int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 }; + + // Calling the sort() method present + // inside Arrays class + Arrays.sort(arr); + + // Printing and display sorted array + System.out.printf("Modified arr[] : %s", + Arrays.toString(arr)); + } +} From d64d14e0225ac70f8f22a5bda36f476a582348b9 Mon Sep 17 00:00:00 2001 From: Ravi Lamkoti Date: Sat, 1 Oct 2022 14:35:53 +0530 Subject: [PATCH 056/278] add: selection sort algo for jsc --- Javascript/selectionSort.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Javascript/selectionSort.js diff --git a/Javascript/selectionSort.js b/Javascript/selectionSort.js new file mode 100644 index 0000000..2527c73 --- /dev/null +++ b/Javascript/selectionSort.js @@ -0,0 +1,18 @@ +function selectionSort(arr) { + let min; + for (let i = 0; i < arr.length; i++) { + // Assume a minimum value + min = i; + for (let j = i + 1; j < arr.length; j++) { + if (arr[j] < arr[min]) { + min = j; + } + } + + // Swap if new minimun value found + if (min !== i) { + [arr[i], arr[min]] = [arr[min], arr[i]]; + } + } + return arr; +} \ No newline at end of file From ca3b60d3df5c8cc3513154dbc95a75d16653e59d Mon Sep 17 00:00:00 2001 From: dipesh88 <63647097+dipesh88@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:43:16 +0530 Subject: [PATCH 057/278] Maximum of two number --- max2num (2020_12_18 18_56_42 UTC).c | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 max2num (2020_12_18 18_56_42 UTC).c diff --git a/max2num (2020_12_18 18_56_42 UTC).c b/max2num (2020_12_18 18_56_42 UTC).c new file mode 100644 index 0000000..62f252b --- /dev/null +++ b/max2num (2020_12_18 18_56_42 UTC).c @@ -0,0 +1,24 @@ +#include +int main() +{ + +int a,b,c; +printf("enter 2 mumbers\n"); +scanf("%d %d",&a,&b); + +a>b?printf(" a is maximum"): printf("b is maximum\n"); + +printf("\n"); + +return 0; +} + + + + + + + + + + From a45b1e5473c1a3a550a01e653f2d12e89eb52fdc Mon Sep 17 00:00:00 2001 From: Alia6922 <112715115+Alia6922@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:43:45 +0530 Subject: [PATCH 058/278] Armstrong number --- Armstrongnumber.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Armstrongnumber.java diff --git a/Armstrongnumber.java b/Armstrongnumber.java new file mode 100644 index 0000000..141dda7 --- /dev/null +++ b/Armstrongnumber.java @@ -0,0 +1,22 @@ +//finding armstrong number in java +public class Armstrong { + + public static void main(String[] args) { + + int number = 371, originalNumber, remainder, result = 0; + + originalNumber = number; + + while (originalNumber != 0) + { + remainder = originalNumber % 10; + result += Math.pow(remainder, 3); + originalNumber /= 10; + } + + if(result == number) + System.out.println(number + " is an Armstrong number."); + else + System.out.println(number + " is not an Armstrong number."); + } +} From 2afe7e02f9228ce9e928e3fbe69dc5a652aeb26d Mon Sep 17 00:00:00 2001 From: Ravi Lamkoti Date: Sat, 1 Oct 2022 14:44:46 +0530 Subject: [PATCH 059/278] chore: organize files and update readme --- .../Search_an_element_in_a_sorted_and_rotated_Array.cpp | 0 Sieve_algorithm.cpp => CPP/Sieve_algorithm.cpp | 0 Transpose_of_Matrix.cpp => CPP/Transpose_of_Matrix.cpp | 0 hashing.cpp => CPP/hashing.cpp | 0 infix_to_postfix.c => CPP/infix_to_postfix.c | 0 maxSum.cpp => CPP/maxSum.cpp | 0 minimum_extraction.cpp => CPP/minimum_extraction.cpp | 0 queue.cpp => CPP/queue.cpp | 0 AreaOfCircle.java => Java/AreaOfCircle.java | 0 BMI.java => Java/BMI.java | 0 ConMetToFeet.java => Java/ConMetToFeet.java | 0 Determinant_of_Matrix.java => Java/Determinant_of_Matrix.java | 0 Overidding.java => Java/Overidding.java | 0 countingSort.java => Java/countingSort.java | 0 javastringintro.java => Java/javastringintro.java | 0 getProviderName.js => Javascript/getProviderName.js | 0 README.md | 4 +++- 17 files changed, 3 insertions(+), 1 deletion(-) rename Search_an_element_in_a_sorted_and_rotated_Array.cpp => CPP/Search_an_element_in_a_sorted_and_rotated_Array.cpp (100%) rename Sieve_algorithm.cpp => CPP/Sieve_algorithm.cpp (100%) rename Transpose_of_Matrix.cpp => CPP/Transpose_of_Matrix.cpp (100%) rename hashing.cpp => CPP/hashing.cpp (100%) rename infix_to_postfix.c => CPP/infix_to_postfix.c (100%) rename maxSum.cpp => CPP/maxSum.cpp (100%) rename minimum_extraction.cpp => CPP/minimum_extraction.cpp (100%) rename queue.cpp => CPP/queue.cpp (100%) rename AreaOfCircle.java => Java/AreaOfCircle.java (100%) rename BMI.java => Java/BMI.java (100%) rename ConMetToFeet.java => Java/ConMetToFeet.java (100%) rename Determinant_of_Matrix.java => Java/Determinant_of_Matrix.java (100%) rename Overidding.java => Java/Overidding.java (100%) rename countingSort.java => Java/countingSort.java (100%) rename javastringintro.java => Java/javastringintro.java (100%) rename getProviderName.js => Javascript/getProviderName.js (100%) diff --git a/Search_an_element_in_a_sorted_and_rotated_Array.cpp b/CPP/Search_an_element_in_a_sorted_and_rotated_Array.cpp similarity index 100% rename from Search_an_element_in_a_sorted_and_rotated_Array.cpp rename to CPP/Search_an_element_in_a_sorted_and_rotated_Array.cpp diff --git a/Sieve_algorithm.cpp b/CPP/Sieve_algorithm.cpp similarity index 100% rename from Sieve_algorithm.cpp rename to CPP/Sieve_algorithm.cpp diff --git a/Transpose_of_Matrix.cpp b/CPP/Transpose_of_Matrix.cpp similarity index 100% rename from Transpose_of_Matrix.cpp rename to CPP/Transpose_of_Matrix.cpp diff --git a/hashing.cpp b/CPP/hashing.cpp similarity index 100% rename from hashing.cpp rename to CPP/hashing.cpp diff --git a/infix_to_postfix.c b/CPP/infix_to_postfix.c similarity index 100% rename from infix_to_postfix.c rename to CPP/infix_to_postfix.c diff --git a/maxSum.cpp b/CPP/maxSum.cpp similarity index 100% rename from maxSum.cpp rename to CPP/maxSum.cpp diff --git a/minimum_extraction.cpp b/CPP/minimum_extraction.cpp similarity index 100% rename from minimum_extraction.cpp rename to CPP/minimum_extraction.cpp diff --git a/queue.cpp b/CPP/queue.cpp similarity index 100% rename from queue.cpp rename to CPP/queue.cpp diff --git a/AreaOfCircle.java b/Java/AreaOfCircle.java similarity index 100% rename from AreaOfCircle.java rename to Java/AreaOfCircle.java diff --git a/BMI.java b/Java/BMI.java similarity index 100% rename from BMI.java rename to Java/BMI.java diff --git a/ConMetToFeet.java b/Java/ConMetToFeet.java similarity index 100% rename from ConMetToFeet.java rename to Java/ConMetToFeet.java diff --git a/Determinant_of_Matrix.java b/Java/Determinant_of_Matrix.java similarity index 100% rename from Determinant_of_Matrix.java rename to Java/Determinant_of_Matrix.java diff --git a/Overidding.java b/Java/Overidding.java similarity index 100% rename from Overidding.java rename to Java/Overidding.java diff --git a/countingSort.java b/Java/countingSort.java similarity index 100% rename from countingSort.java rename to Java/countingSort.java diff --git a/javastringintro.java b/Java/javastringintro.java similarity index 100% rename from javastringintro.java rename to Java/javastringintro.java diff --git a/getProviderName.js b/Javascript/getProviderName.js similarity index 100% rename from getProviderName.js rename to Javascript/getProviderName.js diff --git a/README.md b/README.md index b27d37e..74af6af 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ # Algorithms 🅰️^_^ -#Contributing: +# Contributing: Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate. + +> Please use latest pull and create file under specific language. \ No newline at end of file From 7219f18bcdfc4d8890cc515d65adb8a4e872221f Mon Sep 17 00:00:00 2001 From: dipesh88 <63647097+dipesh88@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:47:56 +0530 Subject: [PATCH 060/278] Maximum 3 Numbers --- max3num (2020_12_18 18_56_42 UTC).exe | Bin 0 -> 45558 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 max3num (2020_12_18 18_56_42 UTC).exe diff --git a/max3num (2020_12_18 18_56_42 UTC).exe b/max3num (2020_12_18 18_56_42 UTC).exe new file mode 100644 index 0000000000000000000000000000000000000000..74cb47682c41aa6fa6a8761b65b9594eb2e557c4 GIT binary patch literal 45558 zcmeIb3w%`7)i=D)%p@5|$V?zy)Tjd;6cj?j&0s+@NhTM`&0M%BcnHY^qLYis8SY4M z66JJEo2QTO^VpWQUR&+s*V?BPsP(boBEi<$XuY6fOBL(Hpv6m(i)Ft5+WVY2b27p9 z*SGKc_4m~SC+F<7*IIk6wbx$za?aUPc2h62GRAB;BN4{-;z~y@|NHrWI+2}v`ID(^ z*Qj4l-Yb>T}w-=;#%!UO)aj1ifUJLYlAOy%$U(` zjdi7$u~I3OwN@RK85n*jF?Nh4Ny(DM#j=1@h10^=z*tHyW&Tqk&LX3{=^@hRBn?fm)o!tI8^QpW?U{`epL-YxgNc^Aw8&W zV-Aj|_<6Z5g5Qsm@Hi!|+Cg};vV|f!1bYG};Vq$rapbbxyjimsaKLky;nIiGg>xCs zm?M`t^JdM>=8zHzmt#1I-v*p92gjQ?k3$X<-btKmR!Yj~Q=$ACuIWH+Ru~o13aRJT8;5;AzRx^$JqmeU9$)xMsho4g?Qo?6K!hh3q-&JJqxdL zXtEBDrs8%JP}4)_@!@$!s2tNoEHNzdAjlx2g z?%FP}9wKg`d?z6;0|qaQ$V2&A1S>GZDhZYa*kCJ}Z`T#1T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-YXAkM3kH<5S-{UJrVE$IahX=J1d~K^M7L_IH zEs*BIm50L7qiP$g>rN0G?V^#0$uax;8$!Z=_y+7+;MK)2ZD`NKHvcUEP8a*t7g{9t z7NZT}QAd!(*v4LXpw5qG@umPQR>1U%t&i$2hAIs{+C*Q33EGg)wuAH9d7PSE#6`k$z&pu$(p@g_t5*MEiLE`eqV-gcd8J2y}8QOYD)S=hJ{Ja88tC_}#g2P6 zeGyaRb>XPdA8ClzmN^cXDx(3j5v?n&88#r|%q}>-`TVvxQkTK`jU1UFU^HZ2IJW8? xBYJ4VxY4niOsa@zh4E6%?1y03MS>cx-XioU$VJkAoI@UNw+psCPNl7p|GySdLX7|b literal 0 HcmV?d00001 From 2e929d70d9b0680b2864cd314c8207fc8ea0d034 Mon Sep 17 00:00:00 2001 From: Aayush Barmecha <68626644+aayushbarmecha@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:49:08 +0530 Subject: [PATCH 061/278] activity_selection --- CPP/activity_selection.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 CPP/activity_selection.cpp diff --git a/CPP/activity_selection.cpp b/CPP/activity_selection.cpp new file mode 100644 index 0000000..66b0239 --- /dev/null +++ b/CPP/activity_selection.cpp @@ -0,0 +1,32 @@ +#include +using namespace std; +struct Activity{ + int start,finish; +}; +bool ActivityCompare(Activity s1, Activity s2){ + return (s1.finish < s2.finish); +} +void printMaxActivities(Activity arr[],int n){ + sort(arr, arr+n, ActivityCompare); + + cout << "Following activities are selected n"; + + int i = 0; + cout << "(" << arr[i].start << ", " << arr[i].finish << "), "; + + for (int j = 1; j < n; j++) + { + if (arr[j].start >= arr[i].finish) + { + cout << "(" << arr[j].start << ", " + << arr[j].finish << "), "; + i = j; + } + } +} +int main(){ + Activity arr[] = {{5, 9}, {1, 2}, {3, 4}, {0, 6},{5, 7}, {8, 9}}; + int n = sizeof(arr)/sizeof(arr[0]); + printMaxActivities(arr, n); + return 0; +} \ No newline at end of file From 8f747cbe4cf2a917601cb42ab26e8ca58cb12be9 Mon Sep 17 00:00:00 2001 From: dipesh88 <63647097+dipesh88@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:49:22 +0530 Subject: [PATCH 062/278] Strings --- string1.c | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 string1.c diff --git a/string1.c b/string1.c new file mode 100644 index 0000000..450097c --- /dev/null +++ b/string1.c @@ -0,0 +1,9 @@ +#include +int mystrlen(char *); +int main() +{ + + + + return 0; +} From 8bfeda49dee45f6eac21ba9316e5877598271a32 Mon Sep 17 00:00:00 2001 From: dipesh88 <63647097+dipesh88@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:51:13 +0530 Subject: [PATCH 063/278] Binary to Decimal --- bintodecimal (2020_12_18 18_56_42 UTC).c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 bintodecimal (2020_12_18 18_56_42 UTC).c diff --git a/bintodecimal (2020_12_18 18_56_42 UTC).c b/bintodecimal (2020_12_18 18_56_42 UTC).c new file mode 100644 index 0000000..a692ec8 --- /dev/null +++ b/bintodecimal (2020_12_18 18_56_42 UTC).c @@ -0,0 +1,21 @@ +#include +#include +#include + +int main() +{ +long int a,b,x=0,i,n; +int d; +float e; +printf("enter binary number\n"); +scanf("%ld",&n); + +for (i=0;n!=0;++i) +{ + a=n%10; + x=a+(pow(2,i))+x; + n=n/10; +} +printf("%ld",x); + return 0; +} \ No newline at end of file From c6df6f49ded43ec4bd5a75ec5841e509d0d4c77e Mon Sep 17 00:00:00 2001 From: Rishabh Jain <70846152+Rishabhjain2002@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:53:00 +0530 Subject: [PATCH 064/278] Add files via upload please add my file to your repository with label as hacktoberfest --- quicksortc++.txt | 71 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 quicksortc++.txt diff --git a/quicksortc++.txt b/quicksortc++.txt new file mode 100644 index 0000000..b8b0028 --- /dev/null +++ b/quicksortc++.txt @@ -0,0 +1,71 @@ +// C++ Implementation of the Quick Sort Algorithm. +#include +using namespace std; + +int partition(int arr[], int start, int end) +{ + + int pivot = arr[start]; + + int count = 0; + for (int i = start + 1; i <= end; i++) { + if (arr[i] <= pivot) + count++; + } + + // Giving pivot element its correct position + int pivotIndex = start + count; + swap(arr[pivotIndex], arr[start]); + + // Sorting left and right parts of the pivot element + int i = start, j = end; + + while (i < pivotIndex && j > pivotIndex) { + + while (arr[i] <= pivot) { + i++; + } + + while (arr[j] > pivot) { + j--; + } + + if (i < pivotIndex && j > pivotIndex) { + swap(arr[i++], arr[j--]); + } + } + + return pivotIndex; +} + +void quickSort(int arr[], int start, int end) +{ + + // base case + if (start >= end) + return; + + // partitioning the array + int p = partition(arr, start, end); + + // Sorting the left part + quickSort(arr, start, p - 1); + + // Sorting the right part + quickSort(arr, p + 1, end); +} + +int main() +{ + + int arr[] = { 9, 3, 4, 2, 1, 8 }; + int n = 6; + + quickSort(arr, 0, n - 1); + + for (int i = 0; i < n; i++) { + cout << arr[i] << " "; + } + + return 0; +} From acb86851864aae4aea4d3399bde8596a51b7455f Mon Sep 17 00:00:00 2001 From: Aayush Barmecha <68626644+aayushbarmecha@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:54:28 +0530 Subject: [PATCH 065/278] adjacency_list --- CPP/adjacency_list.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 CPP/adjacency_list.cpp diff --git a/CPP/adjacency_list.cpp b/CPP/adjacency_list.cpp new file mode 100644 index 0000000..cda272c --- /dev/null +++ b/CPP/adjacency_list.cpp @@ -0,0 +1,34 @@ +// Adjacency List representation in C++ + +#include +// using namespace std; + +// Add edge +void addEdge(vector adj[], int s, int d) { + adj[s].push_back(d); + adj[d].push_back(s); +} + +// Print the graph +void printGraph(vector adj[], int V) { + for (int d = 0; d < V; ++d) { + cout << "\n Vertex "<< d << ":"; + for (auto x : adj[d]) + cout << "-> " << x; + printf("\n"); + } +} + +int main() { + int V = 5; + + // Create a graph + vector adj[V]; + + // Add edges + addEdge(adj, 0, 1); + addEdge(adj, 0, 2); + addEdge(adj, 0, 3); + addEdge(adj, 1, 2); + printGraph(adj, V); +} \ No newline at end of file From a9079af4b96d4f04fd8b52a0508a80626ef5ab53 Mon Sep 17 00:00:00 2001 From: dipesh88 <63647097+dipesh88@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:55:46 +0530 Subject: [PATCH 066/278] Leap year hacktoberfest-2022 --- leapyear (2020_12_18 18_56_42 UTC).c | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 leapyear (2020_12_18 18_56_42 UTC).c diff --git a/leapyear (2020_12_18 18_56_42 UTC).c b/leapyear (2020_12_18 18_56_42 UTC).c new file mode 100644 index 0000000..8f1024e --- /dev/null +++ b/leapyear (2020_12_18 18_56_42 UTC).c @@ -0,0 +1,10 @@ + +#include +int main() +{ + int year; + printf("enter year\n"); + scanf("%d", &year); +(year%4==0 && year%100!=0) ? printf("LEAP YEAR") : (year%400 ==0 ) ? printf("LEAP YEAR") : printf("COMMON YEAR"); + return 0; +} From b1d13bd35ab16b8b868da8a037e1e664c3fa5e53 Mon Sep 17 00:00:00 2001 From: Aayush Barmecha <68626644+aayushbarmecha@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:58:34 +0530 Subject: [PATCH 067/278] Add files via upload --- adjacency_matrix.cpp | 51 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 adjacency_matrix.cpp diff --git a/adjacency_matrix.cpp b/adjacency_matrix.cpp new file mode 100644 index 0000000..dc2ee38 --- /dev/null +++ b/adjacency_matrix.cpp @@ -0,0 +1,51 @@ +#include +using namespace std; +class Graph{ +private: +int numVertices; +bool** adjMatrix; + +public: +Graph(int numVertices){ + this->numVertices=numVertices; + adjMatrix = new bool*[numVertices]; + for (int i = 0; i < numVertices; i++) { + adjMatrix[i] = new bool[numVertices]; + for (int j = 0; j < numVertices; j++) + adjMatrix[i][j] = 0; +} +} + +void addEdge(int i,int j){ + adjMatrix[i][j]=1; + adjMatrix[j][i]=1; +} +void removeEdge(int i,int j){ + adjMatrix[i][j]=0; + adjMatrix[j][i]=0; +} +void toString(){ + cout<<" "; + for(int i=0;i Date: Sat, 1 Oct 2022 15:00:09 +0530 Subject: [PATCH 068/278] Delete adjacency_list.cpp --- CPP/adjacency_list.cpp | 34 ---------------------------------- 1 file changed, 34 deletions(-) delete mode 100644 CPP/adjacency_list.cpp diff --git a/CPP/adjacency_list.cpp b/CPP/adjacency_list.cpp deleted file mode 100644 index cda272c..0000000 --- a/CPP/adjacency_list.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// Adjacency List representation in C++ - -#include -// using namespace std; - -// Add edge -void addEdge(vector adj[], int s, int d) { - adj[s].push_back(d); - adj[d].push_back(s); -} - -// Print the graph -void printGraph(vector adj[], int V) { - for (int d = 0; d < V; ++d) { - cout << "\n Vertex "<< d << ":"; - for (auto x : adj[d]) - cout << "-> " << x; - printf("\n"); - } -} - -int main() { - int V = 5; - - // Create a graph - vector adj[V]; - - // Add edges - addEdge(adj, 0, 1); - addEdge(adj, 0, 2); - addEdge(adj, 0, 3); - addEdge(adj, 1, 2); - printGraph(adj, V); -} \ No newline at end of file From 89b325cf40357f2123167e2aeb5a4852848231e8 Mon Sep 17 00:00:00 2001 From: Tdsbeast <63647097+dipesh88@users.noreply.github.com> Date: Sat, 1 Oct 2022 15:03:23 +0530 Subject: [PATCH 069/278] Alphabets hacktoberfest-2022 --- charisalphabet (2020_12_18 18_56_42 UTC).c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 charisalphabet (2020_12_18 18_56_42 UTC).c diff --git a/charisalphabet (2020_12_18 18_56_42 UTC).c b/charisalphabet (2020_12_18 18_56_42 UTC).c new file mode 100644 index 0000000..f627650 --- /dev/null +++ b/charisalphabet (2020_12_18 18_56_42 UTC).c @@ -0,0 +1,21 @@ +//char is alphabet or not +#include +int main() +{ + char c; + printf("enter a\n"); + scanf("%c", &c); + + // if (c >= 'a' && c <= 'z' || c >= 'A' && c <= "Z") + // { + // printf("CAHARCTER IS ALPHABET"); + // } + + // else + // { + // printf("NO CAHARCTER IS NOT AN ALPHABET"); + // } + (c >= 'a' && c <= 'z' || c >= 'A' && c <= "Z") ? printf("Character is Alphabet") : printf("NOT AN ALPHABET"); + + return 0; +} From c198b2a17e2ad679d7ff59898f3eaeb1978c3cc8 Mon Sep 17 00:00:00 2001 From: Rishabh Jain <70846152+Rishabhjain2002@users.noreply.github.com> Date: Sat, 1 Oct 2022 15:05:25 +0530 Subject: [PATCH 070/278] Hactoberfest-2022 please add my file to your repository with label as hacktoberfest --- breadthfirstsearch c++.txt | 88 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 breadthfirstsearch c++.txt diff --git a/breadthfirstsearch c++.txt b/breadthfirstsearch c++.txt new file mode 100644 index 0000000..b5f934f --- /dev/null +++ b/breadthfirstsearch c++.txt @@ -0,0 +1,88 @@ +// Program to print BFS traversal from a given +// source vertex. BFS(int s) traverses vertices +// reachable from s. +#include +using namespace std; + +// This class represents a directed graph using +// adjacency list representation +class Graph +{ + int V; // No. of vertices + + // Pointer to an array containing adjacency + // lists + vector> adj; +public: + Graph(int V); // Constructor + + // function to add an edge to graph + void addEdge(int v, int w); + + // prints BFS traversal from a given source s + void BFS(int s); +}; + +Graph::Graph(int V) +{ + this->V = V; + adj.resize(V); +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +void Graph::BFS(int s) +{ + // Mark all the vertices as not visited + vector visited; + visited.resize(V,false); + + // Create a queue for BFS + list queue; + + // Mark the current node as visited and enqueue it + visited[s] = true; + queue.push_back(s); + + while(!queue.empty()) + { + // Dequeue a vertex from queue and print it + s = queue.front(); + cout << s << " "; + queue.pop_front(); + + // Get all adjacent vertices of the dequeued + // vertex s. If a adjacent has not been visited, + // then mark it visited and enqueue it + for (auto adjecent: adj[s]) + { + if (!visited[adjecent]) + { + visited[adjecent] = true; + queue.push_back(adjecent); + } + } + } +} + +// Driver program to test methods of graph class +int main() +{ + // Create a graph given in the above diagram + Graph g(4); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + cout << "Following is Breadth First Traversal " + << "(starting from vertex 2) \n"; + g.BFS(2); + + return 0; +} From c9fce4902e94123cdb5fb54ece35b085b730f791 Mon Sep 17 00:00:00 2001 From: Aayush Barmecha <68626644+aayushbarmecha@users.noreply.github.com> Date: Sat, 1 Oct 2022 15:07:53 +0530 Subject: [PATCH 071/278] flyod_marshall --- CPP/floyd_marshall.cpp | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 CPP/floyd_marshall.cpp diff --git a/CPP/floyd_marshall.cpp b/CPP/floyd_marshall.cpp new file mode 100644 index 0000000..9168553 --- /dev/null +++ b/CPP/floyd_marshall.cpp @@ -0,0 +1,51 @@ +// Floyd-Warshall Algorithm in C++ + +#include +using namespace std; + +// defining the number of vertices +#define nV 4 + +#define INF 999 + +void printMatrix(int matrix[][nV]); + +// Implementing floyd warshall algorithm +void floydWarshall(int graph[][nV]) { + int matrix[nV][nV], i, j, k; + + for (i = 0; i < nV; i++) + for (j = 0; j < nV; j++) + matrix[i][j] = graph[i][j]; + + // Adding vertices individually + for (k = 0; k < nV; k++) { + for (i = 0; i < nV; i++) { + for (j = 0; j < nV; j++) { + if (matrix[i][k] + matrix[k][j] < matrix[i][j]) + matrix[i][j] = matrix[i][k] + matrix[k][j]; + } + } + } + printMatrix(matrix); +} + +void printMatrix(int matrix[][nV]) { + for (int i = 0; i < nV; i++) { + for (int j = 0; j < nV; j++) { + if (matrix[i][j] == INF) + printf("%4s", "INF"); + else + printf("%4d", matrix[i][j]); + } + printf("\n"); + } +} + +int main() { + int graph[nV][nV] = {{0, 3, INF, 5}, + {2, 0, INF, 4}, + {INF, 1, 0, INF}, + {INF, INF, 2, 0}}; + floydWarshall(graph); +} \ No newline at end of file From d5903fa95236f77a21f771933a9f009a62b604a4 Mon Sep 17 00:00:00 2001 From: Tdsbeast <63647097+dipesh88@users.noreply.github.com> Date: Sat, 1 Oct 2022 15:07:57 +0530 Subject: [PATCH 072/278] System Shut Down --- systemshutdown.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 systemshutdown.c diff --git a/systemshutdown.c b/systemshutdown.c new file mode 100644 index 0000000..b161dc3 --- /dev/null +++ b/systemshutdown.c @@ -0,0 +1,16 @@ +//don't run +#include +#include + +int main(int argc, char *argv[]) +{ + int i; + i = atoi(argv[1]); + printf("bye\n"); + sleep((i-1)*60); +// printf("world"); + + system("shutdown /s"); + + return 0; +} \ No newline at end of file From 837f852dc0462df3719d9fe45ca3acdd8e2160ac Mon Sep 17 00:00:00 2001 From: Aayush Barmecha <68626644+aayushbarmecha@users.noreply.github.com> Date: Sat, 1 Oct 2022 15:11:10 +0530 Subject: [PATCH 073/278] hactoberfest-2022 --- CPP/kadane.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 CPP/kadane.cpp diff --git a/CPP/kadane.cpp b/CPP/kadane.cpp new file mode 100644 index 0000000..45fa5bc --- /dev/null +++ b/CPP/kadane.cpp @@ -0,0 +1,30 @@ +// C++ program to print largest contiguous array sum +#include +#include +using namespace std; + +int maxSubArraySum(int a[], int size) +{ + int max_so_far = INT_MIN, max_ending_here = 0; + + for (int i = 0; i < size; i++) + { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; +} + +/*Driver program to test maxSubArraySum*/ +int main() +{ + int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; + int n = sizeof(a)/sizeof(a[0]); + int max_sum = maxSubArraySum(a, n); + cout << "Maximum contiguous sum is " << max_sum; + return 0; +} From 464cf7b6574e9274ab072abf4c132c9fa7edbc37 Mon Sep 17 00:00:00 2001 From: Asmit Kumar <114564653+Asmit-Kumar0@users.noreply.github.com> Date: Sat, 1 Oct 2022 15:15:11 +0530 Subject: [PATCH 074/278] hactoberfest-2022 --- binary_conversion.c | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 binary_conversion.c diff --git a/binary_conversion.c b/binary_conversion.c new file mode 100644 index 0000000..e661efa --- /dev/null +++ b/binary_conversion.c @@ -0,0 +1,24 @@ +#include +#include +#include + +void main() +{ + int n,i=0,z,j; + scanf("%d",&n); + int *a = (int*)malloc(sizeof(int)); + + while(n>0) + { + z=n%2; + a[i]=z; + i++; + n/=2; + } + i--; + while(i>=0) + { + printf("%d",a[i]); + i--; + } +} \ No newline at end of file From 0d104d83b35b761bef15a019826e6ab3b306ad18 Mon Sep 17 00:00:00 2001 From: Aayush Barmecha <68626644+aayushbarmecha@users.noreply.github.com> Date: Sat, 1 Oct 2022 15:15:12 +0530 Subject: [PATCH 075/278] karatsuba --- karatsuba.cpp | 90 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 karatsuba.cpp diff --git a/karatsuba.cpp b/karatsuba.cpp new file mode 100644 index 0000000..f738ee7 --- /dev/null +++ b/karatsuba.cpp @@ -0,0 +1,90 @@ +// C++ implementation of Karatsuba algorithm for bit string multiplication. +#include +#include + +using namespace std; + + +int makeEqualLength(string &str1, string &str2) +{ + int len1 = str1.size(); + int len2 = str2.size(); + if (len1 < len2) + { + for (int i = 0 ; i < len2 - len1 ; i++) + str1 = '0' + str1; + return len2; + } + else if (len1 > len2) + { + for (int i = 0 ; i < len1 - len2 ; i++) + str2 = '0' + str2; + } + return len1; // If len1 >= len2 +} + + +string addBitStrings( string first, string second ) +{ + string result; + + int length = makeEqualLength(first, second); + int carry = 0; + + for (int i = length-1 ; i >= 0 ; i--) + { + int firstBit = first.at(i) - '0'; + int secondBit = second.at(i) - '0'; + + int sum = (firstBit ^ secondBit ^ carry)+'0'; + + result = (char)sum + result; + + carry = (firstBit&secondBit) | (secondBit&carry) | (firstBit&carry); + } + + if (carry) result = '1' + result; + + return result; +} + +int multiplyiSingleBit(string a, string b) +{ return (a[0] - '0')*(b[0] - '0'); } + + +long int multiply(string X, string Y) +{ + + int n = makeEqualLength(X, Y); + + // Base cases + if (n == 0) return 0; + if (n == 1) return multiplyiSingleBit(X, Y); + + int fh = n/2; + int sh = (n-fh); + + + string Xl = X.substr(0, fh); + string Xr = X.substr(fh, sh); + + string Yl = Y.substr(0, fh); + string Yr = Y.substr(fh, sh); + + long int P1 = multiply(Xl, Yl); + long int P2 = multiply(Xr, Yr); + long int P3 = multiply(addBitStrings(Xl, Xr), addBitStrings(Yl, Yr)); + + return P1*(1<<(2*sh)) + (P3 - P1 - P2)*(1< Date: Sat, 1 Oct 2022 15:15:52 +0530 Subject: [PATCH 076/278] Delete karatsuba.cpp --- karatsuba.cpp | 90 --------------------------------------------------- 1 file changed, 90 deletions(-) delete mode 100644 karatsuba.cpp diff --git a/karatsuba.cpp b/karatsuba.cpp deleted file mode 100644 index f738ee7..0000000 --- a/karatsuba.cpp +++ /dev/null @@ -1,90 +0,0 @@ -// C++ implementation of Karatsuba algorithm for bit string multiplication. -#include -#include - -using namespace std; - - -int makeEqualLength(string &str1, string &str2) -{ - int len1 = str1.size(); - int len2 = str2.size(); - if (len1 < len2) - { - for (int i = 0 ; i < len2 - len1 ; i++) - str1 = '0' + str1; - return len2; - } - else if (len1 > len2) - { - for (int i = 0 ; i < len1 - len2 ; i++) - str2 = '0' + str2; - } - return len1; // If len1 >= len2 -} - - -string addBitStrings( string first, string second ) -{ - string result; - - int length = makeEqualLength(first, second); - int carry = 0; - - for (int i = length-1 ; i >= 0 ; i--) - { - int firstBit = first.at(i) - '0'; - int secondBit = second.at(i) - '0'; - - int sum = (firstBit ^ secondBit ^ carry)+'0'; - - result = (char)sum + result; - - carry = (firstBit&secondBit) | (secondBit&carry) | (firstBit&carry); - } - - if (carry) result = '1' + result; - - return result; -} - -int multiplyiSingleBit(string a, string b) -{ return (a[0] - '0')*(b[0] - '0'); } - - -long int multiply(string X, string Y) -{ - - int n = makeEqualLength(X, Y); - - // Base cases - if (n == 0) return 0; - if (n == 1) return multiplyiSingleBit(X, Y); - - int fh = n/2; - int sh = (n-fh); - - - string Xl = X.substr(0, fh); - string Xr = X.substr(fh, sh); - - string Yl = Y.substr(0, fh); - string Yr = Y.substr(fh, sh); - - long int P1 = multiply(Xl, Yl); - long int P2 = multiply(Xr, Yr); - long int P3 = multiply(addBitStrings(Xl, Xr), addBitStrings(Yl, Yr)); - - return P1*(1<<(2*sh)) + (P3 - P1 - P2)*(1< Date: Sat, 1 Oct 2022 15:16:03 +0530 Subject: [PATCH 077/278] Delete adjacency_matrix.cpp --- adjacency_matrix.cpp | 51 -------------------------------------------- 1 file changed, 51 deletions(-) delete mode 100644 adjacency_matrix.cpp diff --git a/adjacency_matrix.cpp b/adjacency_matrix.cpp deleted file mode 100644 index dc2ee38..0000000 --- a/adjacency_matrix.cpp +++ /dev/null @@ -1,51 +0,0 @@ -#include -using namespace std; -class Graph{ -private: -int numVertices; -bool** adjMatrix; - -public: -Graph(int numVertices){ - this->numVertices=numVertices; - adjMatrix = new bool*[numVertices]; - for (int i = 0; i < numVertices; i++) { - adjMatrix[i] = new bool[numVertices]; - for (int j = 0; j < numVertices; j++) - adjMatrix[i][j] = 0; -} -} - -void addEdge(int i,int j){ - adjMatrix[i][j]=1; - adjMatrix[j][i]=1; -} -void removeEdge(int i,int j){ - adjMatrix[i][j]=0; - adjMatrix[j][i]=0; -} -void toString(){ - cout<<" "; - for(int i=0;i Date: Sat, 1 Oct 2022 15:16:25 +0530 Subject: [PATCH 078/278] kruskal --- CPP/kruskal.cpp | 93 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 CPP/kruskal.cpp diff --git a/CPP/kruskal.cpp b/CPP/kruskal.cpp new file mode 100644 index 0000000..1672c32 --- /dev/null +++ b/CPP/kruskal.cpp @@ -0,0 +1,93 @@ +// Kruskal's algorithm in C++ + +#include +#include +#include +using namespace std; + +#define edge pair + +class Graph +{ +private: + vector > G; // graph + vector > T; // mst + int *parent; + int V; // number of vertices/nodes in graph +public: + Graph(int V){ + parent = new int[V]; + + // i 0 1 2 3 4 5 + // parent[i] 0 1 2 3 4 5 + for (int i = 0; i < V; i++) + parent[i] = i; + + G.clear(); + T.clear(); +} + void AddWeightedEdge(int u, int v, int w){ + G.push_back(make_pair(w, edge(u, v))); +} + int find_set(int i){ + // If i is the parent of itself + if (i == parent[i]) + return i; + else + return find_set(parent[i]); +} + void union_set(int u, int v){ + parent[u] = parent[v]; +} + void kruskal(){ + int i, uRep, vRep; + sort(G.begin(), G.end()); // increasing weight + for (i = 0; i < G.size(); i++) + { + uRep = find_set(G[i].second.first); + vRep = find_set(G[i].second.second); + if (uRep != vRep) + { + T.push_back(G[i]); // add to tree + union_set(uRep, vRep); + } + } +} + void print(){ + cout << "Edge :" + << " Weight" << endl; + for (int i = 0; i < T.size(); i++) + { + cout << T[i].second.first << " - " << T[i].second.second << " : " + << T[i].first; + cout << endl; + } +} +}; + + +int main() +{ + Graph g(6); + + g.AddWeightedEdge(0, 1, 4); + g.AddWeightedEdge(0, 2, 4); + g.AddWeightedEdge(1, 2, 2); + g.AddWeightedEdge(1, 0, 4); + g.AddWeightedEdge(2, 0, 4); + g.AddWeightedEdge(2, 1, 2); + g.AddWeightedEdge(2, 3, 3); + g.AddWeightedEdge(2, 5, 2); + g.AddWeightedEdge(2, 4, 4); + g.AddWeightedEdge(3, 2, 3); + g.AddWeightedEdge(3, 4, 3); + g.AddWeightedEdge(4, 2, 4); + g.AddWeightedEdge(4, 3, 3); + g.AddWeightedEdge(5, 2, 2); + g.AddWeightedEdge(5, 4, 3); + + g.kruskal(); + + g.print(); + return 0; +} \ No newline at end of file From f792b786be0e874b0ba2017b85ec4d35f68001e7 Mon Sep 17 00:00:00 2001 From: Aayush Barmecha <68626644+aayushbarmecha@users.noreply.github.com> Date: Sat, 1 Oct 2022 15:17:27 +0530 Subject: [PATCH 079/278] max_subarray --- CPP/max_subarrray.cpp | 69 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 CPP/max_subarrray.cpp diff --git a/CPP/max_subarrray.cpp b/CPP/max_subarrray.cpp new file mode 100644 index 0000000..492a355 --- /dev/null +++ b/CPP/max_subarrray.cpp @@ -0,0 +1,69 @@ +// A Divide and Conquer based program for maximum subarray +// sum problem +#include +#include + +// A utility function to find maximum of two integers +int max(int a, int b) { return (a > b) ? a : b; } + +// A utility function to find maximum of three integers +int max(int a, int b, int c) { return max(max(a, b), c); } + +// Find the maximum possible sum in arr[] auch that arr[m] +// is part of it +int maxCrossingSum(int arr[], int l, int m, int h) +{ + // Include elements on left of mid. + int sum = 0; + int left_sum = INT_MIN; + for (int i = m; i >= l; i--) { + sum = sum + arr[i]; + if (sum > left_sum) + left_sum = sum; + } + + // Include elements on right of mid + sum = 0; + int right_sum = INT_MIN; + for (int i = m + 1; i <= h; i++) { + sum = sum + arr[i]; + if (sum > right_sum) + right_sum = sum; + } + + // Return sum of elements on left and right of mid + // returning only left_sum + right_sum will fail for + // [-2, 1] + return max(left_sum + right_sum, left_sum, right_sum); +} + +// Returns sum of maximum sum subarray in aa[l..h] +int maxSubArraySum(int arr[], int l, int h) +{ + // Base Case: Only one element + if (l == h) + return arr[l]; + + // Find middle point + int m = (l + h) / 2; + + /* Return maximum of following three possible cases + a) Maximum subarray sum in left half + b) Maximum subarray sum in right half + c) Maximum subarray sum such that the subarray + crosses the midpoint */ + return max(maxSubArraySum(arr, l, m), + maxSubArraySum(arr, m + 1, h), + maxCrossingSum(arr, l, m, h)); +} + +/*Driver program to test maxSubArraySum*/ +int main() +{ + int arr[] = { 2, 3, 4, 5, 7 }; + int n = sizeof(arr) / sizeof(arr[0]); + int max_sum = maxSubArraySum(arr, 0, n - 1); + printf("Maximum contiguous sum is %d\n", max_sum); + getchar(); + return 0; +} From 2051a2e35d705e4bec602ab71b55c3de33923a1a Mon Sep 17 00:00:00 2001 From: Ashwin Taras <94214931+BlackBolt2003@users.noreply.github.com> Date: Sat, 1 Oct 2022 15:27:14 +0530 Subject: [PATCH 080/278] Create Quick_Sort.cpp I would like to add quick sort in c++ --- CPP/Quick_Sort.cpp | 83 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 CPP/Quick_Sort.cpp diff --git a/CPP/Quick_Sort.cpp b/CPP/Quick_Sort.cpp new file mode 100644 index 0000000..5e164a4 --- /dev/null +++ b/CPP/Quick_Sort.cpp @@ -0,0 +1,83 @@ +// Quick Sort + +# include +using namespace std; + + +// Function to swap elements of array +void swap(int arr[], int a, int b) +{ + int temp = arr[a]; + arr[a] = arr[b]; + arr[b] = temp; + return; +} + + +// Function to partition around pivot, i.e, separate smaller and greater numbers into two arrays +// and return correct index of pivot +int partition(int arr[], int l, int r) +{ + // select pivot element, here, last element of array + int pivot = arr[r]; + // i = points to last number in array less than pivot + int i = l-1; + + // traverse array from l'th to r-1'th element + for (int j=l; j> n; + + int arr[n]; + cout << "\nEnter numbers to be sorted : " << endl; + for (int i=0; i> arr[i]; + } + + // Perform Quick Sort + quick_sort(arr, 0, n-1); + + // Output Sorted array + cout << "\nSorted Numbers : " << endl; + for (int i=0; i Date: Sat, 1 Oct 2022 13:03:58 +0300 Subject: [PATCH 081/278] C# square root validator --- C#/SquareValidation.cs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C#/SquareValidation.cs diff --git a/C#/SquareValidation.cs b/C#/SquareValidation.cs new file mode 100644 index 0000000..929f369 --- /dev/null +++ b/C#/SquareValidation.cs @@ -0,0 +1,20 @@ +using System; + +namespace Validations +{ + public static class SquareValidation + { + /// + /// Checks if given number is square root of it self + /// + /// + /// + public static bool IsSquare(double value) + { + if (0 > value) => return false; + + var squareRoot = Math.Sqrt(value); + return (value == squareRoot * squareRoot); + } + } +} \ No newline at end of file From f5657b0bcfdd7dc86d9bff6ff4aa40c41474d05d Mon Sep 17 00:00:00 2001 From: JVisuri1 <34973409+JVisuri1@users.noreply.github.com> Date: Sat, 1 Oct 2022 13:35:19 +0300 Subject: [PATCH 082/278] C# radian conversion algorithm --- C#/RadianDegreeConverter.cs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C#/RadianDegreeConverter.cs diff --git a/C#/RadianDegreeConverter.cs b/C#/RadianDegreeConverter.cs new file mode 100644 index 0000000..3a638a8 --- /dev/null +++ b/C#/RadianDegreeConverter.cs @@ -0,0 +1,26 @@ +using System; + +namespace Conversions +{ + public static class RadianDegreeConverter + { + /// + /// Converts given degree to radian + /// + /// + /// + public static double DegreeToRadian(double degree) + { + return degree * (Math.PI / 180); + } + + /// + /// Converts given radian to degree + /// + /// + public static double RadianToDegree(double radian) + { + return radian * (180 / Math.PI); + } + } +} \ No newline at end of file From ad33c452031b43f78c64279462fe3234173af09c Mon Sep 17 00:00:00 2001 From: Parth Shingala <81471165+Parth013@users.noreply.github.com> Date: Sat, 1 Oct 2022 16:08:22 +0530 Subject: [PATCH 083/278] Circular Queue In java --- CQueue.java | 110 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 CQueue.java diff --git a/CQueue.java b/CQueue.java new file mode 100644 index 0000000..800cdca --- /dev/null +++ b/CQueue.java @@ -0,0 +1,110 @@ +public class CQueue { + int SIZE = 5; // Size of Circular Queue + int front, rear; + int items[] = new int[SIZE]; + + CQueue() { + front = -1; + rear = -1; + } + + // Check if the queue is full + boolean isFull() { + if (front == 0 && rear == SIZE - 1) { + return true; + } + if (front == rear + 1) { + return true; + } + return false; + } + + // Check if the queue is empty + boolean isEmpty() { + if (front == -1) + return true; + else + return false; + } + + // Adding an element + void enQueue(int element) { + if (isFull()) { + System.out.println("Queue is full"); + } else { + if (front == -1) + front = 0; + rear = (rear + 1) % SIZE; + items[rear] = element; + System.out.println("Inserted " + element); + } + } + + // Removing an element + int deQueue() { + int element; + if (isEmpty()) { + System.out.println("Queue is empty"); + return (-1); + } else { + element = items[front]; + if (front == rear) { + front = -1; + rear = -1; + } /* Q has only one element, so we reset the queue after deleting it. */ + else { + front = (front + 1) % SIZE; + } + return (element); + } + } + + void display() { + /* Function to display status of Circular Queue */ + int i; + if (isEmpty()) { + System.out.println("Empty Queue"); + } else { + System.out.println("Front -> " + front); + System.out.println("Items -> "); + for (i = front; i != rear; i = (i + 1) % SIZE) + System.out.print(items[i] + " "); + System.out.println(items[i]); + System.out.println("Rear -> " + rear); + } + } + + public static void main(String[] args) { + + CQueue q = new CQueue(); + + // Fails because front = -1 + q.deQueue(); + + q.enQueue(1); + q.enQueue(2); + q.enQueue(3); + q.enQueue(4); + q.enQueue(5); + + // Fails to enqueue because front == 0 && rear == SIZE - 1 + q.enQueue(6); + + q.display(); + + int elem = q.deQueue(); + + if (elem != -1) { + System.out.println("Deleted Element is " + elem); + } + q.display(); + + q.enQueue(7); + + q.display(); + + // Fails to enqueue because front == rear + 1 + q.enQueue(8); + } + +} From 69d57cd1ad827fafaef6619921561d5ffd9a3ebc Mon Sep 17 00:00:00 2001 From: JVisuri1 <34973409+JVisuri1@users.noreply.github.com> Date: Sat, 1 Oct 2022 13:39:44 +0300 Subject: [PATCH 084/278] Remove dublicate file --- C#/SquareValidation.cs | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 C#/SquareValidation.cs diff --git a/C#/SquareValidation.cs b/C#/SquareValidation.cs deleted file mode 100644 index 929f369..0000000 --- a/C#/SquareValidation.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace Validations -{ - public static class SquareValidation - { - /// - /// Checks if given number is square root of it self - /// - /// - /// - public static bool IsSquare(double value) - { - if (0 > value) => return false; - - var squareRoot = Math.Sqrt(value); - return (value == squareRoot * squareRoot); - } - } -} \ No newline at end of file From c05f94a28440abae0377a33abdcb8567b58a5718 Mon Sep 17 00:00:00 2001 From: Samyak2000 <56105502+Samyak2000@users.noreply.github.com> Date: Sat, 1 Oct 2022 16:21:44 +0530 Subject: [PATCH 085/278] Create dataManipulation.java --- dataManipulation.java | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 dataManipulation.java diff --git a/dataManipulation.java b/dataManipulation.java new file mode 100644 index 0000000..efb481a --- /dev/null +++ b/dataManipulation.java @@ -0,0 +1,34 @@ +import java.util.Collections; +import java.util.ArrayList; + +class Main { + public static void main(String[] args) { + // Creating an ArrayList + ArrayList numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + System.out.println("ArrayList1: " + numbers); + + // Using reverse() + Collections.reverse(numbers); + System.out.println("Reversed ArrayList1: " + numbers); + + // Using swap() + Collections.swap(numbers, 0, 1); + System.out.println("ArrayList1 using swap(): " + numbers); + + ArrayList newNumbers = new ArrayList<>(); + + // Using addAll + newNumbers.addAll(numbers); + System.out.println("ArrayList2 using addAll(): " + newNumbers); + + // Using fill() + Collections.fill(numbers, 0); + System.out.println("ArrayList1 using fill(): " + numbers); + + // Using copy() + Collections.copy(newNumbers, numbers); + System.out.println("ArrayList2 using copy(): " + newNumbers); + } +} From 7c70aeb261da122f3294ac2833872c313c4de227 Mon Sep 17 00:00:00 2001 From: VarunBhattacharya <76221455+VarunBhattacharya@users.noreply.github.com> Date: Sat, 1 Oct 2022 16:32:55 +0530 Subject: [PATCH 086/278] Singly Linked List Operations on singly linked list with detailed explanation --- Python/1_Singly_Linked_List.py | 98 ++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Python/1_Singly_Linked_List.py diff --git a/Python/1_Singly_Linked_List.py b/Python/1_Singly_Linked_List.py new file mode 100644 index 0000000..7453d11 --- /dev/null +++ b/Python/1_Singly_Linked_List.py @@ -0,0 +1,98 @@ +#Node Datatype creation +from os import remove + + +class Node: + def __init__(self,data): #Initialization + self.data = data #assigning data + self.next = None #assigning the next pointer to be null + +class SingleLinkedList: + def __init__(self): + self.head = None #assigning the head to be null + + def insertion_at_beg(self, newNode): + if self.head: #if head pointer is not empty + temp = self.head + self.head = newNode + self.head.next = temp + else: #if head pointer is empty + self.head = newNode + + def insertion_at_end(self,newNode): + if self.head: #if head pointer is not empty + temp = self.head #copy the head pointer + while temp.next != None: #traverse through the list till the end + temp = temp.next + temp.next = newNode #assign the new node in the last + newNode.next = None #make the next pointer to be null + else: #if head pointer is empty + self.head = newNode #assign the node as the head node + + def deletion_at_beg(self): + if self.head: + self.head = self.head.next + else: + print("No elements are present") + + def deletion_at_end(self): + if self.head: #if head pointer is not empty + if self.head.next == None: + self.head = None + else: + temp = self.head + while temp.next.next != None: + temp = temp.next + temp.next = None + else: + print("No elements are present") + + def reverse(self): + if self.head: #if head pointer is not empty + previous = self.head + current = self.head.next + self.head = self.head.next + + previous.next = None + while self.head != None: + self.head = self.head.next + current.next = previous + previous = current + current = self.head + + self.head = previous + + print("List Reversed") + else: #if head pointer is empty + print("List Empty") + + def display(self): + ptr = self.head + if ptr == None: #when the head is empty + print("No Elements Present") + else: #print the values present + print("The Values are: ") + while ptr != None: #traverse till end of the list + print(ptr.data, end = "->") + ptr = ptr.next + print("Null") + +if __name__ == "__main__": + listObject = SingleLinkedList() + listObject.insertion_at_end(Node(1)) + listObject.insertion_at_end(Node(2)) + listObject.insertion_at_end(Node(3)) + listObject.insertion_at_end(Node(4)) + listObject.insertion_at_end(Node(5)) + listObject.insertion_at_end(Node(6)) + listObject.insertion_at_end(Node(7)) + listObject.display() + listObject.reverse() + listObject.display() + listObject.deletion_at_beg() + listObject.display() + listObject.insertion_at_beg(Node(8)) + listObject.insertion_at_beg(Node(10)) + listObject.display() + listObject.deletion_at_end() + listObject.display() \ No newline at end of file From d15292afab35ed3b1d0527b557934e3b6393c7b4 Mon Sep 17 00:00:00 2001 From: prakhar-da-gama <95561933+prakhar-da-gama@users.noreply.github.com> Date: Sat, 1 Oct 2022 16:44:21 +0530 Subject: [PATCH 087/278] Create Kadane.cpp --- CPP/Kadane.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 CPP/Kadane.cpp diff --git a/CPP/Kadane.cpp b/CPP/Kadane.cpp new file mode 100644 index 0000000..1da78fd --- /dev/null +++ b/CPP/Kadane.cpp @@ -0,0 +1,30 @@ +// C++ program to print largest contiguous array sum +#include +using namespace std; + +int maxSubArraySum(int a[], int size) +{ + int max_so_far = INT_MIN, max_ending_here = 0; + + for (int i = 0; i < size; i++) { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; +} + +// Driver Code +int main() +{ + int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; + int n = sizeof(a) / sizeof(a[0]); + + // Function Call + int max_sum = maxSubArraySum(a, n); + cout << "Maximum contiguous sum is " << max_sum; + return 0; +} From cca22cd9ba2032483cc6afd5a820b15c9e71aa64 Mon Sep 17 00:00:00 2001 From: Yash-Agarwal1708 <103818600+Yash-Agarwal1708@users.noreply.github.com> Date: Sat, 1 Oct 2022 16:50:23 +0530 Subject: [PATCH 088/278] Fibonacci series --- Python/fibonacci.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Python/fibonacci.py diff --git a/Python/fibonacci.py b/Python/fibonacci.py new file mode 100644 index 0000000..e63c049 --- /dev/null +++ b/Python/fibonacci.py @@ -0,0 +1,15 @@ +def fibonacci(n): + l=[] + for i in range(n): + if(i==0): + l.append(0) + elif(i==1): + l.append(1) + else: + l.append(l[i-1]+l[i-2]) + return l + # return a list of fibonacci numbers + +if __name__ == '__main__': + n = int(input())#number of terms + print(fibonacci(n)) \ No newline at end of file From 97b07926bda2cb6cd648563d73e528acc1d9c128 Mon Sep 17 00:00:00 2001 From: Arie <91861324+ariear@users.noreply.github.com> Date: Sat, 1 Oct 2022 18:30:18 +0700 Subject: [PATCH 089/278] add : binary search js --- Javascript/binarySearch.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Javascript/binarySearch.js diff --git a/Javascript/binarySearch.js b/Javascript/binarySearch.js new file mode 100644 index 0000000..b0c3a4f --- /dev/null +++ b/Javascript/binarySearch.js @@ -0,0 +1,28 @@ +let iterativeFunction = function (arr, x) { + + let start = 0 + let end = arr.length-1 + + while (start<=end){ + + let mid = Math.floor((start + end)/2); + + if (arr[mid]===x) return true; + + else if (arr[mid] < x) + start = mid + 1; + else + end = mid - 1; + } + + return false; +} + +let arr = [1, 3, 5, 7, 8, 9]; +let x = 5; + +if (iterativeFunction(arr, x)) + console.log('Element found!') +else { + console.log('Element not found!') +} From b8ee51ac32c0f1d1094386f43f3bda616afa6ebf Mon Sep 17 00:00:00 2001 From: Suraj Singh <103835667+suraj-s13@users.noreply.github.com> Date: Sat, 1 Oct 2022 17:43:51 +0530 Subject: [PATCH 090/278] readme --- CPP/Single-Linked-List/readme | 1 + 1 file changed, 1 insertion(+) create mode 100644 CPP/Single-Linked-List/readme diff --git a/CPP/Single-Linked-List/readme b/CPP/Single-Linked-List/readme new file mode 100644 index 0000000..451b0d4 --- /dev/null +++ b/CPP/Single-Linked-List/readme @@ -0,0 +1 @@ +**Single Linked List** From 192e04261ee7084fd8bbaa5238f21c7eb03ef06e Mon Sep 17 00:00:00 2001 From: Suraj Singh <103835667+suraj-s13@users.noreply.github.com> Date: Sat, 1 Oct 2022 17:44:21 +0530 Subject: [PATCH 091/278] Rename readme to readme.md --- CPP/Single-Linked-List/{readme => readme.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename CPP/Single-Linked-List/{readme => readme.md} (100%) diff --git a/CPP/Single-Linked-List/readme b/CPP/Single-Linked-List/readme.md similarity index 100% rename from CPP/Single-Linked-List/readme rename to CPP/Single-Linked-List/readme.md From 94f84a58cadcfb58b8c70bdbc25e15d1f8a86157 Mon Sep 17 00:00:00 2001 From: Suraj Singh <103835667+suraj-s13@users.noreply.github.com> Date: Sat, 1 Oct 2022 17:54:09 +0530 Subject: [PATCH 092/278] Update readme.md --- CPP/Single-Linked-List/readme.md | 35 ++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/CPP/Single-Linked-List/readme.md b/CPP/Single-Linked-List/readme.md index 451b0d4..ea642a4 100644 --- a/CPP/Single-Linked-List/readme.md +++ b/CPP/Single-Linked-List/readme.md @@ -1 +1,36 @@ **Single Linked List** + + +**Single linked list is a sequence of elements in which every element has link to its next element in the sequence.** + +In any single linked list, the individual element is called as "Node". Every "Node" contains two fields, data field, and the next field. The data field is used to store actual value of the node and next field is used to store the address of next node in the sequence. + +The graphical representation of a node in a single linked list is as follows... + +![alt text](http://www.btechsmartclass.com/data_structures/ds_images/Linked_List_Node.png) + +**Example** + +![alt text](http://www.btechsmartclass.com/data_structures/ds_images/Linked_List_Example.png) + +**Operations on Single Linked List** + +The following operations are performed on a Single Linked List + +**1.Insertion** + +**2.Deletion** + +**3.Display** + +Before we implement actual operations, first we need to set up an empty list. First, perform the following steps before implementing actual operations. + +Step 1 - Include all the header files which are used in the program. + +Step 2 - Declare all the user defined functions. + +Step 3 - Define a Node structure with two members data and next + +Step 4 - Define a Node pointer 'head' and set it to NULL. + +Step 5 - Implement the main method by displaying operations menu and make suitable function calls in the main method to perform user selected operation. From bef01b0f719d6178975511e96e3eeb074c563b58 Mon Sep 17 00:00:00 2001 From: Sahil Rana <51770809+Rsr0@users.noreply.github.com> Date: Sat, 1 Oct 2022 17:54:29 +0530 Subject: [PATCH 093/278] Create linkedListCycle.cpp --- CPP/linkedListCycle.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 CPP/linkedListCycle.cpp diff --git a/CPP/linkedListCycle.cpp b/CPP/linkedListCycle.cpp new file mode 100644 index 0000000..01ce102 --- /dev/null +++ b/CPP/linkedListCycle.cpp @@ -0,0 +1,23 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool hasCycle(ListNode *head) { + if(!head || !head->next) return 0; + ListNode* fast=head, *slow=head; + while(fast && fast->next){ + fast=fast->next->next; + slow=slow->next; + + if(fast==slow) + return 1; + } + return 0; + } +}; From e6926d495a631f62cf6884f852c8df718360dbb2 Mon Sep 17 00:00:00 2001 From: Suraj Singh <103835667+suraj-s13@users.noreply.github.com> Date: Sat, 1 Oct 2022 17:55:21 +0530 Subject: [PATCH 094/278] CODE --- CPP/Single-Linked-List/singlelinkedlist.c | 207 ++++++++++++++++++++++ 1 file changed, 207 insertions(+) create mode 100644 CPP/Single-Linked-List/singlelinkedlist.c diff --git a/CPP/Single-Linked-List/singlelinkedlist.c b/CPP/Single-Linked-List/singlelinkedlist.c new file mode 100644 index 0000000..bf787e9 --- /dev/null +++ b/CPP/Single-Linked-List/singlelinkedlist.c @@ -0,0 +1,207 @@ +#include +#include +#include + +void insertAtBeginning(int); +void insertAtEnd(int); +void insertBetween(int,int,int); +void display(); +void removeBeginning(); +void removeEnd(); +void removeSpecific(int); + +struct Node +{ + int data; + struct Node *next; +}*head = NULL; + +void main() +{ + int choice,value,choice1,loc1,loc2; + clrscr(); + while(1){ + mainMenu: printf("\n\n****** MENU ******\n1. Insert\n2. Display\n3. Delete\n4. Exit\nEnter your choice: "); + scanf("%d",&choice); + switch(choice) + { + case 1: printf("Enter the value to be insert: "); + scanf("%d",&value); + while(1){ + printf("Where you want to insert: \n1. At Beginning\n2. At End\n3. Between\nEnter your choice: "); + scanf("%d",&choice1); + switch(choice1) + { + case 1: insertAtBeginning(value); + break; + case 2: insertAtEnd(value); + break; + case 3: printf("Enter the two values where you wanto insert: "); + scanf("%d%d",&loc1,&loc2); + insertBetween(value,loc1,loc2); + break; + default: printf("\nWrong Input!! Try again!!!\n\n"); + goto mainMenu; + } + goto subMenuEnd; + } + subMenuEnd: + break; + case 2: display(); + break; + case 3: printf("How do you want to Delete: \n1. From Beginning\n2. From End\n3. Spesific\nEnter your choice: "); + scanf("%d",&choice1); + switch(choice1) + { + case 1: removeBeginning(); + break; + case 2: removeEnd(); + break; + case 3: printf("Enter the value which you wanto delete: "); + scanf("%d",&loc2); + removeSpecific(loc2); + break; + default: printf("\nWrong Input!! Try again!!!\n\n"); + goto mainMenu; + } + break; + case 4: exit(0); + default: printf("\nWrong input!!! Try again!!\n\n"); + } + } +} + +void insertAtBeginning(int value) +{ + struct Node *newNode; + newNode = (struct Node*)malloc(sizeof(struct Node)); + newNode->data = value; + if(head == NULL) + { + newNode->next = NULL; + head = newNode; + } + else + { + newNode->next = head; + head = newNode; + } + printf("\nOne node inserted!!!\n"); +} +void insertAtEnd(int value) +{ + struct Node *newNode; + newNode = (struct Node*)malloc(sizeof(struct Node)); + newNode->data = value; + newNode->next = NULL; + if(head == NULL) + head = newNode; + else + { + struct Node *temp = head; + while(temp->next != NULL) + temp = temp->next; + temp->next = newNode; + } + printf("\nOne node inserted!!!\n"); +} +void insertBetween(int value, int loc1, int loc2) +{ + struct Node *newNode; + newNode = (struct Node*)malloc(sizeof(struct Node)); + newNode->data = value; + if(head == NULL) + { + newNode->next = NULL; + head = newNode; + } + else + { + struct Node *temp = head; + while(temp->data != loc1 && temp->data != loc2) + temp = temp->next; + newNode->next = temp->next; + temp->next = newNode; + } + printf("\nOne node inserted!!!\n"); +} + +void removeBeginning() +{ + if(head == NULL) + printf("\n\nList is Empty!!!"); + else + { + struct Node *temp = head; + if(head->next == NULL) + { + head = NULL; + free(temp); + } + else + { + head = temp->next; + free(temp); + printf("\nOne node deleted!!!\n\n"); + } + } +} +void removeEnd() +{ + if(head == NULL) + { + printf("\nList is Empty!!!\n"); + } + else + { + struct Node *temp1 = head,*temp2; + if(head->next == NULL) + head = NULL; + else + { + while(temp1->next != NULL) + { + temp2 = temp1; + temp1 = temp1->next; + } + temp2->next = NULL; + } + free(temp1); + printf("\nOne node deleted!!!\n\n"); + } +} +void removeSpecific(int delValue) +{ + struct Node *temp1 = head, *temp2; + while(temp1->data != delValue) + { + if(temp1 -> next == NULL){ + printf("\nGiven node not found in the list!!!"); + goto functionEnd; + } + temp2 = temp1; + temp1 = temp1 -> next; + } + temp2 -> next = temp1 -> next; + free(temp1); + printf("\nOne node deleted!!!\n\n"); + functionEnd: +} +void display() +{ + if(head == NULL) + { + printf("\nList is Empty\n"); + } + else + { + struct Node *temp = head; + printf("\n\nList elements are - \n"); + while(temp->next != NULL) + { + printf("%d --->",temp->data); + temp = temp->next; + } + printf("%d --->NULL",temp->data); + } +} From 5f970c2d6e48ce536dfa492bf830efac6e7ad1b5 Mon Sep 17 00:00:00 2001 From: Suraj Singh <103835667+suraj-s13@users.noreply.github.com> Date: Sat, 1 Oct 2022 17:58:50 +0530 Subject: [PATCH 095/278] Update and rename singlelinkedlist.c to singlelinkedlist.cpp --- CPP/Single-Linked-List/singlelinkedlist.c | 207 -------------------- CPP/Single-Linked-List/singlelinkedlist.cpp | 174 ++++++++++++++++ 2 files changed, 174 insertions(+), 207 deletions(-) delete mode 100644 CPP/Single-Linked-List/singlelinkedlist.c create mode 100644 CPP/Single-Linked-List/singlelinkedlist.cpp diff --git a/CPP/Single-Linked-List/singlelinkedlist.c b/CPP/Single-Linked-List/singlelinkedlist.c deleted file mode 100644 index bf787e9..0000000 --- a/CPP/Single-Linked-List/singlelinkedlist.c +++ /dev/null @@ -1,207 +0,0 @@ -#include -#include -#include - -void insertAtBeginning(int); -void insertAtEnd(int); -void insertBetween(int,int,int); -void display(); -void removeBeginning(); -void removeEnd(); -void removeSpecific(int); - -struct Node -{ - int data; - struct Node *next; -}*head = NULL; - -void main() -{ - int choice,value,choice1,loc1,loc2; - clrscr(); - while(1){ - mainMenu: printf("\n\n****** MENU ******\n1. Insert\n2. Display\n3. Delete\n4. Exit\nEnter your choice: "); - scanf("%d",&choice); - switch(choice) - { - case 1: printf("Enter the value to be insert: "); - scanf("%d",&value); - while(1){ - printf("Where you want to insert: \n1. At Beginning\n2. At End\n3. Between\nEnter your choice: "); - scanf("%d",&choice1); - switch(choice1) - { - case 1: insertAtBeginning(value); - break; - case 2: insertAtEnd(value); - break; - case 3: printf("Enter the two values where you wanto insert: "); - scanf("%d%d",&loc1,&loc2); - insertBetween(value,loc1,loc2); - break; - default: printf("\nWrong Input!! Try again!!!\n\n"); - goto mainMenu; - } - goto subMenuEnd; - } - subMenuEnd: - break; - case 2: display(); - break; - case 3: printf("How do you want to Delete: \n1. From Beginning\n2. From End\n3. Spesific\nEnter your choice: "); - scanf("%d",&choice1); - switch(choice1) - { - case 1: removeBeginning(); - break; - case 2: removeEnd(); - break; - case 3: printf("Enter the value which you wanto delete: "); - scanf("%d",&loc2); - removeSpecific(loc2); - break; - default: printf("\nWrong Input!! Try again!!!\n\n"); - goto mainMenu; - } - break; - case 4: exit(0); - default: printf("\nWrong input!!! Try again!!\n\n"); - } - } -} - -void insertAtBeginning(int value) -{ - struct Node *newNode; - newNode = (struct Node*)malloc(sizeof(struct Node)); - newNode->data = value; - if(head == NULL) - { - newNode->next = NULL; - head = newNode; - } - else - { - newNode->next = head; - head = newNode; - } - printf("\nOne node inserted!!!\n"); -} -void insertAtEnd(int value) -{ - struct Node *newNode; - newNode = (struct Node*)malloc(sizeof(struct Node)); - newNode->data = value; - newNode->next = NULL; - if(head == NULL) - head = newNode; - else - { - struct Node *temp = head; - while(temp->next != NULL) - temp = temp->next; - temp->next = newNode; - } - printf("\nOne node inserted!!!\n"); -} -void insertBetween(int value, int loc1, int loc2) -{ - struct Node *newNode; - newNode = (struct Node*)malloc(sizeof(struct Node)); - newNode->data = value; - if(head == NULL) - { - newNode->next = NULL; - head = newNode; - } - else - { - struct Node *temp = head; - while(temp->data != loc1 && temp->data != loc2) - temp = temp->next; - newNode->next = temp->next; - temp->next = newNode; - } - printf("\nOne node inserted!!!\n"); -} - -void removeBeginning() -{ - if(head == NULL) - printf("\n\nList is Empty!!!"); - else - { - struct Node *temp = head; - if(head->next == NULL) - { - head = NULL; - free(temp); - } - else - { - head = temp->next; - free(temp); - printf("\nOne node deleted!!!\n\n"); - } - } -} -void removeEnd() -{ - if(head == NULL) - { - printf("\nList is Empty!!!\n"); - } - else - { - struct Node *temp1 = head,*temp2; - if(head->next == NULL) - head = NULL; - else - { - while(temp1->next != NULL) - { - temp2 = temp1; - temp1 = temp1->next; - } - temp2->next = NULL; - } - free(temp1); - printf("\nOne node deleted!!!\n\n"); - } -} -void removeSpecific(int delValue) -{ - struct Node *temp1 = head, *temp2; - while(temp1->data != delValue) - { - if(temp1 -> next == NULL){ - printf("\nGiven node not found in the list!!!"); - goto functionEnd; - } - temp2 = temp1; - temp1 = temp1 -> next; - } - temp2 -> next = temp1 -> next; - free(temp1); - printf("\nOne node deleted!!!\n\n"); - functionEnd: -} -void display() -{ - if(head == NULL) - { - printf("\nList is Empty\n"); - } - else - { - struct Node *temp = head; - printf("\n\nList elements are - \n"); - while(temp->next != NULL) - { - printf("%d --->",temp->data); - temp = temp->next; - } - printf("%d --->NULL",temp->data); - } -} diff --git a/CPP/Single-Linked-List/singlelinkedlist.cpp b/CPP/Single-Linked-List/singlelinkedlist.cpp new file mode 100644 index 0000000..739d1a4 --- /dev/null +++ b/CPP/Single-Linked-List/singlelinkedlist.cpp @@ -0,0 +1,174 @@ +#include +using namespace std; + +// Node class to represent +// a node of the linked list. +class Node { +public: + int data; + Node* next; + + // Default constructor + Node() + { + data = 0; + next = NULL; + } + + // Parameterised Constructor + Node(int data) + { + this->data = data; + this->next = NULL; + } +}; + +// Linked list class to +// implement a linked list. +class Linkedlist { + Node* head; + +public: + // Default constructor + Linkedlist() { head = NULL; } + + // Function to insert a + // node at the end of the + // linked list. + void insertNode(int); + + // Function to print the + // linked list. + void printList(); + + // Function to delete the + // node at given position + void deleteNode(int); +}; + +// Function to delete the +// node at given position +void Linkedlist::deleteNode(int nodeOffset) +{ + Node *temp1 = head, *temp2 = NULL; + int ListLen = 0; + + if (head == NULL) { + cout << "List empty." << endl; + return; + } + + // Find length of the linked-list. + while (temp1 != NULL) { + temp1 = temp1->next; + ListLen++; + } + + // Check if the position to be + // deleted is less than the length + // of the linked list. + if (ListLen < nodeOffset) { + cout << "Index out of range" + << endl; + return; + } + + // Declare temp1 + temp1 = head; + + // Deleting the head. + if (nodeOffset == 1) { + + // Update head + head = head->next; + delete temp1; + return; + } + + // Traverse the list to + // find the node to be deleted. + while (nodeOffset-- > 1) { + + // Update temp2 + temp2 = temp1; + + // Update temp1 + temp1 = temp1->next; + } + + // Change the next pointer + // of the previous node. + temp2->next = temp1->next; + + // Delete the node + delete temp1; +} + +// Function to insert a new node. +void Linkedlist::insertNode(int data) +{ + // Create the new Node. + Node* newNode = new Node(data); + + // Assign to head + if (head == NULL) { + head = newNode; + return; + } + + // Traverse till end of list + Node* temp = head; + while (temp->next != NULL) { + + // Update temp + temp = temp->next; + } + + // Insert at the last. + temp->next = newNode; +} + +// Function to print the +// nodes of the linked list. +void Linkedlist::printList() +{ + Node* temp = head; + + // Check for empty list. + if (head == NULL) { + cout << "List empty" << endl; + return; + } + + // Traverse the list. + while (temp != NULL) { + cout << temp->data << " "; + temp = temp->next; + } +} + +// Driver Code +int main() +{ + Linkedlist list; + + // Inserting nodes + list.insertNode(1); + list.insertNode(2); + list.insertNode(3); + list.insertNode(4); + + cout << "Elements of the list are: "; + + // Print the list + list.printList(); + cout << endl; + + // Delete node at position 2. + list.deleteNode(2); + + cout << "Elements of the list are: "; + list.printList(); + cout << endl; + return 0; +} From 7b6186bb7eb2058946d84d55061b16e33073395e Mon Sep 17 00:00:00 2001 From: Suraj Singh <103835667+suraj-s13@users.noreply.github.com> Date: Sat, 1 Oct 2022 18:01:08 +0530 Subject: [PATCH 096/278] Update readme.md --- CPP/Single-Linked-List/readme.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CPP/Single-Linked-List/readme.md b/CPP/Single-Linked-List/readme.md index ea642a4..ce95b8f 100644 --- a/CPP/Single-Linked-List/readme.md +++ b/CPP/Single-Linked-List/readme.md @@ -34,3 +34,9 @@ Step 3 - Define a Node structure with two members data and next Step 4 - Define a Node pointer 'head' and set it to NULL. Step 5 - Implement the main method by displaying operations menu and make suitable function calls in the main method to perform user selected operation. + +**Output** + + +![image](https://user-images.githubusercontent.com/103835667/193409700-2bb264c0-022a-4fe3-8acc-99853bc4ade9.png) + From 9595105246feecd87e9b08ab70596b3bdc7d22dc Mon Sep 17 00:00:00 2001 From: Himanshu Gupta <59887776+Himanshu-Gupta2001@users.noreply.github.com> Date: Sat, 1 Oct 2022 18:06:29 +0530 Subject: [PATCH 097/278] ReverseOfArray --- ReverseOfArray.java | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 ReverseOfArray.java diff --git a/ReverseOfArray.java b/ReverseOfArray.java new file mode 100644 index 0000000..9430ecf --- /dev/null +++ b/ReverseOfArray.java @@ -0,0 +1,38 @@ +public class GFG { + + static void rvereseArray(int arr[], + int start, int end) + { + int temp; + + while (start < end) + { + temp = arr[start]; + arr[start] = arr[end]; + arr[end] = temp; + start++; + end--; + } + } + + static void printArray(int arr[], + int size) + { + for (int i = 0; i < size; i++) + System.out.print(arr[i] + " "); + + System.out.println(); + } + + + public static void main(String args[]) { + + int arr[] = {1, 2, 3, 4, 5, 6}; + printArray(arr, 6); + rvereseArray(arr, 0, 5); + System.out.print("Reversed array is \n"); + printArray(arr, 6); + + } +} + From 15acc863538f55c1d20817d48f0d5189736f6716 Mon Sep 17 00:00:00 2001 From: yusmnn <76932249+yusmnn@users.noreply.github.com> Date: Sat, 1 Oct 2022 20:43:43 +0800 Subject: [PATCH 098/278] Add files via upload --- doubleLinkedList.cpp | 136 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 doubleLinkedList.cpp diff --git a/doubleLinkedList.cpp b/doubleLinkedList.cpp new file mode 100644 index 0000000..4d890a9 --- /dev/null +++ b/doubleLinkedList.cpp @@ -0,0 +1,136 @@ +#include +using namespace std; + +template +struct DoubleLinkedList{ + struct Node{ + T data; + Node *next; + Node *prev; + }; + + Node *n=NULL, *head=NULL, *tail=NULL, *x=NULL; + + void addNewNode(T i){ + n = new Node; + n->data = i; + n->prev = NULL; + head = n; + tail = n; + tail->next = NULL; + } + + void addNodeLast(T i){ + n = new Node; + n->data = i; + n->prev = tail; + tail->next = n; + tail = n; + tail->next = NULL; + } + + void addNodeFront(T i){ + n = new Node; + n->data = i; + n->next = head; + head->prev = n; + n->prev = NULL; + head = n; + } + + void addNodeMiddle(T i, T j){ + x = head; + while(x->data != j) x = x->next; + n = new Node; + n->data = i; + n->next = x->next; + x->next = n; + n->prev = x; + x = n->next; + x->prev = n; + } + + void addData(T i){ + if(head == NULL) + addNewNode(i); + else + addNodeLast(i); + } + + void readDataFront(){ + x = head; + while(x!=NULL){ + cout << x->data << " "; + x = x->next; + } + } + + void readDataLast(){ + x = tail; + while(x!=NULL){ + cout << x->data << " "; + x = x->prev; + } + } + + void deleteDataFront(){ + x = head; + head = head->next; + delete(x); + x = NULL; + head->prev = NULL; + } + + void deleteDataMiddle(T i){ + Node *temp = NULL; + x = head; + while(x->data != i){ + temp = x; + x = x->next; + } + temp->next = x->next; + temp = x->next; + temp->prev = x->prev; + delete(x); + x = NULL; + } + + void deleteDataLast(){ + x = tail; + tail = tail->prev; + delete(x); + x = NULL; + tail->next = NULL; + } + + + bool searchData(T i){ + x = head; + while(x!=NULL){ + if (i == x->data) return true; + x = x->next; + } + return false; + } + + void DeleteData(T i){ + if(!cariData(i)) return; + + if (i == head->data) + deleteDataFront(); + else if (i == tail->data) + deleteDataLast(); + else + deleteDataMiddle(i); + } +}; +int main(){ + DoubleLinkedList list; + list.addData("Hasan"); + list.addData("budi"); + list.addData("Taufiq"); + list.addData("Andi"); + list.readDataFront(); + cout << endl; + list.readDataLast(); +} From 090dfa5de9c16fc5895c6f33e994e1eabd8f2af4 Mon Sep 17 00:00:00 2001 From: Mansi <60071257+mansi0703@users.noreply.github.com> Date: Sat, 1 Oct 2022 18:33:11 +0530 Subject: [PATCH 099/278] Create wildcardmatching.cpp --- CPP/wildcardmatching.cpp | 86 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 CPP/wildcardmatching.cpp diff --git a/CPP/wildcardmatching.cpp b/CPP/wildcardmatching.cpp new file mode 100644 index 0000000..fea93de --- /dev/null +++ b/CPP/wildcardmatching.cpp @@ -0,0 +1,86 @@ +// C++ program to implement wildcard +// pattern matching algorithm +#include +using namespace std; + +// Function that matches input str with +// given wildcard pattern +bool strmatch(char str[], char pattern[], int n, int m) +{ + // empty pattern can only match with + // empty string + if (m == 0) + return (n == 0); + + // lookup table for storing results of + // subproblems + bool lookup[n + 1][m + 1]; + + // initialize lookup table to false + memset(lookup, false, sizeof(lookup)); + + // empty pattern can match with empty string + lookup[0][0] = true; + + // Only '*' can match with empty string + for (int j = 1; j <= m; j++) + if (pattern[j - 1] == '*') + lookup[0][j] = lookup[0][j - 1]; + + // fill the table in bottom-up fashion + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + // Two cases if we see a '*' + // a) We ignore ‘*’ character and move + // to next character in the pattern, + // i.e., ‘*’ indicates an empty sequence. + // b) '*' character matches with ith + // character in input + if (pattern[j - 1] == '*') + lookup[i][j] + = lookup[i][j - 1] || lookup[i - 1][j]; + + // Current characters are considered as + // matching in two cases + // (a) current character of pattern is '?' + // (b) characters actually match + else if (pattern[j - 1] == '?' + || str[i - 1] == pattern[j - 1]) + lookup[i][j] = lookup[i - 1][j - 1]; + + // If characters don't match + else + lookup[i][j] = false; + } + } + + return lookup[n][m]; +} + +int main() +{ + char str[] = "baaabab"; + char pattern[] = "*****ba*****ab"; + // char pattern[] = "ba*****ab"; + // char pattern[] = "ba*ab"; + // char pattern[] = "a*ab"; + // char pattern[] = "a*****ab"; + // char pattern[] = "*a*****ab"; + // char pattern[] = "ba*ab****"; + // char pattern[] = "****"; + // char pattern[] = "*"; + // char pattern[] = "aa?ab"; + // char pattern[] = "b*b"; + // char pattern[] = "a*a"; + // char pattern[] = "baaabab"; + // char pattern[] = "?baaabab"; + // char pattern[] = "*baaaba*"; + + if (strmatch(str, pattern, strlen(str), + strlen(pattern))) + cout << "Yes" << endl; + else + cout << "No" << endl; + + return 0; +} From 08a244fc572aad4e22b4931a51f7255732614870 Mon Sep 17 00:00:00 2001 From: megha-vishwakarma <70430389+megha-vishwakarma@users.noreply.github.com> Date: Sat, 1 Oct 2022 18:58:41 +0530 Subject: [PATCH 100/278] Created snake-game --- Java Games/SimpleSnake.java | 319 ++++++++++++++++++++++++++++++++++++ 1 file changed, 319 insertions(+) create mode 100644 Java Games/SimpleSnake.java diff --git a/Java Games/SimpleSnake.java b/Java Games/SimpleSnake.java new file mode 100644 index 0000000..babcbf8 --- /dev/null +++ b/Java Games/SimpleSnake.java @@ -0,0 +1,319 @@ +package Sb; + +import java.awt.*; +import java.awt.event.*; +import static java.lang.String.format; +import java.util.*; +import java.util.List; +import javax.swing.*; + +public class SimpleSnake extends JPanel implements Runnable { + enum Dir { + up(0, -1), right(1, 0), down(0, 1), left(-1, 0); + + Dir(int x, int y) { + this.x = x; this.y = y; + } + + final int x, y; + } + + static final Random rand = new Random(); + static final int WALL = -1; + static final int MAX_ENERGY = 1500; + + volatile boolean gameOver = true; + + Thread gameThread; + int score, hiScore; + int nRows = 44; + int nCols = 64; + Dir dir; + int energy; + + int[][] grid; + List snake, treats; + Font smallFont; + + public SimpleSnake() { + setPreferredSize(new Dimension(640, 440)); + setBackground(Color.WHITE); + setFont(new Font("TimesNewRoman", Font.BOLD, 48)); + setFocusable(true); + + smallFont = getFont().deriveFont(Font.BOLD, 18); + initGrid(); + + addMouseListener( + new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + if (gameOver) { + startNewGame(); + repaint(); + } + } + }); + + addKeyListener( + new KeyAdapter() { + + @Override + public void keyPressed(KeyEvent e) { + + switch (e.getKeyCode()) { + + case KeyEvent.VK_UP: + if (dir != Dir.down) + dir = Dir.up; + break; + + case KeyEvent.VK_LEFT: + if (dir != Dir.right) + dir = Dir.left; + break; + + case KeyEvent.VK_RIGHT: + if (dir != Dir.left) + dir = Dir.right; + break; + + case KeyEvent.VK_DOWN: + if (dir != Dir.up) + dir = Dir.down; + break; + } + repaint(); + } + }); + } + + void startNewGame() { + gameOver = false; + + stop(); + initGrid(); + treats = new LinkedList<>(); + + dir = Dir.left; + energy = MAX_ENERGY; + + if (score > hiScore) + hiScore = score; + score = 0; + + snake = new ArrayList<>(); + for (int x = 0; x < 7; x++) + snake.add(new Point(nCols / 2 + x, nRows / 2)); + + do + addTreat(); + while(treats.isEmpty()); + + (gameThread = new Thread(this)).start(); + } + + void stop() { + if (gameThread != null) { + Thread tmp = gameThread; + gameThread = null; + tmp.interrupt(); + } + } + + void initGrid() { + grid = new int[nRows][nCols]; + for (int r = 0; r < nRows; r++) { + for (int c = 0; c < nCols; c++) { + if (c == 0 || c == nCols - 1 || r == 0 || r == nRows - 1) + grid[r][c] = WALL; + } + } + } + + @Override + public void run() { + + while (Thread.currentThread() == gameThread) { + + try { + Thread.sleep(Math.max(75 - score, 25)); + } catch (InterruptedException e) { + return; + } + + if (energyUsed() || hitsWall() || hitsSnake()) { + gameOver(); + } else { + if (eatsTreat()) { + score++; + energy = MAX_ENERGY; + growSnake(); + } + moveSnake(); + addTreat(); + } + repaint(); + } + } + + boolean energyUsed() { + energy -= 10; + return energy <= 0; + } + + boolean hitsWall() { + Point head = snake.get(0); + int nextCol = head.x + dir.x; + int nextRow = head.y + dir.y; + return grid[nextRow][nextCol] == WALL; + } + + boolean hitsSnake() { + Point head = snake.get(0); + int nextCol = head.x + dir.x; + int nextRow = head.y + dir.y; + for (Point p : snake) + if (p.x == nextCol && p.y == nextRow) + return true; + return false; + } + + boolean eatsTreat() { + Point head = snake.get(0); + int nextCol = head.x + dir.x; + int nextRow = head.y + dir.y; + for (Point p : treats) + if (p.x == nextCol && p.y == nextRow) { + return treats.remove(p); + } + return false; + } + + void gameOver() { + gameOver = true; + stop(); + } + + void moveSnake() { + for (int i = snake.size() - 1; i > 0; i--) { + Point p1 = snake.get(i - 1); + Point p2 = snake.get(i); + p2.x = p1.x; + p2.y = p1.y; + } + Point head = snake.get(0); + head.x += dir.x; + head.y += dir.y; + } + + void growSnake() { + Point tail = snake.get(snake.size() - 1); + int x = tail.x + dir.x; + int y = tail.y + dir.y; + snake.add(new Point(x, y)); + } + + void addTreat() { + if (treats.size() < 3) { + + if (rand.nextInt(10) == 0) { // 1 in 10 + + if (rand.nextInt(4) != 0) { // 3 in 4 + int x, y; + while (true) { + + x = rand.nextInt(nCols); + y = rand.nextInt(nRows); + if (grid[y][x] != 0) + continue; + + Point p = new Point(x, y); + if (snake.contains(p) || treats.contains(p)) + continue; + + treats.add(p); + break; + } + } else if (treats.size() > 1) + treats.remove(0); + } + } + } + + void drawGrid(Graphics2D g) { + g.setColor(Color.black); + for (int r = 0; r < nRows; r++) { + for (int c = 0; c < nCols; c++) { + if (grid[r][c] == WALL) + g.fillRect(c * 10, r * 10, 10, 10); + } + } + } + + void drawSnake(Graphics2D g) { + g.setColor(Color.red); + for (Point p : snake) + g.fillRect(p.x * 10, p.y * 10, 10, 10); + + g.setColor(energy < 500 ? Color.red : Color.orange); + Point head = snake.get(0); + g.fillRect(head.x * 10, head.y * 10, 10, 10); + } + + void drawTreats(Graphics2D g) { + g.setColor(Color.green); + for (Point p : treats) + g.fillRect(p.x * 10, p.y * 10, 10, 10); + } + + void drawStartScreen(Graphics2D g) { + g.setColor(Color.red); + g.setFont(getFont()); + g.drawString("SNAKE", 240, 190); + g.setColor(Color.orange); + g.setFont(smallFont); + g.drawString("(Click To START)", 250, 240); + } + + void drawScore(Graphics2D g) { + int h = getHeight(); + g.setFont(smallFont); + g.setColor(getForeground()); + String s = format("Hi-Score: %d Score: %d", hiScore, score); + g.drawString(s, 30, h - 30); + g.drawString(format("Energy: %d", energy), getWidth() - 150, h - 30); + } + + @Override + public void paintComponent(Graphics gg) { + super.paintComponent(gg); + Graphics2D g = (Graphics2D) gg; + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + drawGrid(g); + + if (gameOver) { + drawStartScreen(g); + } else { + drawSnake(g); + drawTreats(g); + drawScore(g); + } + } + + public static void main(String[] args) { + SwingUtilities.invokeLater( + () -> { + JFrame mainFrame = new JFrame(); + mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + mainFrame.setTitle("SNAKE"); + mainFrame.setResizable(true); + mainFrame.add(new SimpleSnake(), BorderLayout.CENTER); + mainFrame.pack(); + mainFrame.setLocationRelativeTo(null); + mainFrame.setVisible(true); + }); + } +} From ada3c6215954f266da1b04a1601ac8985a670947 Mon Sep 17 00:00:00 2001 From: Aditya Wadkar <67093170+AdityaWadkar@users.noreply.github.com> Date: Sat, 1 Oct 2022 19:55:32 +0530 Subject: [PATCH 101/278] created basic.py --- Python/Basic.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Python/Basic.py diff --git a/Python/Basic.py b/Python/Basic.py new file mode 100644 index 0000000..316f831 --- /dev/null +++ b/Python/Basic.py @@ -0,0 +1,29 @@ +import pygame +pygame.init() + +#creating window +gamewindow = pygame.display.set_mode((600,400)) +pygame.display.set_caption("Flappy bird") + +# creating specific variables + +exit_game = False +game_over = False + +# creating game loop + +while not exit_game: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + exit_game = True + if event.type == pygame.KEYDOWN: + if event.key == pygame.K_RIGHT: + print("your pressed right arrow key") + if event.key == pygame.K_LEFT: + print("your pressed Left arrow key") + if event.key == pygame.K_UP: + print("your pressed up arrow key") + if event.key == pygame.K_DOWN: + print("you pressed down arrow key") +pygame.quit() +quit() \ No newline at end of file From d41873374b280a83b312b2d920b477b90bb71f02 Mon Sep 17 00:00:00 2001 From: Saurabh gupta <72506852+skgx@users.noreply.github.com> Date: Sat, 1 Oct 2022 20:28:20 +0530 Subject: [PATCH 102/278] added kadane's algorithm code --- CPP/kadanes.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 CPP/kadanes.cpp diff --git a/CPP/kadanes.cpp b/CPP/kadanes.cpp new file mode 100644 index 0000000..33cf57a --- /dev/null +++ b/CPP/kadanes.cpp @@ -0,0 +1,21 @@ +//KADANE,S ALGORITHM +#include +#define pb push_back +#define ll long long int +#define all(x) x.begin(), x.end() +using namespace std; + + int maxSubarraySum(int arr[], int n){ + + int local_max=0; + int global_max=INT_MIN; + + for(int i=0;iglobal_max) + global_max=local_max; + } + return global_max; + +} From 2df48251a3ffb2f80adc789b29023800d250d77a Mon Sep 17 00:00:00 2001 From: Mansi <60071257+mansi0703@users.noreply.github.com> Date: Sat, 1 Oct 2022 20:32:23 +0530 Subject: [PATCH 103/278] Create nqueens.cpp --- CPP/nqueens.cpp | 176 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 CPP/nqueens.cpp diff --git a/CPP/nqueens.cpp b/CPP/nqueens.cpp new file mode 100644 index 0000000..35deeb3 --- /dev/null +++ b/CPP/nqueens.cpp @@ -0,0 +1,176 @@ +/* C++ program to solve N Queen Problem using + + backtracking */ +#include + +using namespace std; +#define N 4 +/* ld is an array where its indices indicate row-col+N-1 + + (N-1) is for shifting the difference to store negative + + indices */ + +int ld[30] = { 0 }; +/* rd is an array where its indices indicate row+col + + and used to check whether a queen can be placed on + + right diagonal or not*/ + +int rd[30] = { 0 }; +/*column array where its indices indicates column and + + used to check whether a queen can be placed in that + + row or not*/ + +int cl[30] = { 0 }; +/* A utility function to print solution */ + +void printSolution(int board[N][N]) +{ + + for (int i = 0; i < N; i++) { + + for (int j = 0; j < N; j++) + + cout<<" "<< board[i][j]<<" "; + + cout<= N) + + return true; + + + + /* Consider this column and try placing + + this queen in all rows one by one */ + + for (int i = 0; i < N; i++) { + + /* Check if the queen can be placed on + + board[i][col] */ + + /* A check if a queen can be placed on + + board[row][col].We just need to check + + ld[row-col+n-1] and rd[row+coln] where + + ld and rd are for left and right + + diagonal respectively*/ + + if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { + + /* Place this queen in board[i][col] */ + + board[i][col] = 1; + + ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; + + + + /* recur to place rest of the queens */ + + if (solveNQUtil(board, col + 1)) + + return true; + + + + /* If placing queen in board[i][col] + + doesn't lead to a solution, then + + remove queen from board[i][col] */ + + board[i][col] = 0; // BACKTRACK + + ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; + + } + + } + + + + /* If the queen cannot be placed in any row in + + this column col then return false */ + + return false; +} +/* This function solves the N Queen problem using + + Backtracking. It mainly uses solveNQUtil() to + + solve the problem. It returns false if queens + + cannot be placed, otherwise, return true and + + prints placement of queens in the form of 1s. + + Please note that there may be more than one + + solutions, this function prints one of the + + feasible solutions.*/ + +bool solveNQ() +{ + + int board[N][N] = { { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 } }; + + + + if (solveNQUtil(board, 0) == false) { + + cout<<"Solution does not exist"; + + return false; + + } + + + + printSolution(board); + + return true; +} + + +// driver program to test above function + +int main() +{ + + solveNQ(); + + return 0; +} From 0db599ab18aae5153c2856436f2300ffe48ec0fe Mon Sep 17 00:00:00 2001 From: Mansi <60071257+mansi0703@users.noreply.github.com> Date: Sat, 1 Oct 2022 20:35:44 +0530 Subject: [PATCH 104/278] Create ratInAMaze.cpp --- CPP/ratInAMaze.cpp | 148 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 CPP/ratInAMaze.cpp diff --git a/CPP/ratInAMaze.cpp b/CPP/ratInAMaze.cpp new file mode 100644 index 0000000..194a5cd --- /dev/null +++ b/CPP/ratInAMaze.cpp @@ -0,0 +1,148 @@ +// C++ program to solve Rat in a Maze problem using +// backtracking +#include + +using namespace std; +// Maze size +#define N 4 + + +bool solveMazeUtil(int maze[N][N], int x, int y,int sol[N][N]); + +// A utility function to print solution matrix sol[N][N] + +void printSolution(int sol[N][N]) +{ + + for (int i = 0; i < N; i++) { + + for (int j = 0; j < N; j++) + + cout<<" "<= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) + + return true; + + return false; +} + +// This function solves the Maze problem using Backtracking. +// It mainly uses solveMazeUtil() to solve the problem. It +// returns false if no path is possible, otherwise return +// true and prints the path in the form of 1s. Please note +// that there may be more than one solutions, this function +// prints one of the feasible solutions. + +bool solveMaze(int maze[N][N]) +{ + + int sol[N][N] = { { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 } }; + + if (solveMazeUtil(maze, 0, 0, sol) == false) { + + cout<<"Solution doesn't exist"; + + return false; + + } + + printSolution(sol); + + return true; +} + +// A recursive utility function to solve Maze problem + +bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]) +{ + + // if (x, y is goal) return true + + if (x == N - 1 && y == N - 1 && maze[x][y] == 1) { + + sol[x][y] = 1; + + return true; + + } + + // Check if maze[x][y] is valid + + if (isSafe(maze, x, y) == true) { + + // Check if the current block is already part of + + // solution path. + + if (sol[x][y] == 1) + + return false; + + // mark x, y as part of solution path + + sol[x][y] = 1; + + /* Move forward in x direction */ + + if (solveMazeUtil(maze, x + 1, y, sol) == true) + + return true; + + // If moving in x direction doesn't give solution + + // then Move down in y direction + + if (solveMazeUtil(maze, x, y + 1, sol) == true) + + return true; + + // If none of the above movements work then + + // BACKTRACK: unmark x, y as part of solution path + + sol[x][y] = 0; + + return false; + + } + + return false; +} + +// driver program to test above function + +int main() +{ + + int maze[N][N] = { { 1, 0, 0, 0 }, + + { 1, 1, 0, 1 }, + + { 0, 1, 0, 0 }, + + { 1, 1, 1, 1 } }; + + solveMaze(maze); + + return 0; +} From 857d410adda1c3481670e155e2fc3f82eccd658b Mon Sep 17 00:00:00 2001 From: Namgup001 <51751217+Namgup001@users.noreply.github.com> Date: Sat, 1 Oct 2022 20:38:27 +0530 Subject: [PATCH 105/278] hacktoberfest-2022 please add my file to your repository with label as hacktoberfest-2022 --- CPP/regularExpressionMatching.cpp | 80 +++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 CPP/regularExpressionMatching.cpp diff --git a/CPP/regularExpressionMatching.cpp b/CPP/regularExpressionMatching.cpp new file mode 100644 index 0000000..5e1811d --- /dev/null +++ b/CPP/regularExpressionMatching.cpp @@ -0,0 +1,80 @@ +// Question- + +// Suppose we have an array of numbers. It stores n integers, there are four elements a, b, c and d in the array. We have another target value, such that a + b + c + d = target. Find all unique quadruplets in the array which satisfies the situation. So if the array is like [-1,0,1,2,0,-2] and target is 0, then the result will be [[-1, 0, 0, 1],[-2, -1, 1, 2], [-2, 0, 0, 2]] +// Input- +// [1,0,-1,0,-2,2] +// 0 +// Output- +// [[1,2,-1,-2],[0,2,0,-2],[0,1,0,-1]] + + + +#include +using namespace std; + + +class Solution { +public: + void addAll(vector < vector >& res, vector < vector >& temp){ + for(int i = 0; i < temp.size(); i++)res.push_back(temp[i]); + } + vector> fourSum(vector& nums, int target) { + sort(nums.begin(), nums.end()); + return kSum(nums, 0, 4, target); + } + vector < vector > kSum(vector & arr, int start, int k, int target){ + vector < vector > res; + if(k == 2){ + int left = start; + int right = arr.size() - 1; + vector temp(2); + while(left < right){ + if(arr[left] + arr[right] == target){ + temp[0] = arr[left]; + temp[1] = arr[right]; + res.push_back(temp); + while(left < right && arr[left] == arr[left + 1])left++; + while(left < right && arr[right] == arr[right - 1])right--; + left++; + right--; + } + else if(arr[left] + arr[right] > target)right--; + else left ++; + } + } + else{ + for(int i = start; i < (int)arr.size() - k + 1; i++){ + if(i > start && arr[i] == arr[i - 1])continue; + vector < vector > temp = kSum(arr, i + 1, k - 1, target - arr[i]); + for(int j = 0; j < temp.size(); j++){ + temp[j].push_back(arr[i]); + } + addAll(res, temp); + } + } + return res; + } +}; + + + +void print_vector(vector > v){ + cout << "["; + for(int i = 0; i v = {1,0,-1,0,-2,2}; + print_vector(ob.fourSum(v, 0)); +} From 9a5780242dc444290a6f53fc90b4d5887c6bea87 Mon Sep 17 00:00:00 2001 From: Fernando Julian Date: Sat, 1 Oct 2022 22:08:38 +0700 Subject: [PATCH 106/278] web-scrapping using request web-scrapping using request --- Python/web-scrapping.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 Python/web-scrapping.py diff --git a/Python/web-scrapping.py b/Python/web-scrapping.py new file mode 100644 index 0000000..5ab7bc2 --- /dev/null +++ b/Python/web-scrapping.py @@ -0,0 +1,6 @@ +import requests +from bs4 import BeautifulSoup + +page = requests.get('http://corona.sumselprov.go.id/index.php?module=home&id=1') + +print(page.content) \ No newline at end of file From c49a21d860fcad6a61bccb36c4c306c5f8dd7469 Mon Sep 17 00:00:00 2001 From: Namgup001 <51751217+Namgup001@users.noreply.github.com> Date: Sat, 1 Oct 2022 20:42:54 +0530 Subject: [PATCH 107/278] hacktoberfest-2022 please add my file to your repository with label as hacktoberfest-2022 --- CPP/regularExpressionMatching.cpp => 4Sum.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename CPP/regularExpressionMatching.cpp => 4Sum.cpp (100%) diff --git a/CPP/regularExpressionMatching.cpp b/4Sum.cpp similarity index 100% rename from CPP/regularExpressionMatching.cpp rename to 4Sum.cpp From b5597d87fd0e3926bec919f565776eccff90ff8e Mon Sep 17 00:00:00 2001 From: Mansi <60071257+mansi0703@users.noreply.github.com> Date: Sat, 1 Oct 2022 20:44:45 +0530 Subject: [PATCH 108/278] Create 4sum.cpp --- CPP/4sum.cpp | 143 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 CPP/4sum.cpp diff --git a/CPP/4sum.cpp b/CPP/4sum.cpp new file mode 100644 index 0000000..62233e4 --- /dev/null +++ b/CPP/4sum.cpp @@ -0,0 +1,143 @@ +// C++ program to find four +// elements with the given sum +#include + +using namespace std; + +// Function to find 4 elements that add up to +// given sum + +void fourSum(int X, int arr[], map> Map, int N) +{ + + int temp[N]; + + + // Iterate from 0 to temp.length + + for (int i = 0; i < N; i++) + + temp[i] = 0; + + + // Iterate from 0 to arr.length + + for (int i = 0; i < N - 1; i++) + + { + + + // Iterate from i + 1 to arr.length + + for (int j = i + 1; j < N; j++) + + { + + + // Store curr_sum = arr[i] + arr[j] + + int curr_sum = arr[i] + arr[j]; + + + // Check if X - curr_sum if present + + // in map + + if (Map.find(X - curr_sum) != Map.end()) + + { + + + // Store pair having map value + + // X - curr_sum + + pair p = Map[X - curr_sum]; + + + if (p.first != i && p.second != i + + && p.first != j && p.second != j + + && temp[p.first] == 0 + + && temp[p.second] == 0 && temp[i] == 0 + + && temp[j] == 0) + + { + + + // Print the output + + cout << arr[i] << "," << arr[j] << + + "," << arr[p.first] << "," << arr[p.second]; + + temp[p.second] = 1; + + temp[i] = 1; + + temp[j] = 1; + + break; + + } + + } + + } + + } +} + +// Program for two Sum + +map> twoSum(int nums[], int N) +{ + + map> Map; + + for (int i = 0; i < N - 1; i++) + + { + + for (int j = i + 1; j < N; j++) + + { + + Map[nums[i] + nums[j]].first = i; + + Map[nums[i] + nums[j]].second = j; + + } + + } + + return Map; +} + +// Driver code + +int main() +{ + + int arr[] = { 10, 20, 30, 40, 1, 2 }; + + int n = sizeof(arr) / sizeof(arr[0]); + + int X = 91; + + map> Map = twoSum(arr, n); + + + + // Function call + + fourSum(X, arr, Map, n); + + + return 0; +} From 24d8adfe9e1f43287dfcfc1f47655bd210715148 Mon Sep 17 00:00:00 2001 From: Namgup001 <51751217+Namgup001@users.noreply.github.com> Date: Sat, 1 Oct 2022 20:46:21 +0530 Subject: [PATCH 109/278] hacktoberfest-2022 please add my file to your repository with label as hacktoberfest-2022 --- Permutation in String.cpp | 41 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Permutation in String.cpp diff --git a/Permutation in String.cpp b/Permutation in String.cpp new file mode 100644 index 0000000..22d1de0 --- /dev/null +++ b/Permutation in String.cpp @@ -0,0 +1,41 @@ +Question- + +Suppose we have two strings s1 and s2, we have to write a function to return true if s2 contains the permutation of s1. So we can say that one of the first string's permutations is the substring of the second string. + +Input- +"abc" +"findcab" +Output- +1 + + +Solution- + +#include +using namespace std; +class Solution { +public: + bool checkInclusion(string s1, string s2) { + vector cnt1(26), cnt2(26); + for(int i = 0; i < s1.size(); i++)cnt1[s1[i] - 'a']++; + int j = 0; + int required = s1.size(); + for(int i = 0; i < s2.size(); i++){ + char x = s2[i]; + cnt2[x - 'a']++; + if(cnt1[x - 'a'] && cnt2[x - 'a'] <= cnt1[x - 'a']) required--; + while(j <= i && cnt2[s2[j] - 'a'] - 1 >= cnt1[s2[j] - 'a']){ + cnt2[s2[j] - 'a']--; + j++; + } + if(i - j + 1 == s1.size() && required == 0){ + return true; + } + } + return false; + } +}; +main(){ + Solution ob; + cout << (ob.checkInclusion("abc", "findcab")); +} From f3f7f3ca02dab94e3af0d3abca9759538476f011 Mon Sep 17 00:00:00 2001 From: lakshay451 <89472581+lakshay451@users.noreply.github.com> Date: Sat, 1 Oct 2022 21:01:40 +0530 Subject: [PATCH 110/278] Added solution for reversing a linked list --- CPP/Reverse_linked_list.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 CPP/Reverse_linked_list.cpp diff --git a/CPP/Reverse_linked_list.cpp b/CPP/Reverse_linked_list.cpp new file mode 100644 index 0000000..0ff73cf --- /dev/null +++ b/CPP/Reverse_linked_list.cpp @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + ListNode* prev = NULL; + ListNode* nxt = NULL; + ListNode* temp = head; + + while(temp != NULL) + { + nxt = temp->next; + temp->next = prev; + prev = temp; + temp = nxt; + } + return prev; + } +}; From 3ea6010d6db5d8d10049ec85b0c024db28284900 Mon Sep 17 00:00:00 2001 From: VarunBhattacharya <76221455+VarunBhattacharya@users.noreply.github.com> Date: Sat, 1 Oct 2022 21:30:20 +0530 Subject: [PATCH 111/278] Operations on Stack Implementation of various operations on the stack. --- Python/Operations_On_Stack.py | 88 +++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 Python/Operations_On_Stack.py diff --git a/Python/Operations_On_Stack.py b/Python/Operations_On_Stack.py new file mode 100644 index 0000000..a0169fc --- /dev/null +++ b/Python/Operations_On_Stack.py @@ -0,0 +1,88 @@ +''' +Operations on Stack +''' + +arr = [] + +# def input_elements(n): +# for i in range(0,n): +# ele = int(input(f"Enter {i+1} element: ")) +# arr.append(ele) + +def push(): + if(len(arr) == n): + print("Stack Overflow") + else: + ele = int(input("Enter Value to be inserted: ")) + arr.append(ele) + +def pop(): + if(len(arr) == 0): + print("No Elements There") + else: + print(f"Popped element is: {arr.pop()}") + #del arr[n-1] + +def disp(): + if(len(arr) == 0): + print("No Elements There") + else: + print(f"Array elements are: {arr}") + #print(arr) + +def peek(): + if(len(arr) == 0): + print("No Elements There") + else: + print(f"Array elements are: {arr[-1]}") + +def isFull(): + if(len(arr) == n): + print("Stack Overflow") + else: + print("Stack not full") + +def isEmpty(): + if(len(arr) == 0): + print("Empty Stack") + else: + print("Stack has elements") + +def size(): + print(f"Size of array is: {len(arr)}") + + +print("Basic Operations on Stack") +n = int(input("Enter size of array: ")) + +while(True): + print("\n") + print("1_Push in Stack") + print("2_Pop from Stack") + print("3_Display the Stack") + print("4_Peek from Stack") + print("5_IsFull Stack") + print("6_IsEmpty Stack") + print("7_Size") + print("8_Exit") + + opt = int(input("\nEnter your choice: ")) + + if(opt == 1): + push() + elif(opt == 2): + pop() + elif(opt == 3): + disp() + elif(opt == 4): + peek() + elif(opt == 5): + isFull() + elif(opt == 6): + isEmpty() + elif(opt == 7): + size() + elif(opt == 8): + exit() + else: + print("Invalid Choice") \ No newline at end of file From a526a93da2f708d866f13413fe9757b45738b5d7 Mon Sep 17 00:00:00 2001 From: Namgup001 <51751217+Namgup001@users.noreply.github.com> Date: Sat, 1 Oct 2022 21:32:26 +0530 Subject: [PATCH 112/278] hacktoberfest-2022 please add my file to your repository with label as hacktoberfest --- 3SumClosest.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 3SumClosest.cpp diff --git a/3SumClosest.cpp b/3SumClosest.cpp new file mode 100644 index 0000000..bc4f4d2 --- /dev/null +++ b/3SumClosest.cpp @@ -0,0 +1,39 @@ +// Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. + +// Return the sum of the three integers. + +// You may assume that each input would have exactly one solution. + +// https://leetcode.com/problems/3sum-closest/ + +// Example 1: + +// Input: nums = [-1,2,1,-4], target = 1 +// Output: 2 +// Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). + + + +int threeSumClosest(vector& nums, int target) { + if(nums.size() < 3) return 0; + int closest = nums[0]+nums[1]+nums[2]; + sort(nums.begin(), nums.end()); + for(int first = 0 ; first < nums.size()-2 ; ++first) { + if(first > 0 && nums[first] == nums[first-1]) continue; + int second = first+1; + int third = nums.size()-1; + while(second < third) { + int curSum = nums[first]+nums[second]+nums[third]; + if(curSum == target) return curSum; + if(abs(target-curSum) target) { + --third; + } else { + ++second; + } + } + } + return closest; +} From 46bba465b3b3e5befbd864bd16c77d70e25b3d8a Mon Sep 17 00:00:00 2001 From: harendrabhardwaj <40700440+harendrabhardwaj@users.noreply.github.com> Date: Sat, 1 Oct 2022 21:33:50 +0530 Subject: [PATCH 113/278] Temperature conversion --- temperatureConversion.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 temperatureConversion.java diff --git a/temperatureConversion.java b/temperatureConversion.java new file mode 100644 index 0000000..2cf8fdf --- /dev/null +++ b/temperatureConversion.java @@ -0,0 +1,12 @@ +import java.util.Scanner; +public class temperatureConversion { + public static void main(String[] args){ + float celsius,fahrenheit; + Scanner input = new Scanner(System.in); + System.out.println("Enter temperature in Fahrenheit :"); + fahrenheit=input.nextInt(); + celsius=(fahrenheit - 32)*5/9; + System.out.println("Celsius = "+celsius); + input.close(); + } +} From f43019d0ab3dd592241a6fe5ee3bbce6c96bc472 Mon Sep 17 00:00:00 2001 From: VarunBhattacharya <76221455+VarunBhattacharya@users.noreply.github.com> Date: Sat, 1 Oct 2022 21:35:56 +0530 Subject: [PATCH 114/278] Binary Search in an array Binary Search in an array using various different sorting algorithms. --- Python/BinarySearch.py | 52 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Python/BinarySearch.py diff --git a/Python/BinarySearch.py b/Python/BinarySearch.py new file mode 100644 index 0000000..542cd31 --- /dev/null +++ b/Python/BinarySearch.py @@ -0,0 +1,52 @@ +''' +Binary Search +''' + +class BinarySearch: + def __init__(self, arr, val): + self.arr = arr + self.val = val + + def bubsortArray(self): + for i in range(len(self.arr)): + for j in range(len(self.arr)-1): + if self.arr[i] < self.arr[j]: + self.arr[i], self.arr[j] = self.arr[j], self.arr[i] + return self.arr + + def selectsortArray(self): + for i in range(len(self.arr)): + for j in range(i+1, len(self.arr)): + if self.arr[i] > self.arr[j]: + self.arr[j], self.arr[i] = self.arr[i], self.arr[j] + return self.arr + + def insertsortArray(self): + for i in range(len(self.arr)): + for j in range(i ,0 , -1): + if self.arr[j] < self.arr[j-1]: + self.arr[j], self.arr[j-1] = self.arr[j-1], self.arr[j] + return self.arr + + def binarySearch(self): + # self.arr = self.bubsortArray() + # self.arr = self.selectsortArray() + self.arr = self.insertsortArray() + beg = 0 + end = len(self.arr)-1 + mid = 0 + + while beg < end: + mid = (beg + end)//2 + if self.arr[mid] == self.val: + return mid+1 + elif self.arr[mid] < self.val: + beg = mid+1 + else: + end = mid-1 + + return -1 + +if __name__ == "__main__": + obj = BinarySearch([4,1,7,3,8,2,9,5,6], 5) + print("Element not present." if obj.binarySearch == -1 else f"Element found at position: {obj.binarySearch()}.") \ No newline at end of file From 2ecc16256893d2bd7200f78fea776ded4ae5e3cb Mon Sep 17 00:00:00 2001 From: Sahil Rana <51770809+Rsr0@users.noreply.github.com> Date: Sat, 1 Oct 2022 21:37:28 +0530 Subject: [PATCH 115/278] Create generateParentheses.cpp --- CPP/generateParentheses.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 CPP/generateParentheses.cpp diff --git a/CPP/generateParentheses.cpp b/CPP/generateParentheses.cpp new file mode 100644 index 0000000..6235dc0 --- /dev/null +++ b/CPP/generateParentheses.cpp @@ -0,0 +1,27 @@ +/* +Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. +Input: n = 3 +Output: ["((()))","(()())","(())()","()(())","()()()"] + +*/ + +class Solution { +public: + + void solve(vector &res, string s, int left, int right ){ + if(left==0 && right==0){ + res.push_back(s); + return; + } + + if(left>0) solve(res, s+"(", left-1, right); + if(right>left) solve(res, s+")", left, right-1); + + } + + vector generateParenthesis(int n) { + vector res; + solve(res, "", n, n); + return res; + } +}; From 8843b2cddf20bd36783749a4dba5b6a6e45bb835 Mon Sep 17 00:00:00 2001 From: Namgup001 <51751217+Namgup001@users.noreply.github.com> Date: Sat, 1 Oct 2022 21:46:13 +0530 Subject: [PATCH 116/278] hacktoberfest-2022 please add my file to your repository with label as hacktoberfest --- Building_roads_cses(connected_components).cpp | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Building_roads_cses(connected_components).cpp diff --git a/Building_roads_cses(connected_components).cpp b/Building_roads_cses(connected_components).cpp new file mode 100644 index 0000000..8ae20aa --- /dev/null +++ b/Building_roads_cses(connected_components).cpp @@ -0,0 +1,77 @@ +#include +using namespace std; +#define ll long long int +#define sz(x) x.size() +#define pb push_back +#define pb2 pop_back +#define ff first +#define ss second +#define lb lower_bound +#define ub upper_bound +#define bend(x) x.begin(), x.end() +#define vi vector +#define mapp map +#define sett set +#define ve vector +#define un_m unordered_map +#define f(i, a, b) for (i = a; i < b; i++) +#define f2(i, a) for (auto i = a.begin(); i != a.end(); i++) +#define MAXN 10000001 + +#define mp make_pair +#define in(t) scanf("%lld",&t) +#define out(t) printf("%lld",t) + +const unsigned int moduli = 1000000007; + + +ll vis[1000001]; +vi v[1000001]; +vi l; + +void dfs(ll n) { + vis[n] = 1; + for (auto a : v[n]) { + if (!vis[a]) { + dfs(a); + } + } +} + +void sol() { + ll d = 0, ds, e = 0, x, n, k; + ll i, j, tt = 0, w = 0, t; + ll ans = 0, cnt = 0, sum = 0; + ll m; + cin >> n >> m; + f(i, 0, m) { + cin >> d >> e; + v[d].pb(e); + v[e].pb(d); + } + f(i, 1, n + 1) { + if (!vis[i]) l.pb(i), dfs(i), ans++; + } + cout << ans - 1 << endl; + cnt = l[0]; + if (ans > 1) + f(i, 1, ans) { + ds = l[i]; + cout << cnt << " " << ds << endl; + cnt = ds; + } + +} + +// driver function +int main() { + + ll tc; + //cin >> tc; + //while (tc--) { + sol(); + cout << endl; + // } + + return 0; +} \ No newline at end of file From 551eede3899313889ce27310f94797f99e407154 Mon Sep 17 00:00:00 2001 From: Namgup001 <51751217+Namgup001@users.noreply.github.com> Date: Sat, 1 Oct 2022 21:48:14 +0530 Subject: [PATCH 117/278] hacktoberfest-2022 please add my file to your repository with label as hacktoberfest --- CPP/Rabin-Karp.cpp | 155 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 CPP/Rabin-Karp.cpp diff --git a/CPP/Rabin-Karp.cpp b/CPP/Rabin-Karp.cpp new file mode 100644 index 0000000..5724ae8 --- /dev/null +++ b/CPP/Rabin-Karp.cpp @@ -0,0 +1,155 @@ +#include +using namespace std; +#define ll long long int +#define sz(x) x.size() +#define pb push_back +#define pb2 pop_back +#define ff first +#define ss second +#define lb lower_bound +#define ub upper_bound +#define bend(x) x.begin(), x.end() +#define vi vector +#define mapp map +#define sett set +#define ve vector +#define un_m unordered_map +#define f(i, a, b) for (i = a; i < b; i++) +#define f2(i, x) for (i = a.begin(); i != a.end(); i++) +#define maxxx INT32_MAX +#define mp make_pair +/* +const unsigned int moduli = 1000000007; +ll gcd(ll a, ll b) +{ + if (b == 0) + return a; + return gcd(b, a % b); +} +*/ +/* +ll getIndex(vector v, ll K) +{ + auto it = find(v.begin(), v.end(), K); + + if (it != v.end()) { + + ll index = distance(v.begin(), it); + return index; + } + + return -1; + +} +*/ +/* +string d2b(ll N) +{ + + // To store the binary number + ll B_Number = 0; + ll cnt = 0; + while (N != 0) { + ll rem = N % 2; + ll c = pow(10, cnt); + B_Number += rem * c; + N /= 2; + + // Count used to store exponent value + cnt++; + } Pattern found at index 0 + + return to_string(B_Number); +} */ +void solution() +{ + +// ll n,m,k; + + string aa,s,t; + cin>>s>>t; + aa=s; + ll code=0,code2=0; + ll l1=s.length(); + ll l2=t.length(); + vi v; + s+="#"; + s+=t; + //cout<0 && t[i]!=t[tt]) + tt=pi[tt-1]; + + if(t[i]==t[tt]) + tt++; + + pi[i]=tt; + } + + ll cnt = 0, prev = 0; + ll n=t.length(); +/* f(i,0,n) + { + tt=prev; + while(tt>0 && s[i]!=s[tt]) + tt=pi[tt-1]; + if(s[i]==t[tt]) + tt++; + prev=tt; + if(tt==l2) + { + aa.pb(i+1); + cnt++; + } + }*/ + + for(i=0;i> tc; + while (tc--) + { + solution(); + cout << endl; + } + + return 0; +} +/* +ll power(ll x,ll y) +{ + //(x^y)%MOD + ll ans=1,s=x; + while(y){ + if(y&1){ + ans*=s; + ans%=moduli; + } + s*=s; + s%=moduli; + y>>=1; + } + return ans; +} + + +*/ From 0530150ab390748d873ec9f184a5e1ebaa1eda17 Mon Sep 17 00:00:00 2001 From: VarunBhattacharya <76221455+VarunBhattacharya@users.noreply.github.com> Date: Sat, 1 Oct 2022 21:48:25 +0530 Subject: [PATCH 118/278] Create readme.md Data Structures in C programming language. --- C/readme.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 C/readme.md diff --git a/C/readme.md b/C/readme.md new file mode 100644 index 0000000..8adea76 --- /dev/null +++ b/C/readme.md @@ -0,0 +1 @@ +This following folder contains data structures and algorithms in C programming language. From df44114d8b2d4f40035db20ee1a2f0708a59e275 Mon Sep 17 00:00:00 2001 From: Namgup001 <51751217+Namgup001@users.noreply.github.com> Date: Sat, 1 Oct 2022 21:49:47 +0530 Subject: [PATCH 119/278] hacktoberfest-2022 please add my file to your repository with label as hacktoberfest --- CPP/Rabin-Karp.cpp | 155 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 CPP/Rabin-Karp.cpp diff --git a/CPP/Rabin-Karp.cpp b/CPP/Rabin-Karp.cpp new file mode 100644 index 0000000..5724ae8 --- /dev/null +++ b/CPP/Rabin-Karp.cpp @@ -0,0 +1,155 @@ +#include +using namespace std; +#define ll long long int +#define sz(x) x.size() +#define pb push_back +#define pb2 pop_back +#define ff first +#define ss second +#define lb lower_bound +#define ub upper_bound +#define bend(x) x.begin(), x.end() +#define vi vector +#define mapp map +#define sett set +#define ve vector +#define un_m unordered_map +#define f(i, a, b) for (i = a; i < b; i++) +#define f2(i, x) for (i = a.begin(); i != a.end(); i++) +#define maxxx INT32_MAX +#define mp make_pair +/* +const unsigned int moduli = 1000000007; +ll gcd(ll a, ll b) +{ + if (b == 0) + return a; + return gcd(b, a % b); +} +*/ +/* +ll getIndex(vector v, ll K) +{ + auto it = find(v.begin(), v.end(), K); + + if (it != v.end()) { + + ll index = distance(v.begin(), it); + return index; + } + + return -1; + +} +*/ +/* +string d2b(ll N) +{ + + // To store the binary number + ll B_Number = 0; + ll cnt = 0; + while (N != 0) { + ll rem = N % 2; + ll c = pow(10, cnt); + B_Number += rem * c; + N /= 2; + + // Count used to store exponent value + cnt++; + } Pattern found at index 0 + + return to_string(B_Number); +} */ +void solution() +{ + +// ll n,m,k; + + string aa,s,t; + cin>>s>>t; + aa=s; + ll code=0,code2=0; + ll l1=s.length(); + ll l2=t.length(); + vi v; + s+="#"; + s+=t; + //cout<0 && t[i]!=t[tt]) + tt=pi[tt-1]; + + if(t[i]==t[tt]) + tt++; + + pi[i]=tt; + } + + ll cnt = 0, prev = 0; + ll n=t.length(); +/* f(i,0,n) + { + tt=prev; + while(tt>0 && s[i]!=s[tt]) + tt=pi[tt-1]; + if(s[i]==t[tt]) + tt++; + prev=tt; + if(tt==l2) + { + aa.pb(i+1); + cnt++; + } + }*/ + + for(i=0;i> tc; + while (tc--) + { + solution(); + cout << endl; + } + + return 0; +} +/* +ll power(ll x,ll y) +{ + //(x^y)%MOD + ll ans=1,s=x; + while(y){ + if(y&1){ + ans*=s; + ans%=moduli; + } + s*=s; + s%=moduli; + y>>=1; + } + return ans; +} + + +*/ From 262347911957133baa7f8b059a2e9611f54815b9 Mon Sep 17 00:00:00 2001 From: VarunBhattacharya <76221455+VarunBhattacharya@users.noreply.github.com> Date: Sat, 1 Oct 2022 21:49:49 +0530 Subject: [PATCH 120/278] PostFix Evaluation Evaluating Postfix expression using stack concepts. --- C/PostfixEvaluation.c | 96 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 C/PostfixEvaluation.c diff --git a/C/PostfixEvaluation.c b/C/PostfixEvaluation.c new file mode 100644 index 0000000..2d86707 --- /dev/null +++ b/C/PostfixEvaluation.c @@ -0,0 +1,96 @@ +/* +Given a postfix expression in digits(only from 0-9), evaluate it and get the answer using stack. +Test Case +i.) 65*3+ (ans - 33) +ii.) 245+* (ans - 18) + +Short Algorithm +---> Include all the required libraries +---> Make the function push and pop +---> read the postfix expression and read till the end +---> find the result and push it in the stack +---> call the function whatever required for finding the result +---> pop the result in a variable and print it +*/ + +//Including Libraries +#include +#include +#include + +//Global Declarations +int size = 50; +char input[50]; +int arr[50]; +int top = -1; + +//Function Declarations +int pop(); +void push(); + +//Main Function +int main() +{ + int i, x, y, res; + char c; + int ans; + printf("Enter the Postfix Expression: "); + scanf("%s", &input); + for(i = 0; input[i] != '\0'; i++) + { + c = input[i]; + // if(isalpha(c) == 0) //it cannot accept alphabets, only digits + // { + // printf("\nWrong Input! Enter only digits for the solution\n"); + // } + if(isdigit(c)) //check for digits and then pushing the value + { + push(c - 48); //pushing the actual value in the expression by subtracting the ASCII value of 0 + } + else if(c == '+' || c == '-' || c == '*' || c == '/') + { + y = pop(); + x = pop(); + switch(c) //for finding the results + { + case '+': res = x + y; break; + case '-': res = x - y; break; + case '*': res = x * y; break; + case '/': res = x / y; break; + } + push(res); //pushing in the array + } + } + ans = pop(); //popping the final answer + printf("\nThe Postfix Expression is: %d", ans); + return 0; +} + +//Function Implementation +void push(int a) +{ + if (top < size - 1) + { + arr[++top] = a; //incrementing the top position and then inserting the element + } + else + { + printf("\nStack Overflow\n"); + exit(0); + } +} +int pop() +{ + int a; + if (top > -1) + { + a = arr[top]; //popping the element + arr[top--] = -1; + return a; //returning the element + } + else + { + printf("\nNo Element There\n"); + exit(0); + } +} \ No newline at end of file From 5f0b76ac94d14d8a1cff01ebe0b0b0272dc651d4 Mon Sep 17 00:00:00 2001 From: nishitv2898 <36642477+nishitv2898@users.noreply.github.com> Date: Sat, 1 Oct 2022 21:51:04 +0530 Subject: [PATCH 121/278] Strong Number Checker --- strongNumberCheck.java | 57 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 strongNumberCheck.java diff --git a/strongNumberCheck.java b/strongNumberCheck.java new file mode 100644 index 0000000..786316d --- /dev/null +++ b/strongNumberCheck.java @@ -0,0 +1,57 @@ +import java.util.Scanner; + +public class StrongNumberCheck { + + + public static boolean isStrong(int number) { + + + int sum = 0, lastDigit = 0; + int tempNum = number; + + + while(tempNum != 0) { + lastDigit = tempNum % 10; + sum += factorial(lastDigit); + tempNum /= 10; + } + + + if(sum == number) + return true; + return false; + } + + + public static long factorial(int n) { + long fact = 1; + for(int i=1; i<=n; i++) { + fact *= i; + } + return fact; + } + + public static void main(String[] args) { + + int number = 0; + boolean result = false; + + + Scanner scan = new Scanner(System.in); + + + System.out.print("Enter an integer number:: "); + number = scan.nextInt(); + + + result = isStrong(number); + if(result) + System.out.println(number + + " is a strong number."); + else + System.out.println(number + + " is not a strong number"); + + scan.close(); + } +} From b07abdb1abbd4a100d6d19417b958c287f0b085f Mon Sep 17 00:00:00 2001 From: Namgup001 <51751217+Namgup001@users.noreply.github.com> Date: Sat, 1 Oct 2022 21:52:25 +0530 Subject: [PATCH 122/278] hacktoberfest-2022 please add my file to your repository with label as hacktoberfest --- CPP/minimizingCoins.cpp | 66 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 CPP/minimizingCoins.cpp diff --git a/CPP/minimizingCoins.cpp b/CPP/minimizingCoins.cpp new file mode 100644 index 0000000..ec77ab4 --- /dev/null +++ b/CPP/minimizingCoins.cpp @@ -0,0 +1,66 @@ +#include +using namespace std; +#define ll long long int +#define sz(x) x.size() +#define pb push_back +#define pb2 pop_back +#define ff first +#define ss second +#define lb lower_bound +#define ub upper_bound +#define bend(x) x.begin(), x.end() +#define vi vector +#define mapp map +#define sett set +#define ve vector +#define un_m unordered_map +#define f(i, a, b) for (i = a; i < b; i++) +#define f2(i, x) for (i = a.begin(); i != a.end(); i++) +#define maxxx INT32_MAX +#define mp make_pair +#define in(t) scanf("%lld",&t) +#define out(t) printf("%lld",t) + +const unsigned int moduli = 1000000007; + + +void sol() +{ + ll d=0,ds,e=0,x,n,k; + ll i,j,tt=0,t; + ll cnt=0,sum=0; + + cin>>n>>x; + ll a[n]; + f(i,0,n) cin>>a[i]; + + ll dp[x+1]; + + f(i,0,x+1) dp[i]=INT_MAX; + + dp[0]=0; + f(i,1,n+1) + { + f(j,0,x+1) + { + if(j-a[i-1] >= 0) + dp[j]=min( dp[j-a[i-1]] + 1 , dp[j]); + } + } + if(dp[x]==INT_MAX) cout<<-1; + else cout<> tc; + // while (tc--) + // { + sol(); + cout << endl; + // } + + return 0; +} \ No newline at end of file From 3ece1080c3e70089952ecac79faf245d026cf9c7 Mon Sep 17 00:00:00 2001 From: devanshukd04 Date: Sat, 1 Oct 2022 22:17:18 +0530 Subject: [PATCH 123/278] Added BST using preorder traversal --- BST using preorder traversal.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 BST using preorder traversal.cpp diff --git a/BST using preorder traversal.cpp b/BST using preorder traversal.cpp new file mode 100644 index 0000000..cc8d18c --- /dev/null +++ b/BST using preorder traversal.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + TreeNode* solve(vector& preorder,int mini,int maxi,int &i){ + if(i>=preorder.size()){ + return NULL; + } + if(preorder[i]maxi){ + return NULL; + } + TreeNode* root=new TreeNode(preorder[i++]); + root->left=solve(preorder,mini,root->val,i); + root->right=solve(preorder,root->val,maxi,i); + return root; + } + TreeNode* bstFromPreorder(vector& preorder) { + int mini=INT_MIN; + int maxi=INT_MAX; + int i=0; + + return solve(preorder,mini,maxi,i); + } +}; \ No newline at end of file From 2c1532fdb746e3b9e8c2eaf60fc9e025ff196dc3 Mon Sep 17 00:00:00 2001 From: devanshukd04 Date: Sat, 1 Oct 2022 22:23:25 +0530 Subject: [PATCH 124/278] Added Circular Queue implementation in C++ --- CPP/Circular Queue | 97 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 CPP/Circular Queue diff --git a/CPP/Circular Queue b/CPP/Circular Queue new file mode 100644 index 0000000..711333d --- /dev/null +++ b/CPP/Circular Queue @@ -0,0 +1,97 @@ +#include +using namespace std; + +int cqueue[10]; +int front = -1, rear = -1, n=5; + +void insertCQ(int val) { + if ((front == 0 && rear == n-1) || (front == rear+1)) { + cout<<"Queue is full\n"; + return; + } + if (front == -1) { + front = 0; + rear = 0; + } else { + if (rear == n - 1) + rear = 0; + else + rear = rear + 1; + } + cqueue[rear] = val ; +} +void deleteCQ() { + if (front == -1) { + cout<<"Queue Underflow\n"; + return ; + } + cout<<"Element deleted from queue is : "<>ch; + switch(ch) { + case 1: + cout<<"Enter the value"<>val; + insertCQ(val); + break; + + case 2: + deleteCQ(); + break; + + case 3: + displayCQ(); + break; + + case 4: + cout<<"Exit\n"; + break; + default: cout<<"Enter valid option!\n"; + } + } while(ch != 4); + return 0; +} \ No newline at end of file From 3c6625661532920f1643e03702a07dfa9d0a0428 Mon Sep 17 00:00:00 2001 From: SHIRANSH PRATAP SINGH <90133405+singhshrey27@users.noreply.github.com> Date: Sat, 1 Oct 2022 22:24:27 +0530 Subject: [PATCH 125/278] sliding_window problem --- Slidingwindow.cpp | 53 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Slidingwindow.cpp diff --git a/Slidingwindow.cpp b/Slidingwindow.cpp new file mode 100644 index 0000000..7697e59 --- /dev/null +++ b/Slidingwindow.cpp @@ -0,0 +1,53 @@ +/* +Test Case 1: +Input : s = "abcabcbb" +Output: 3 +Explaination: here longest substring without repeating character is "abc" so answer is 3 +Test Case 2: +Input : s = "bbbbb" +Output : 1 +Explaination : here longest substring without repeating character is "b" only +*/ +//Solution here + +#include +using namespace std; +int lengthOfLongestSubstring(string s) { + unordered_map mp; + int i=0,j=0; + int maxm=0; + while(j>t; + cout<<"The length of longest substring is : "< Date: Sat, 1 Oct 2022 22:24:48 +0530 Subject: [PATCH 126/278] Linear Search --- Linear Search | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Linear Search diff --git a/Linear Search b/Linear Search new file mode 100644 index 0000000..50f03c7 --- /dev/null +++ b/Linear Search @@ -0,0 +1,38 @@ +class GFG { + + // Function for linear search + public static int search(int arr[], int x) + { + int n = arr.length; + + // Traverse array arr[] + for (int i = 0; i < n; i++) { + + // If element found then + // return that index + if (arr[i] == x) + return i; + } + return -1; + } + + // Driver Code + public static void main(String args[]) + { + // Given arr[] + int arr[] = { 2, 3, 4, 10, 40 }; + + // Element to search + int x = 10; + + // Function Call + int result = search(arr, x); + if (result == -1) + System.out.print( + "Element is not present in array"); + else + System.out.print("Element is present" + + " at index " + + result); + } +} From 7334859e3c2701222edbda7a51e134ea3de69ed3 Mon Sep 17 00:00:00 2001 From: Devanshu Kishor Dalal Date: Sat, 1 Oct 2022 22:24:54 +0530 Subject: [PATCH 127/278] Delete Circular Queue --- CPP/Circular Queue | 97 ---------------------------------------------- 1 file changed, 97 deletions(-) delete mode 100644 CPP/Circular Queue diff --git a/CPP/Circular Queue b/CPP/Circular Queue deleted file mode 100644 index 711333d..0000000 --- a/CPP/Circular Queue +++ /dev/null @@ -1,97 +0,0 @@ -#include -using namespace std; - -int cqueue[10]; -int front = -1, rear = -1, n=5; - -void insertCQ(int val) { - if ((front == 0 && rear == n-1) || (front == rear+1)) { - cout<<"Queue is full\n"; - return; - } - if (front == -1) { - front = 0; - rear = 0; - } else { - if (rear == n - 1) - rear = 0; - else - rear = rear + 1; - } - cqueue[rear] = val ; -} -void deleteCQ() { - if (front == -1) { - cout<<"Queue Underflow\n"; - return ; - } - cout<<"Element deleted from queue is : "<>ch; - switch(ch) { - case 1: - cout<<"Enter the value"<>val; - insertCQ(val); - break; - - case 2: - deleteCQ(); - break; - - case 3: - displayCQ(); - break; - - case 4: - cout<<"Exit\n"; - break; - default: cout<<"Enter valid option!\n"; - } - } while(ch != 4); - return 0; -} \ No newline at end of file From b716556527958d66314eb6bc9aed9d0668e20c48 Mon Sep 17 00:00:00 2001 From: devanshukd04 Date: Sat, 1 Oct 2022 22:26:35 +0530 Subject: [PATCH 128/278] Added Circular Queue implementation in C++ --- CPP/Circular Queue.cpp | 97 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 CPP/Circular Queue.cpp diff --git a/CPP/Circular Queue.cpp b/CPP/Circular Queue.cpp new file mode 100644 index 0000000..711333d --- /dev/null +++ b/CPP/Circular Queue.cpp @@ -0,0 +1,97 @@ +#include +using namespace std; + +int cqueue[10]; +int front = -1, rear = -1, n=5; + +void insertCQ(int val) { + if ((front == 0 && rear == n-1) || (front == rear+1)) { + cout<<"Queue is full\n"; + return; + } + if (front == -1) { + front = 0; + rear = 0; + } else { + if (rear == n - 1) + rear = 0; + else + rear = rear + 1; + } + cqueue[rear] = val ; +} +void deleteCQ() { + if (front == -1) { + cout<<"Queue Underflow\n"; + return ; + } + cout<<"Element deleted from queue is : "<>ch; + switch(ch) { + case 1: + cout<<"Enter the value"<>val; + insertCQ(val); + break; + + case 2: + deleteCQ(); + break; + + case 3: + displayCQ(); + break; + + case 4: + cout<<"Exit\n"; + break; + default: cout<<"Enter valid option!\n"; + } + } while(ch != 4); + return 0; +} \ No newline at end of file From ea99aa7657532a6ddc9e4fa2557e5b34490d0d90 Mon Sep 17 00:00:00 2001 From: SHIRANSH PRATAP SINGH <90133405+singhshrey27@users.noreply.github.com> Date: Sat, 1 Oct 2022 22:44:13 +0530 Subject: [PATCH 129/278] Create Insertionsort.cpp --- Insertionsort.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Insertionsort.cpp diff --git a/Insertionsort.cpp b/Insertionsort.cpp new file mode 100644 index 0000000..34ba1c0 --- /dev/null +++ b/Insertionsort.cpp @@ -0,0 +1,33 @@ + // code of the insertion sort +#include +using namespace std; + int main() + { + int n; + cout<<"Enter the size of the array you want to sort"<>n; + int arr[n]; + cout<<"Enter the elements of the array"<>arr[i]; + } + int j,temp=0; + for(int i=1;i=0&&arr[j]>temp) + { + arr[j+1]=arr[j]; + j--; + } + arr[j+1]=temp; + } + for(int i=0;i Date: Sat, 1 Oct 2022 22:46:34 +0530 Subject: [PATCH 130/278] Create Quicksort.cpp --- Quicksort.cpp | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Quicksort.cpp diff --git a/Quicksort.cpp b/Quicksort.cpp new file mode 100644 index 0000000..d5b5523 --- /dev/null +++ b/Quicksort.cpp @@ -0,0 +1,57 @@ +#include +using namespace std; +void swap(int *x,int *y) +{ + int temp; + temp=*x; + *x=*y; + *y=temp; +} +int partition(int arr[],int lb,int ub) +{ +int pivot=arr[lb]; +int start=lb; +int end=ub; +while(startpivot) +{ + end--; +} +if(start Date: Sat, 1 Oct 2022 23:10:52 +0530 Subject: [PATCH 131/278] Create Krushkals_algorithm_in_java Please add my file with label hacktoberfest-2022 --- Krushkals_algorithm_in_java | 187 ++++++++++++++++++++++++++++++++++++ 1 file changed, 187 insertions(+) create mode 100644 Krushkals_algorithm_in_java diff --git a/Krushkals_algorithm_in_java b/Krushkals_algorithm_in_java new file mode 100644 index 0000000..e0b75ef --- /dev/null +++ b/Krushkals_algorithm_in_java @@ -0,0 +1,187 @@ +// Java program for Kruskal's algorithm to find Minimum Spanning Tree of a given connected, undirected and weighted graph + +import java.io.*; +import java.lang.*; +import java.util.*; + +class Graph { + + // A class to represent a graph edge + class Edge implements Comparable { + int src, dest, weight; + + // Comparator function used for + // sorting edgesbased on their weight + public int compareTo(Edge compareEdge) + { + return this.weight - compareEdge.weight; + } + }; + + // A class to represent a subset for + // union-find + class subset { + int parent, rank; + }; + + int V, E; // V-> no. of vertices & E->no.of edges + Edge edge[]; // collection of all edges + + // Creates a graph with V vertices and E edges + Graph(int v, int e) + { + V = v; + E = e; + edge = new Edge[E]; + for (int i = 0; i < e; ++i) + edge[i] = new Edge(); + } + + // A utility function to find set of an + // element i (uses path compression technique) + int find(subset subsets[], int i) + { + // find root and make root as parent of i + // (path compression) + if (subsets[i].parent != i) + subsets[i].parent + = find(subsets, subsets[i].parent); + + return subsets[i].parent; + } + + // A function that does union of two sets + // of x and y (uses union by rank) + void Union(subset subsets[], int x, int y) + { + int xroot = find(subsets, x); + int yroot = find(subsets, y); + + // Attach smaller rank tree under root + // of high rank tree (Union by Rank) + if (subsets[xroot].rank < subsets[yroot].rank) + subsets[xroot].parent = yroot; + else if (subsets[xroot].rank > subsets[yroot].rank) + subsets[yroot].parent = xroot; + + // If ranks are same, then make one as + // root and increment its rank by one + else { + subsets[yroot].parent = xroot; + subsets[xroot].rank++; + } + } + + // The main function to construct MST using Kruskal's + // algorithm + void KruskalMST() + { + // This will store the resultant MST + Edge result[] = new Edge[V]; + + // An index variable, used for result[] + int e = 0; + + // An index variable, used for sorted edges + int i = 0; + for (i = 0; i < V; ++i) + result[i] = new Edge(); + + // Step 1: Sort all the edges in non-decreasing + // order of their weight. If we are not allowed to + // change the given graph, we can create a copy of + // array of edges + Arrays.sort(edge); + + // Allocate memory for creating V subsets + subset subsets[] = new subset[V]; + for (i = 0; i < V; ++i) + subsets[i] = new subset(); + + // Create V subsets with single elements + for (int v = 0; v < V; ++v) { + subsets[v].parent = v; + subsets[v].rank = 0; + } + + i = 0; // Index used to pick next edge + + // Number of edges to be taken is equal to V-1 + while (e < V - 1) { + // Step 2: Pick the smallest edge. And increment + // the index for next iteration + Edge next_edge = edge[i++]; + + int x = find(subsets, next_edge.src); + int y = find(subsets, next_edge.dest); + + // If including this edge doesn't cause cycle, + // include it in result and increment the index + // of result for next edge + if (x != y) { + result[e++] = next_edge; + Union(subsets, x, y); + } + // Else discard the next_edge + } + + // print the contents of result[] to display + // the built MST + System.out.println("Following are the edges in " + + "the constructed MST"); + int minimumCost = 0; + for (i = 0; i < e; ++i) { + System.out.println(result[i].src + " -- " + + result[i].dest + + " == " + result[i].weight); + minimumCost += result[i].weight; + } + System.out.println("Minimum Cost Spanning Tree " + + minimumCost); + } + + // Driver's Code + public static void main(String[] args) + { + + /* Let us create following weighted graph + 10 + 0--------1 + | \ | + 6| 5\ |15 + | \ | + 2--------3 + 4 */ + int V = 4; // Number of vertices in graph + int E = 5; // Number of edges in graph + Graph graph = new Graph(V, E); + + // add edge 0-1 + graph.edge[0].src = 0; + graph.edge[0].dest = 1; + graph.edge[0].weight = 10; + + // add edge 0-2 + graph.edge[1].src = 0; + graph.edge[1].dest = 2; + graph.edge[1].weight = 6; + + // add edge 0-3 + graph.edge[2].src = 0; + graph.edge[2].dest = 3; + graph.edge[2].weight = 5; + + // add edge 1-3 + graph.edge[3].src = 1; + graph.edge[3].dest = 3; + graph.edge[3].weight = 15; + + // add edge 2-3 + graph.edge[4].src = 2; + graph.edge[4].dest = 3; + graph.edge[4].weight = 4; + + // Function call + graph.KruskalMST(); + } +} From 20a645fccb2715846c73193422c2b7177683d7f1 Mon Sep 17 00:00:00 2001 From: NIVED P V <92683901+nivedpv21040@users.noreply.github.com> Date: Sat, 1 Oct 2022 23:22:12 +0530 Subject: [PATCH 132/278] Create reversing array --- program/reversing array | 1 + 1 file changed, 1 insertion(+) create mode 100644 program/reversing array diff --git a/program/reversing array b/program/reversing array new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/program/reversing array @@ -0,0 +1 @@ + From 5aa7652105ef6aef6505df38bea731714226ccd1 Mon Sep 17 00:00:00 2001 From: NIVED P V <92683901+nivedpv21040@users.noreply.github.com> Date: Sat, 1 Oct 2022 23:23:03 +0530 Subject: [PATCH 133/278] reversing array --- program/reversing array.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 program/reversing array.py diff --git a/program/reversing array.py b/program/reversing array.py new file mode 100644 index 0000000..7df67fc --- /dev/null +++ b/program/reversing array.py @@ -0,0 +1,6 @@ +from array import * +array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3]) +print("Original array: "+str(array_num)) +array_num.reverse() +print("Reverse the order of the items:") +print(str(array_num)) \ No newline at end of file From 09ba37069bc1b0cf24e06e23a12bbc3a4515cf38 Mon Sep 17 00:00:00 2001 From: Arka90 <64225385+Arka90@users.noreply.github.com> Date: Sun, 2 Oct 2022 00:30:09 +0530 Subject: [PATCH 134/278] Tic tac toe game --- Java Games/Board.java | 63 ++++++++++++++++++++++++++++++++++++++++++ Java Games/Player.java | 33 ++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 Java Games/Board.java create mode 100644 Java Games/Player.java diff --git a/Java Games/Board.java b/Java Games/Board.java new file mode 100644 index 0000000..32c1d5c --- /dev/null +++ b/Java Games/Board.java @@ -0,0 +1,63 @@ +public class Board { +private char board[][]; +private int boardSize = 3; +private char p1Symbol, p2Symbol; +private int count; +public final static int PLAYER_1_WINS = 1; +public final static int PLAYER_2_WINS = 2; +public final static int DRAW = 3; +public final static int INCOMPLETE = 4; +public final static int INVALID = 5; + +public Board(char p1Symbol, char p2Symbol){ +board = new char[boardSize][boardSize]; +for(int i =0; i < boardSize; i++){ +for(int j =0; j < boardSize; j++){ +board[i][j] = ' '; +} +} +this.p1Symbol = p1Symbol; +this.p2Symbol = p2Symbol; +} +public int move(char symbol, int x, int y) { +if(x < 0 || x >= boardSize || y < 0 || y >= boardSize ||board[x][y] != EMPTY){ +return INVALIDMOVE; +} + +board[x][y] = symbol; +count++; + +// Check Row +if(board[x][0] == board[x][1] && board[x][0] == board[x][2]){ +return symbol == p1Symbol ? PLAYER1WINS :PLAYER2WINS; +} +// Check Col +if(board[0][y] == board[1][y] && board[0][y] == board[2][y]){ +return symbol == p1Symbol ? PLAYER1WINS :PLAYER2WINS; +} +// First Diagonal +if(board[0][0] != EMPTY && board[0][0] == board[1][1] && board[0][0] == board[2][2]){ +return symbol == p1Symbol ? PLAYER1WINS :PLAYER2WINS; +} +// Second Diagonal +if(board[0][2] != EMPTY && board[0][2] == board[1][1] && board[0][2] == board[2][0]){ +return symbol == p1Symbol ? PLAYER1WINS :PLAYER2WINS; +} + +if(count == boardSize * boardSize){ +return DRAW; +} +return INCOMPLETE; +} +public void print() { +System.out.println("---------------"); +for(int i =0; i < boardSize; i++){ +for(int j =0; j < boardSize; j++){ +System.out.print("| " + board[i][j] + " |"); +} +System.out.println(); +} +System.out.println(); +System.out.println("---------------"); +} +} \ No newline at end of file diff --git a/Java Games/Player.java b/Java Games/Player.java new file mode 100644 index 0000000..1b8caa5 --- /dev/null +++ b/Java Games/Player.java @@ -0,0 +1,33 @@ +package tictactoe; + +public class Player { + +private String name; +private char symbol; + +public Player(String name, char symbol) { +setName(name); +setSymbol(symbol); +} + +public void setName(String name) { + +if(!name.isEmpty()) { +this.name = name; +} +} + +public String getName() { +return this.name; +} + +public void setSymbol(char symbol) { + if(symbol != '\0') { +this. symbol = symbol; +} +} + +public char getSymbol() { +return this.symbol; +} +} \ No newline at end of file From 475fcff457f2dc3c309624461a9af6311aed0936 Mon Sep 17 00:00:00 2001 From: Suraj Singh <103835667+suraj-s13@users.noreply.github.com> Date: Sun, 2 Oct 2022 00:36:10 +0530 Subject: [PATCH 135/278] Created a tic-tac-toe game using python Using python and tkinter. --- Python/tic-tac-toe.py | 190 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 190 insertions(+) create mode 100644 Python/tic-tac-toe.py diff --git a/Python/tic-tac-toe.py b/Python/tic-tac-toe.py new file mode 100644 index 0000000..ca0a9d8 --- /dev/null +++ b/Python/tic-tac-toe.py @@ -0,0 +1,190 @@ +import tkinter as tk +from itertools import cycle +from tkinter import font +from typing import NamedTuple + +class Player(NamedTuple): + label: str + color: str + +class Move(NamedTuple): + row: int + col: int + label: str = "" + +BOARD_SIZE = 3 +DEFAULT_PLAYERS = ( + Player(label="X", color="blue"), + Player(label="O", color="green"), +) + +class TicTacToeGame: + def __init__(self, players=DEFAULT_PLAYERS, board_size=BOARD_SIZE): + self._players = cycle(players) + self.board_size = board_size + self.current_player = next(self._players) + self.winner_combo = [] + self._current_moves = [] + self._has_winner = False + self._winning_combos = [] + self._setup_board() + + def _setup_board(self): + self._current_moves = [ + [Move(row, col) for col in range(self.board_size)] + for row in range(self.board_size) + ] + self._winning_combos = self._get_winning_combos() + + def _get_winning_combos(self): + rows = [ + [(move.row, move.col) for move in row] + for row in self._current_moves + ] + columns = [list(col) for col in zip(*rows)] + first_diagonal = [row[i] for i, row in enumerate(rows)] + second_diagonal = [col[j] for j, col in enumerate(reversed(columns))] + return rows + columns + [first_diagonal, second_diagonal] + + def toggle_player(self): + """Return a toggled player.""" + self.current_player = next(self._players) + + def is_valid_move(self, move): + """Return True if move is valid, and False otherwise.""" + row, col = move.row, move.col + move_was_not_played = self._current_moves[row][col].label == "" + no_winner = not self._has_winner + return no_winner and move_was_not_played + + def process_move(self, move): + """Process the current move and check if it's a win.""" + row, col = move.row, move.col + self._current_moves[row][col] = move + for combo in self._winning_combos: + results = set(self._current_moves[n][m].label for n, m in combo) + is_win = (len(results) == 1) and ("" not in results) + if is_win: + self._has_winner = True + self.winner_combo = combo + break + + def has_winner(self): + """Return True if the game has a winner, and False otherwise.""" + return self._has_winner + + def is_tied(self): + """Return True if the game is tied, and False otherwise.""" + no_winner = not self._has_winner + played_moves = ( + move.label for row in self._current_moves for move in row + ) + return no_winner and all(played_moves) + + def reset_game(self): + """Reset the game state to play again.""" + for row, row_content in enumerate(self._current_moves): + for col, _ in enumerate(row_content): + row_content[col] = Move(row, col) + self._has_winner = False + self.winner_combo = [] + +class TicTacToeBoard(tk.Tk): + def __init__(self, game): + super().__init__() + self.title("Tic-Tac-Toe Game") + self._cells = {} + self._game = game + self._create_menu() + self._create_board_display() + self._create_board_grid() + + def _create_menu(self): + menu_bar = tk.Menu(master=self) + self.config(menu=menu_bar) + file_menu = tk.Menu(master=menu_bar) + file_menu.add_command(label="Play Again", command=self.reset_board) + file_menu.add_separator() + file_menu.add_command(label="Exit", command=quit) + menu_bar.add_cascade(label="File", menu=file_menu) + + def _create_board_display(self): + display_frame = tk.Frame(master=self) + display_frame.pack(fill=tk.X) + self.display = tk.Label( + master=display_frame, + text="Ready?", + font=font.Font(size=28, weight="bold"), + ) + self.display.pack() + + def _create_board_grid(self): + grid_frame = tk.Frame(master=self) + grid_frame.pack() + for row in range(self._game.board_size): + self.rowconfigure(row, weight=1, minsize=50) + self.columnconfigure(row, weight=1, minsize=75) + for col in range(self._game.board_size): + button = tk.Button( + master=grid_frame, + text="", + font=font.Font(size=36, weight="bold"), + fg="black", + width=3, + height=2, + highlightbackground="lightblue", + ) + self._cells[button] = (row, col) + button.bind("", self.play) + button.grid(row=row, column=col, padx=5, pady=5, sticky="nsew") + + def play(self, event): + """Handle a player's move.""" + clicked_btn = event.widget + row, col = self._cells[clicked_btn] + move = Move(row, col, self._game.current_player.label) + if self._game.is_valid_move(move): + self._update_button(clicked_btn) + self._game.process_move(move) + if self._game.is_tied(): + self._update_display(msg="Tied game!", color="red") + elif self._game.has_winner(): + self._highlight_cells() + msg = f'Player "{self._game.current_player.label}" won!' + color = self._game.current_player.color + self._update_display(msg, color) + else: + self._game.toggle_player() + msg = f"{self._game.current_player.label}'s turn" + self._update_display(msg) + + def _update_button(self, clicked_btn): + clicked_btn.config(text=self._game.current_player.label) + clicked_btn.config(fg=self._game.current_player.color) + + def _update_display(self, msg, color="black"): + self.display["text"] = msg + self.display["fg"] = color + + def _highlight_cells(self): + for button, coordinates in self._cells.items(): + if coordinates in self._game.winner_combo: + button.config(highlightbackground="red") + + def reset_board(self): + """Reset the game's board to play again.""" + self._game.reset_game() + self._update_display(msg="Ready?") + for button in self._cells.keys(): + button.config(highlightbackground="lightblue") + button.config(text="") + button.config(fg="black") + +def main(): + """Create the game's board and run its main loop.""" + game = TicTacToeGame() + board = TicTacToeBoard(game) + board.mainloop() + +if __name__ == "__main__": + main() From 257b0e39b181f2bfbe6df2feb2bab9040cb542fa Mon Sep 17 00:00:00 2001 From: ra015 <70957876+exploe08@users.noreply.github.com> Date: Sun, 2 Oct 2022 01:17:52 +0530 Subject: [PATCH 136/278] hacktoberfest-2022 please add my file to your repository with label as hacktoberfest --- Javascript/Linear_Search.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Javascript/Linear_Search.js diff --git a/Javascript/Linear_Search.js b/Javascript/Linear_Search.js new file mode 100644 index 0000000..64cfab6 --- /dev/null +++ b/Javascript/Linear_Search.js @@ -0,0 +1,13 @@ +const array = [3, 8, 12, 6, 10, 2]; + +function checkForN(arr, n) { + for(let i = 0; i < array.length; i++) { + if (n === array[i]) { + return `${true} ${n} exists at index ${i}`; + } + } + + return `${false} ${n} does not exist in the given array.`; +} + +checkForN(array, 10); \ No newline at end of file From c4ce6a67b0d9a1624fcd46faad06d8fc6b00651b Mon Sep 17 00:00:00 2001 From: ra015 <70957876+exploe08@users.noreply.github.com> Date: Sun, 2 Oct 2022 01:23:09 +0530 Subject: [PATCH 137/278] Delete Linear_Search.js --- Javascript/Linear_Search.js | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 Javascript/Linear_Search.js diff --git a/Javascript/Linear_Search.js b/Javascript/Linear_Search.js deleted file mode 100644 index 64cfab6..0000000 --- a/Javascript/Linear_Search.js +++ /dev/null @@ -1,13 +0,0 @@ -const array = [3, 8, 12, 6, 10, 2]; - -function checkForN(arr, n) { - for(let i = 0; i < array.length; i++) { - if (n === array[i]) { - return `${true} ${n} exists at index ${i}`; - } - } - - return `${false} ${n} does not exist in the given array.`; -} - -checkForN(array, 10); \ No newline at end of file From d3e4fd4670de09d548612a35003cb2bcb8fb3197 Mon Sep 17 00:00:00 2001 From: ra015 <70957876+exploe08@users.noreply.github.com> Date: Sun, 2 Oct 2022 01:24:43 +0530 Subject: [PATCH 138/278] Linear Search --- Javascript/linearSearch.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Javascript/linearSearch.js diff --git a/Javascript/linearSearch.js b/Javascript/linearSearch.js new file mode 100644 index 0000000..64cfab6 --- /dev/null +++ b/Javascript/linearSearch.js @@ -0,0 +1,13 @@ +const array = [3, 8, 12, 6, 10, 2]; + +function checkForN(arr, n) { + for(let i = 0; i < array.length; i++) { + if (n === array[i]) { + return `${true} ${n} exists at index ${i}`; + } + } + + return `${false} ${n} does not exist in the given array.`; +} + +checkForN(array, 10); \ No newline at end of file From 5e372bc8df5d0f7fb5d294a17057c0748a54e26f Mon Sep 17 00:00:00 2001 From: Awdhesh Kumar <100534409+awdhesh-kumar27@users.noreply.github.com> Date: Sun, 2 Oct 2022 01:30:12 +0530 Subject: [PATCH 139/278] added antiDiagonalPattern.cpp added antiDiagonalPattern.cpp --- CPP/antiDiagonalPattern.cpp | 60 +++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 CPP/antiDiagonalPattern.cpp diff --git a/CPP/antiDiagonalPattern.cpp b/CPP/antiDiagonalPattern.cpp new file mode 100644 index 0000000..a88c4b3 --- /dev/null +++ b/CPP/antiDiagonalPattern.cpp @@ -0,0 +1,60 @@ +#include +using namespace std; + + +vector antiDiagonalPattern(vector>&matrix) + { + vector>arr; + int n = matrix.size(); + int m= matrix[0].size(); + + for(int j = 0;jtemp; + for(auto x : arr){ + int i = x.first; + int j = x.second; + + while(i=0){ + temp.push_back(matrix[i][j]); + i++; + j--; + } + } + return temp; + } + + + +void print(vector&arr){ + for(auto x : arr){ + + cout<>matrix; + int n; + cin>>n; + for(int i = 0;itemp; + for(int j = 0;j>val; + temp.push_back(val); + } + matrix.push_back(temp); + } + vectorans; + ans = antiDiagonalPattern(matrix); + cout<<"AntiDiagonal Pattern : \n"; + print(ans); + return 0; +} + From 6d71c90c3ed090e4f8326ae1fbc494ceee0d17dc Mon Sep 17 00:00:00 2001 From: Nipun Agarwal Date: Sun, 2 Oct 2022 01:38:06 +0530 Subject: [PATCH 140/278] Add files via upload --- fds 2.ipynb | 540 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 540 insertions(+) create mode 100644 fds 2.ipynb diff --git a/fds 2.ipynb b/fds 2.ipynb new file mode 100644 index 0000000..43dafa5 --- /dev/null +++ b/fds 2.ipynb @@ -0,0 +1,540 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "f8649652", + "metadata": {}, + "source": [ + "# functions/module in python" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "1d1a7c97", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "value of n=4\n", + "16.0\n" + ] + } + ], + "source": [ + "#write a function which finds square of a number\n", + "def fun(n):\n", + " return (n*n)\n", + "n=input(\"value of n=\")\n", + "n=float(n)\n", + "c=fun(n) #--> function call\n", + "print(c)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "c58237ec", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "value of n=2\n", + "16.0\n" + ] + } + ], + "source": [ + "#nesting of function call\n", + "def fun(n):\n", + " return (n*n)\n", + "n=input(\"value of n=\")\n", + "n=float(n)\n", + "c=fun(fun(n)) #--> nesting of function call\n", + "print(c)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "5737c287", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "4\n" + ] + } + ], + "source": [ + "#another way to the same problem\n", + "def fun(n):\n", + " print(n*n)\n", + "fun(2)" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "42340b13", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "a=4\n", + "b=8\n", + "c=9\n", + "d=2\n", + "9\n" + ] + } + ], + "source": [ + "#write a function to find maximum number between four numbers\n", + "def max(x,y):\n", + " if x>y:\n", + " return(x)\n", + " else: \n", + " return(y)\n", + "a=input(\"a=\")\n", + "b=input(\"b=\")\n", + "c=input(\"c=\")\n", + "d=input(\"d=\")\n", + "\n", + "a=int(a)\n", + "b=int(b)\n", + "c=int(c)\n", + "d=int(d)\n", + "\n", + "m=max(a,b)\n", + "m=max(m,c)\n", + "m=max(m,d)\n", + "\n", + "print (m)\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "db402092", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "welcome to python\n" + ] + } + ], + "source": [ + "#develop a function which prints welcome to python\n", + "def fun():\n", + " print(\"welcome to python\")\n", + "fun() " + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "6fa968de", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "100\n" + ] + } + ], + "source": [ + "def f1(x):\n", + " x=x+1\n", + " print(x)\n", + "f1(99) " + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "6a907c54", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[100, 20, 30, 40, 50]\n" + ] + } + ], + "source": [ + "def f2(x):\n", + " x[0]=100\n", + "\n", + "a=[10,20,30,40,50]\n", + "f2(a)\n", + "print(a)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "829a1135", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(10, 20, 30)\n" + ] + } + ], + "source": [ + "#variable number of parameters\n", + "def f3(*args):\n", + " print(args)\n", + "\n", + "f3(10,20,30) " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "e19231e4", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "16\n" + ] + } + ], + "source": [ + "#lambda function\n", + "z=lambda x:x*x\n", + "print(z(4))" + ] + }, + { + "cell_type": "markdown", + "id": "feb0be9c", + "metadata": {}, + "source": [ + "whenever a function has another function as parameter ,it is known as higher order function,example-> filter(function,list), here function is a parameter" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "4859f994", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[10, 2, 8]\n" + ] + } + ], + "source": [ + "#application of lambda function -> they are used in higher order function\n", + "# write a function to separate even numbers from a given list of numbers\n", + "# a=[10,2,13,7,15,8]\n", + "\n", + "a=[10,2,13,7,15,8]\n", + "b=list(filter(lambda x:x%2==0,a)) #of form filter(fun,list)\n", + "print(b)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "8848a3c5", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[13, 7, 15]\n" + ] + } + ], + "source": [ + "#for odd numbers\n", + "a=[10,2,13,7,15,8]\n", + "b=list(filter(lambda x:x%2!=0,a)) \n", + "print(b)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "3ccf89af", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[75, 66, 99, 100]\n" + ] + } + ], + "source": [ + "#given a list a,create a list b which contains all the numbers>50\n", + "a=[15,75,66,99,2,36,100]\n", + "b=list(filter(lambda x:x>=50,a))\n", + "print(b)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "469887f6", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[75, 66, 99, 100]\n" + ] + } + ], + "source": [ + "#another way to do the same question\n", + "a=[15,75,66,99,2,36,100]\n", + "b=[]\n", + "for x in a:\n", + " if x>50:\n", + " b.append(x)\n", + "print(b) " + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "cb2ecaaf", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[100, 900, 4, 49, 64, 16]\n" + ] + } + ], + "source": [ + "# map function -> higher order function\n", + "# create a list using function which contains squares of all the\n", + "#numbers given a list\n", + "a=[10,30,2,7,8,4]\n", + "b=list(map(lambda x:x**2,a))\n", + "print(b)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "558c0edd", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[11, 22, 33, 44, 55]\n" + ] + } + ], + "source": [ + "#given list a and b,create a c list which contains a+b\n", + "a=[1,2,3,4,5]\n", + "b=[10,20,30,40,50] #if there is less no. of elements,that no. is printed\n", + "c=list(map(lambda x,y:x+y,a,b))\n", + "print(c)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "6f48b469", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 4, 9, 16, 25]\n" + ] + } + ], + "source": [ + "#we can use a named function instead of lambda\n", + "def square(x):\n", + " return x*x\n", + "a=[1,2,3,4,5]\n", + "b=list(map(square,a))\n", + "print(b)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "61a635f9", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "60\n" + ] + } + ], + "source": [ + "# create a program to add many numbers ,using variable number of parameters\n", + "def sum(*args):\n", + " s=0\n", + " for x in args:\n", + " s=s+x\n", + " return s\n", + "print(sum(10,50))\n" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "6ba8470d", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "70\n" + ] + } + ], + "source": [ + "#using positional and variable number of parameters together\n", + "def sum(x,y,*args):\n", + " s=0\n", + " s=x+y\n", + " for e in args:\n", + " s=s+e\n", + " return s\n", + "print(sum(10,20,40))\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "0be12c73", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10 20 (30, 40) 50 70 {'m': 60, 'n': 90}\n" + ] + } + ], + "source": [ + "def fun(x,y,*args,p,q,**kwargs): #**kwargs is used to print dict\n", + " print(x,y,args,p,q,kwargs)\n", + "fun(10,20,30,40,p=50,q=70,m=60,n=90) " + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "80d8ce2b", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "16\n" + ] + } + ], + "source": [ + "#default parameters\n", + "def add(x,y=6):\n", + " return x+y\n", + "print(add(10))" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "75502de2", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "108\n" + ] + } + ], + "source": [ + "def add(x,y):\n", + " return(x+y)\n", + "z=(add(100,8))\n", + "print(z)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3d97f0d1", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.7" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} From 241adbf91c01a70119faaaa37b93ad568bfa708b Mon Sep 17 00:00:00 2001 From: mind8hunter <67045160+mind8hunter@users.noreply.github.com> Date: Sun, 2 Oct 2022 02:03:17 +0530 Subject: [PATCH 141/278] Add files via upload --- Python/insta_amazon_snapchat_facebook.txt | 87 +++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Python/insta_amazon_snapchat_facebook.txt diff --git a/Python/insta_amazon_snapchat_facebook.txt b/Python/insta_amazon_snapchat_facebook.txt new file mode 100644 index 0000000..4aabec3 --- /dev/null +++ b/Python/insta_amazon_snapchat_facebook.txt @@ -0,0 +1,87 @@ +import requests +import trio +import httpx +from ignorant.modules.social_media.instagram import instagram +from ignorant.modules.shopping.amazon import amazon + +phone__number = int(input("Enter the phone number: ")) +url = "https://accounts.snapchat.com/accounts/validate_phone_number" +cookies = { + "xsrf_token":'BtpZ6sL9OenEJJYbQXFEsg' + } +headers = { + "accept": "*/*", + "accept-encoding": "gzip, deflate, br", + "accept-language": "ar,en;q=0.9,en-US;q=0.8", + "content-type": "application/x-www-form-urlencoded; charset=utf-8", + "sec-fetch-dest": "empty", + "sec-fetch-mode": "same-origin", + "sec-fetch-site": "same-origin", + "user-agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Mobile Safari/537.36" + } +data = {"phone_country_code":"IN","phone_number":phone__number,"xsrf_token":"BtpZ6sL9OenEJJYbQXFEsg"} +req = requests.post(url,data=data,headers=headers,cookies=cookies).json() +text = str(req) + #print(text) +if text.find('OK')>=0: + print(f"{phone__number}==> Not Exist In Snapchat") +else: + print(f"{phone__number}==> Exist In Snapchat") +email = phone__number +x = requests.Session() + +h={"origin": "https://www.facebook.com","referer":"https://www.facebook.com/login/identify/?ctx=recover&ars=facebook_login&from_login_screen=0","sec-fetch-dest": "empty","sec-fetch-mode": "cors","sec-fetch-site": "same-origin","sec-gpc": "1","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.72 Safari/537.36"} +r = x.get("https://m.facebook.com/login",headers=h) +a = r.text.split('type="hidden" name="jazoest" value="', 1)[1] +jaz = a.split('"', 1)[0] +b = r.text.split(' Exist In Facebook") +else: + print(f"{email}==> Not Exist In Facebook") +async def main(): + phone=phone__number + country_code="91" + client = httpx.AsyncClient() + out = [] + await instagram(phone, country_code, client, out) + y=str(out) + if "True" in y: + print(f"{email}==>> Exist In Instagram") + else : + print(f"{email}==>> Not Exist In Instagram") + # print(y) + await amazon(phone, country_code, client, out) + z=str(out) + if "True" in z: + print(f"{email}==>> Exist In Amazon") + else : + print(f"{email}==>> Not Exist To Amazon") + await client.aclose() +trio.run(main) From 82ab8b7510b5bdfc47e3b6fae30733665ba0a896 Mon Sep 17 00:00:00 2001 From: batrakeshav10 <71037843+batrakeshav10@users.noreply.github.com> Date: Sun, 2 Oct 2022 04:05:22 +0530 Subject: [PATCH 142/278] Create binary_conversions1.c please add my file to your repository with label as hacktoberfest --- binary_conversions1.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 binary_conversions1.c diff --git a/binary_conversions1.c b/binary_conversions1.c new file mode 100644 index 0000000..eb4c6a1 --- /dev/null +++ b/binary_conversions1.c @@ -0,0 +1,26 @@ +#include +#include +#include + +void main() +{ + int n,i=0,z,j; + scanf("%d",&n); + int *a = (int*)malloc(sizeof(int)); + + while(n>0) + { + z=n%2; + a[i]=z; + i++; + n/=2; + } + i--; + while(i>=0) + { + printf("%d",a[i]); + i--; + } +} +Footer +© 2022 GitHub, Inc. From f62f2fe074d0dac5a2511b727d27bee9cd253b66 Mon Sep 17 00:00:00 2001 From: batrakeshav10 <71037843+batrakeshav10@users.noreply.github.com> Date: Sun, 2 Oct 2022 04:44:16 +0530 Subject: [PATCH 143/278] Update 4Sum.cpp please add my file to your repository with label as hacktoberfest --- 4_Sum.cpp | 92 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 4_Sum.cpp diff --git a/4_Sum.cpp b/4_Sum.cpp new file mode 100644 index 0000000..792ffaa --- /dev/null +++ b/4_Sum.cpp @@ -0,0 +1,92 @@ + + /*this code is edited by batrakeshav10 + sir please accept my pull request and guide me, + so that i can win hactoberfest tshirt */ +// Question- + +/* Suppose we have an array of numbers. It stores n integers, there are four elements a, b, c and d in the array. We have another target value, such that a + b + c + d = target. Find all the unique quadruplets in the array which satisfies the situation. So if the array is like [-1,0,1,2,0,-2] and target is 0, then the result will be [[-1, 0, 0, 1],[-2, -1, 1, 2], [-2, 0, 0, 2]] + Input- + [1,0,-1,0,-2,2] + 0 + Output +[[1,2,-1,-2],[0,2,0,-2],[0,1,0,-1]] */ + + + +#include +using namespace std; + + +class Solution { +public: + void addAll(vector < vector >& res, vector < vector >& temp){ + for(int i = 0; i < temp.size(); i++)res.push_back(temp[i]); + } + vector> fourSum(vector& nums, int target) { + sort(nums.begin(), nums.end()); + return kSum(nums, 0, 4, target); + } + vector < vector > kSum(vector & arr, int start, int k, int target){ + vector < vector > res; + if(k == 2){ + int left = start; + int right = arr.size() - 1; + vector temp(2); + while(left < right){ + if(arr[left] + arr[right] == target){ + temp[0] = arr[left]; + temp[1] = arr[right]; + res.push_back(temp); + while(left < right && arr[left] == arr[left + 1])left++; + while(left < right && arr[right] == arr[right - 1])right--; + left++; + right--; + } + + /*this code is edited by batrakeshav10 + sir please accept my pull request and guide me, + so that i can win hactoberfest tshirt */ + else if(arr[left] + arr[right] > target)right--; + else left ++; + } + } + else{ + for(int i = start; i < (int)arr.size() - k + 1; i++){ + if(i > start && arr[i] == arr[i - 1])continue; + vector < vector > temp = kSum(arr, i + 1, k - 1, target - arr[i]); + for(int j = 0; j < temp.size(); j++){ + temp[j].push_back(arr[i]); + } + addAll(res, temp); + } + } + return res; + } +}; + + + +void print_vector(vector > v){ + cout << "["; + for(int i = 0; i v = {1,0,-1,0,-2,2}; + print_vector(ob.fourSum(v, 0)); +} + + /*this code is edited by batrakeshav10 + sir please accept my pull request and guide me, + so that i can win hactoberfest tshirt */ From 2918165742f012f2e34ad5e00c71d98f9a2ac371 Mon Sep 17 00:00:00 2001 From: Arie <91861324+ariear@users.noreply.github.com> Date: Sun, 2 Oct 2022 09:21:11 +0700 Subject: [PATCH 144/278] add: Pascal's Triangle js --- Javascript/pascalTriangle.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Javascript/pascalTriangle.js diff --git a/Javascript/pascalTriangle.js b/Javascript/pascalTriangle.js new file mode 100644 index 0000000..4fda019 --- /dev/null +++ b/Javascript/pascalTriangle.js @@ -0,0 +1,30 @@ +const generate = (numRows) => { + let triangle = [[1], [1,1]] + + if(numRows === 0){ + return [] + }else if(numRows == 1){ + return [[1]] + }else if(numRows == 2){ + return [[1], [1,1]] + }else{ + for(let i = 2; i < numRows; i++){ + addRow(triangle) + } + } + return triangle +} + +const addRow = (triangle) => { + let previous = triangle[triangle.length - 1] + let newRow = [1] + for(let i = 0; i < previous.length - 1; i++){ + let current = previous[i] + let next = previous[i+1] + newRow.push(current + next) + } + newRow.push(1) + return triangle.push(newRow) +} + +console.log(generate(10)) From b3b67e515b37c1df9abe5ef0e93f425b04362402 Mon Sep 17 00:00:00 2001 From: shubham-7430 <114841302+shubham-7430@users.noreply.github.com> Date: Sun, 2 Oct 2022 08:16:41 +0530 Subject: [PATCH 145/278] BinaryTree --- bst.cpp | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 bst.cpp diff --git a/bst.cpp b/bst.cpp new file mode 100644 index 0000000..6bcb688 --- /dev/null +++ b/bst.cpp @@ -0,0 +1,57 @@ +#include +using namespace std; + +class Node { + public: + int data; + Node* left; + Node* right; + + // Val is the key or the value that + // has to be added to the data part + Node(int val) + { + data = val; + + // Left and right child for node + // will be initialized to null + left = NULL; + right = NULL; + } +}; + +int main() +{ + + /*create root*/ + Node* root = new Node(1); + /* following is the tree after above statement + + 1 + / \ + NULL NULL + */ + + root->left = new Node(2); + root->right = new Node(3); + /* 2 and 3 become left and right children of 1 + 1 + / \ + 2 3 + / \ / \ + NULL NULL NULL NULL + */ + + root->left->left = new Node(4); + /* 4 becomes left child of 2 + 1 + / \ + 2 3 + / \ / \ + 4 NULL NULL NULL + / \ + NULL NULL + */ + + return 0; +} \ No newline at end of file From 1dc2b3565758e16dafa496f8335be3d1f9f2bf7c Mon Sep 17 00:00:00 2001 From: William Luqui <88260564+Williamluqui@users.noreply.github.com> Date: Sun, 2 Oct 2022 00:46:03 -0300 Subject: [PATCH 146/278] filter --- Javascript/filter.js | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Javascript/filter.js diff --git a/Javascript/filter.js b/Javascript/filter.js new file mode 100644 index 0000000..f13e1c0 --- /dev/null +++ b/Javascript/filter.js @@ -0,0 +1,9 @@ +const users = [ + { name: 'Ada Lovelace', premium: true }, + { name: 'Grace Hopper', premium: false }, + { name: 'Alan Turing', premium: true }, + { name: 'Linus Torvalds', premium: false }, + { name: 'Margaret Hamilton', premium: true } + ] + const premiumUser = users.filter(user => user.premium) + console.log(premiumUser) From bd88f10e989ea541b71a7891349fb3b529d4742c Mon Sep 17 00:00:00 2001 From: Rishabh Jain <70846152+Rishabhjain2002@users.noreply.github.com> Date: Sun, 2 Oct 2022 09:44:54 +0530 Subject: [PATCH 147/278] Hactoberfest-2022 please add my file to your repository with label as hacktoberfest --- depthfirsstsearch c++.txt | 62 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 depthfirsstsearch c++.txt diff --git a/depthfirsstsearch c++.txt b/depthfirsstsearch c++.txt new file mode 100644 index 0000000..c00bec8 --- /dev/null +++ b/depthfirsstsearch c++.txt @@ -0,0 +1,62 @@ +// C++ program to print DFS traversal from +// a given vertex in a given graph +#include +using namespace std; + +// Graph class represents a directed graph +// using adjacency list representation +class Graph { +public: + map visited; + map > adj; + + // function to add an edge to graph + void addEdge(int v, int w); + + // DFS traversal of the vertices + // reachable from v + void DFS(int v); +}; + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +void Graph::DFS(int v) +{ + // Mark the current node as visited and + // print it + visited[v] = true; + cout << v << " "; + + // Recur for all the vertices adjacent + // to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + if (!visited[*i]) + DFS(*i); +} + +// Driver's code +int main() +{ + // Create a graph given in the above diagram + Graph g; + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + cout << "Following is Depth First Traversal" + " (starting from vertex 2) \n"; + + // Function call + g.DFS(2); + + return 0; +} + +// improved by Vishnudev C From 8b3689fb144da11348085204e7681b54ea043342 Mon Sep 17 00:00:00 2001 From: Rishabh Jain <70846152+Rishabhjain2002@users.noreply.github.com> Date: Sun, 2 Oct 2022 09:49:28 +0530 Subject: [PATCH 148/278] Hactoberfest-2022 please add my file to your repository with label as hacktoberfest --- calculate number of nodes dfs method.txt | 87 ++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 calculate number of nodes dfs method.txt diff --git a/calculate number of nodes dfs method.txt b/calculate number of nodes dfs method.txt new file mode 100644 index 0000000..4d739b2 --- /dev/null +++ b/calculate number of nodes dfs method.txt @@ -0,0 +1,87 @@ +// C++ program for the above approach + +#include +using namespace std; + +// Function to return the count of nodes +// in the path from source to destination +int dfs(int src, int dest, int* vis, + vector* adj) +{ + + // Mark the node visited + vis[src] = 1; + + // If dest is reached + if (src == dest) { + return 1; + } + + // Traverse all adjacent nodes + for (int u : adj[src]) { + + // If not already visited + if (!vis[u]) { + + int temp = dfs(u, dest, vis, adj); + + // If there is path, then + // include the current node + if (temp != 0) { + + return temp + 1; + } + } + } + + // Return 0 if there is no path + // between src and dest through + // the current node + return 0; +} + +// Function to return the +// count of nodes between two +// given vertices of the acyclic Graph +int countNodes(int V, int E, int src, int dest, + int edges[][2]) +{ + // Initialize an adjacency list + vector adj[V + 1]; + + // Populate the edges in the list + for (int i = 0; i < E; i++) { + adj[edges[i][0]].push_back(edges[i][1]); + adj[edges[i][1]].push_back(edges[i][0]); + } + + // Mark all the nodes as not visited + int vis[V + 1] = { 0 }; + + // Count nodes in the path from src to dest + int count = dfs(src, dest, vis, adj); + + // Return the nodes between src and dest + return count - 2; +} + +// Driver Code +int main() +{ + // Given number of vertices and edges + int V = 8, E = 7; + + // Given source and destination vertices + int src = 5, dest = 2; + + // Given edges + int edges[][2] + = { { 1, 4 }, { 4, 5 }, + { 4, 2 }, { 2, 6 }, + { 6, 3 }, { 2, 7 }, + { 3, 8 } }; + + cout << countNodes(V, E, src, dest, edges); + + return 0; +} From bef70b763edb21869c913deefb0da5f088ad0f65 Mon Sep 17 00:00:00 2001 From: raj-hero <91920953+raj-hero@users.noreply.github.com> Date: Sun, 2 Oct 2022 09:56:24 +0530 Subject: [PATCH 149/278] Created 3sum.cpp Leetcode's 15. 3sum's solution in cpp --- CPP/3sum.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 CPP/3sum.cpp diff --git a/CPP/3sum.cpp b/CPP/3sum.cpp new file mode 100644 index 0000000..a7a4b5a --- /dev/null +++ b/CPP/3sum.cpp @@ -0,0 +1,39 @@ +// 15. 3Sum Leetcode +// problem:https://leetcode.com/problems/3sum/ +class Solution { +public: + vector> threeSum(vector& nums) + { + int n=nums.size(); + sort(nums.begin(),nums.end()); + vector>v; + if(n<3) return v; + // we use set because we do not need duplicate pairs + set >s; + // consider it as 2sum in a loop + for(int i=0;i0&&nums[i]!=nums[i-1])) + { + while(lt) --r; + } + } + } + for(auto it=s.begin();it!=s.end();++it){ + v.push_back(*it); + } + return v; + } +}; From e54199ccdfda31bb5b612d6e176181aafc4a91b0 Mon Sep 17 00:00:00 2001 From: Namgup001 <51751217+Namgup001@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:00:41 +0530 Subject: [PATCH 150/278] Create dfs.cpp Hacktoberfest-2022 please add it under the label hacktoberfest-2022 --- CPP/dfs.cpp | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 CPP/dfs.cpp diff --git a/CPP/dfs.cpp b/CPP/dfs.cpp new file mode 100644 index 0000000..0c4b412 --- /dev/null +++ b/CPP/dfs.cpp @@ -0,0 +1,58 @@ +#include +using namespace std; + +// Graph class represents a directed graph +// using adjacency list representation +class Graph { +public: + map visited; + map > adj; + + // function to add an edge to graph + void addEdge(int v, int w); + + // DFS traversal of the vertices + // reachable from v + void DFS(int v); +}; + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +void Graph::DFS(int v) +{ + // Mark the current node as visited and + // print it + visited[v] = true; + cout << v << " "; + + // Recur for all the vertices adjacent + // to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + if (!visited[*i]) + DFS(*i); +} + +// Driver's code +int main() +{ + // Create a graph given in the above diagram + Graph g; + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + cout << "Following is Depth First Traversal" + " (starting from vertex 2) \n"; + + // Function call + g.DFS(2); + + return 0; +} From b35bd17dd64ab4eae1c33fc187e60485fb636be3 Mon Sep 17 00:00:00 2001 From: Namgup001 <51751217+Namgup001@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:02:53 +0530 Subject: [PATCH 151/278] Create undir to SCC.cpp hacktoberfest-2022 please add it under the label hacktoberfest-2022 --- CPP/undir to SCC.cpp | 152 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 CPP/undir to SCC.cpp diff --git a/CPP/undir to SCC.cpp b/CPP/undir to SCC.cpp new file mode 100644 index 0000000..12f06e8 --- /dev/null +++ b/CPP/undir to SCC.cpp @@ -0,0 +1,152 @@ + +#include +using namespace std; + +// To store the assigned Edges +vector > ans; + +// Flag variable to check Bridges +int flag = 1; + +// Function to implement DFS Traversal +int dfs(vector adj[], + int* order, int* bridge_detect, + bool* mark, int v, int l) +{ + + // Mark the current node as visited + mark[v] = 1; + + // Update the order of node v + order[v] = order[l] + 1; + + // Update the bridge_detect for node v + bridge_detect[v] = order[v]; + + // Traverse the adjacency list of + // Node v + for (int i = 0; i < adj[v].size(); i++) { + int u = adj[v][i]; + + // Ignores if same edge is traversed + if (u == l) { + continue; + } + + // Ignores the edge u --> v as + // v --> u is already processed + if (order[v] < order[u]) { + continue; + } + + // Finds a back Edges, cycle present + if (mark[u]) { + + // Update the bridge_detect[v] + bridge_detect[v] + = min(order[u], + bridge_detect[v]); + } + + // Else DFS traversal for current + // node in the adjacency list + else { + + dfs(adj, order, bridge_detect, + mark, u, v); + } + + // Update the bridge_detect[v] + bridge_detect[v] + = min(bridge_detect[u], + bridge_detect[v]); + + // Store the current directed Edge + ans.push_back(make_pair(v, u)); + } + + // Condition for Bridges + if (bridge_detect[v] == order[v] + && l != 0) { + flag = 0; + } + + // Return flag + return flag; +} + +// Function to print the direction +// of edges to make graph SCCs +void convert(vector adj[], int n) +{ + + // Arrays to store the visited, + // bridge_detect and order of + // Nodes + int order[n] = { 0 }; + int bridge_detect[n] = { 0 }; + bool mark[n]; + + // Initialise marks[] as false + memset(mark, false, sizeof(mark)); + + // DFS Traversal from vertex 1 + int flag = dfs(adj, order, + bridge_detect, + mark, 1, 0); + + // If flag is zero, then Bridge + // is present in the graph + if (flag == 0) { + cout << "-1"; + } + + // Else print the direction of + // Edges assigned + else { + for (auto& it : ans) { + cout << it.first << "->" + << it.second << '\n'; + } + } +} + +// Function to create graph +void createGraph(int Edges[][2], + vector adj[], + int M) +{ + + // Traverse the Edges + for (int i = 0; i < M; i++) { + + int u = Edges[i][0]; + int v = Edges[i][1]; + + // Push the edges in an + // adjacency list + adj[u].push_back(v); + adj[v].push_back(u); + } +} + +// Driver Code +int main() +{ + // N vertices and M Edges + int N = 5, M = 6; + int Edges[M][2] + = { { 0, 1 }, { 0, 2 }, + { 1, 2 }, { 1, 4 }, + { 2, 3 }, { 3, 4 } }; + + // To create Adjacency List + vector adj[N]; + + // Create an undirected graph + createGraph(Edges, adj, M); + + // Function Call + convert(adj, N); + return 0; +} From 2011110c2b9eaf1e112fe57ca629f9c462087ffa Mon Sep 17 00:00:00 2001 From: NaprKnight <86531684+NaprKnight@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:04:58 +0530 Subject: [PATCH 152/278] Create Kosaraju using dfs.cpp hacktoberfest-2022 please add it under the label hacktoberfest-2022 --- CPP/Kosaraju using dfs.cpp | 126 +++++++++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 CPP/Kosaraju using dfs.cpp diff --git a/CPP/Kosaraju using dfs.cpp b/CPP/Kosaraju using dfs.cpp new file mode 100644 index 0000000..879e7f7 --- /dev/null +++ b/CPP/Kosaraju using dfs.cpp @@ -0,0 +1,126 @@ +#include +#include +#include +using namespace std; + +class Graph +{ + int V; // No. of vertices + list *adj; // An array of adjacency lists + + // A recursive function to print DFS + // starting from v + void DFSUtil(int v, bool visited[]); +public: + // Constructor and Destructor + Graph(int V) { this->V = V; adj = new list[V];} + ~Graph() { delete [] adj; } + + // Method to add an edge + void addEdge(int v, int w); + + // The main function that returns true if the + // graph is strongly connected, otherwise false + bool isSC(); + + // Function that returns reverse (or transpose) + // of this graph + Graph getTranspose(); +}; + +// A recursive function to print DFS starting from v +void Graph::DFSUtil(int v, bool visited[]) +{ + // Mark the current node as visited and print it + visited[v] = true; + + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + if (!visited[*i]) + DFSUtil(*i, visited); +} + +// Function that returns reverse (or transpose) of this graph +Graph Graph::getTranspose() +{ + Graph g(V); + for (int v = 0; v < V; v++) + { + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for(i = adj[v].begin(); i != adj[v].end(); ++i) + { + g.adj[*i].push_back(v); + } + } + return g; +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +// The main function that returns true if graph +// is strongly connected +bool Graph::isSC() +{ + // St1p 1: Mark all the vertices as not visited + // (For first DFS) + bool visited[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + + // Step 2: Do DFS traversal starting from first vertex. + DFSUtil(0, visited); + + // If DFS traversal doesn’t visit all vertices, + // then return false. + for (int i = 0; i < V; i++) + if (visited[i] == false) + return false; + + // Step 3: Create a reversed graph + Graph gr = getTranspose(); + + // Step 4: Mark all the vertices as not visited + // (For second DFS) + for(int i = 0; i < V; i++) + visited[i] = false; + + // Step 5: Do DFS for reversed graph starting from + // first vertex. Starting Vertex must be same starting + // point of first DFS + gr.DFSUtil(0, visited); + + // If all vertices are not visited in second DFS, then + // return false + for (int i = 0; i < V; i++) + if (visited[i] == false) + return false; + + return true; +} + +// Driver program to test above functions +int main() +{ + // Create graphs given in the above diagrams + Graph g1(5); + g1.addEdge(0, 1); + g1.addEdge(1, 2); + g1.addEdge(2, 3); + g1.addEdge(3, 0); + g1.addEdge(2, 4); + g1.addEdge(4, 2); + g1.isSC()? cout << "Yes\n" : cout << "No\n"; + + Graph g2(4); + g2.addEdge(0, 1); + g2.addEdge(1, 2); + g2.addEdge(2, 3); + g2.isSC()? cout << "Yes\n" : cout << "No\n"; + + return 0; +} From ea6bf88b8dcf0326ac9dbb0848b001e7ac5aaf35 Mon Sep 17 00:00:00 2001 From: NaprKnight <86531684+NaprKnight@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:06:11 +0530 Subject: [PATCH 153/278] Create kosaraju using bfs.cpp hacktoberfest-2022 please add it under the label hacktoberfest-2022 --- CPP/kosaraju using bfs.cpp | 145 +++++++++++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 CPP/kosaraju using bfs.cpp diff --git a/CPP/kosaraju using bfs.cpp b/CPP/kosaraju using bfs.cpp new file mode 100644 index 0000000..862197b --- /dev/null +++ b/CPP/kosaraju using bfs.cpp @@ -0,0 +1,145 @@ +#include +using namespace std; + +class Graph +{ + int V; // No. of vertices + list *adj; // An array of adjacency lists + + // A recursive function to print DFS starting from v + void BFSUtil(int v, bool visited[]); +public: + + // Constructor and Destructor + Graph(int V) { this->V = V; adj = new list[V];} + ~Graph() { delete [] adj; } + + // Method to add an edge + void addEdge(int v, int w); + + // The main function that returns true if the + // graph is strongly connected, otherwise false + bool isSC(); + + // Function that returns reverse (or transpose) + // of this graph + Graph getTranspose(); +}; + +// A recursive function to print DFS starting from v +void Graph::BFSUtil(int v, bool visited[]) +{ + // Create a queue for BFS + list queue; + + // Mark the current node as visited and enqueue it + visited[v] = true; + queue.push_back(v); + + // 'i' will be used to get all adjacent vertices + // of a vertex + list::iterator i; + + while (!queue.empty()) + { + // Dequeue a vertex from queue + v = queue.front(); + queue.pop_front(); + + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it + // visited and enqueue it + for (i = adj[v].begin(); i != adj[v].end(); ++i) + { + if (!visited[*i]) + { + visited[*i] = true; + queue.push_back(*i); + } + } + } +} + +// Function that returns reverse (or transpose) of this graph +Graph Graph::getTranspose() +{ + Graph g(V); + for (int v = 0; v < V; v++) + { + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + g.adj[*i].push_back(v); + } + return g; +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +// The main function that returns true if graph +// is strongly connected +bool Graph::isSC() +{ + // Step 1: Mark all the vertices as not + // visited (For first BFS) + bool visited[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + + // Step 2: Do BFS traversal starting + // from first vertex. + BFSUtil(0, visited); + + // If BFS traversal doesn’t visit all + // vertices, then return false. + for (int i = 0; i < V; i++) + if (visited[i] == false) + return false; + + // Step 3: Create a reversed graph + Graph gr = getTranspose(); + + // Step 4: Mark all the vertices as not + // visited (For second BFS) + for(int i = 0; i < V; i++) + visited[i] = false; + + // Step 5: Do BFS for reversed graph + // starting from first vertex. + // Starting Vertex must be same starting + // point of first DFS + gr.BFSUtil(0, visited); + + // If all vertices are not visited in + // second DFS, then return false + for (int i = 0; i < V; i++) + if (visited[i] == false) + return false; + + return true; +} + +// Driver program to test above functions +int main() +{ + // Create graphs given in the above diagrams + Graph g1(5); + g1.addEdge(0, 1); + g1.addEdge(1, 2); + g1.addEdge(2, 3); + g1.addEdge(3, 0); + g1.addEdge(2, 4); + g1.addEdge(4, 2); + g1.isSC()? cout << "Yes\n" : cout << "No\n"; + + Graph g2(4); + g2.addEdge(0, 1); + g2.addEdge(1, 2); + g2.addEdge(2, 3); + g2.isSC()? cout << "Yes\n" : cout << "No\n"; + + return 0; +} From d4956080f4e6e622bbff46df7ffe740124df5dfe Mon Sep 17 00:00:00 2001 From: Ujjawal Kumar Date: Sun, 2 Oct 2022 11:06:41 +0530 Subject: [PATCH 154/278] bubbleSort --- bubble_sort.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 bubble_sort.py diff --git a/bubble_sort.py b/bubble_sort.py new file mode 100644 index 0000000..19c8763 --- /dev/null +++ b/bubble_sort.py @@ -0,0 +1,23 @@ +def bubblesort(arr): + n=len(arr) + swapped = False + for i in range (n-1): + + for j in range (0,n-i-1): + + if arr[j]>arr[j+1]: + swapped = True + temp=arr[j] + arr[j]=arr[j+1] + arr[j+1]=temp + + if not swapped: + return + + + +arr=[23,21,34,32,12,10,10] +bubblesort(arr) +print("Sorted array :") +for i in range(len(arr)): + print(arr[i],end=" ") \ No newline at end of file From d787abd3f9ed491ebcce61f6139e7d75ba93d2e2 Mon Sep 17 00:00:00 2001 From: NaprKnight <86531684+NaprKnight@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:07:56 +0530 Subject: [PATCH 155/278] Create detect_cycle_in_direGraph.cpp hacktoberfest-2022 please add it under the label hacktoberfest-2022 --- CPP/detect_cycle_in_direGraph.cpp | 114 ++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 CPP/detect_cycle_in_direGraph.cpp diff --git a/CPP/detect_cycle_in_direGraph.cpp b/CPP/detect_cycle_in_direGraph.cpp new file mode 100644 index 0000000..24edc9e --- /dev/null +++ b/CPP/detect_cycle_in_direGraph.cpp @@ -0,0 +1,114 @@ +#include +using namespace std; + +// Class to represent a graph +class Graph { + int V; // No. of vertices' + + // Pointer to an array containing adjacency list + list* adj; + +public: + Graph(int V); // Constructor + + // function to add an edge to graph + void addEdge(int u, int v); + + // Returns true if there is a cycle in the graph + // else false. + bool isCycle(); +}; + +Graph::Graph(int V) +{ + this->V = V; + adj = new list[V]; +} + +void Graph::addEdge(int u, int v) +{ + adj[u].push_back(v); +} + +// This function returns true if there is a cycle +// in directed graph, else returns false. +bool Graph::isCycle() +{ + // Create a vector to store indegrees of all + // vertices. Initialize all indegrees as 0. + vector in_degree(V, 0); + + // Traverse adjacency lists to fill indegrees of + // vertices. This step takes O(V+E) time + for (int u = 0; u < V; u++) { + for (auto v : adj[u]) + in_degree[v]++; + } + + // Create an queue and enqueue all vertices with + // indegree 0 + queue q; + for (int i = 0; i < V; i++) + if (in_degree[i] == 0) + q.push(i); + + // Initialize count of visited vertices + // 1 For src Node + int cnt = 1; + + // Create a vector to store result (A topological + // ordering of the vertices) + vector top_order; + + // One by one dequeue vertices from queue and enqueue + // adjacents if indegree of adjacent becomes 0 + while (!q.empty()) { + + // Extract front of queue (or perform dequeue) + // and add it to topological order + int u = q.front(); + q.pop(); + top_order.push_back(u); + + // Iterate through all its neighbouring nodes + // of dequeued node u and decrease their in-degree + // by 1 + list::iterator itr; + for (itr = adj[u].begin(); itr != adj[u].end(); itr++) + + // If in-degree becomes zero, add it to queue + if (--in_degree[*itr] == 0) + { + q.push(*itr); + //while we are pushing elements to the queue we will incrementing the cnt + cnt++; + } + + + } + + // Check if there was a cycle + if (cnt != V) + return true; + else + return false; +} + +// Driver program to test above functions +int main() +{ + // Create a graph given in the above diagram + Graph g(6); + g.addEdge(0, 1); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(3, 4); + g.addEdge(4, 5); + + if (g.isCycle()) + cout << "Yes"; + else + cout << "No"; + + return 0; +} From 5c8ec97f66a3c41a2910bcc0b985e4ddd0745791 Mon Sep 17 00:00:00 2001 From: Sahil Rana <51770809+Rsr0@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:08:02 +0530 Subject: [PATCH 156/278] Create plagrismDetector.py --- Python/plagrismDetector.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Python/plagrismDetector.py diff --git a/Python/plagrismDetector.py b/Python/plagrismDetector.py new file mode 100644 index 0000000..9a5a3c6 --- /dev/null +++ b/Python/plagrismDetector.py @@ -0,0 +1,8 @@ +from difflib import SequenceMatcher + +with open("1.txt") as f1, open("2.txt") as f2: + f1Data = f1.read() + f2Data = f2.read() + similarity = SequenceMaster(None, f1Data, f2Data).ratio() + print(similarity*100) + From 20bb0bb02629483787a67c77ee733ee79a041674 Mon Sep 17 00:00:00 2001 From: NaprKnight <86531684+NaprKnight@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:09:48 +0530 Subject: [PATCH 157/278] Create Nodes which are not part of any cycle in a Directed Graph hacktoberfest-2022 please add it under the label hacktoberfest-2022 --- ... not part of any cycle in a Directed Graph | 174 ++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 CPP/Nodes which are not part of any cycle in a Directed Graph diff --git a/CPP/Nodes which are not part of any cycle in a Directed Graph b/CPP/Nodes which are not part of any cycle in a Directed Graph new file mode 100644 index 0000000..f2d7455 --- /dev/null +++ b/CPP/Nodes which are not part of any cycle in a Directed Graph @@ -0,0 +1,174 @@ + +#include +using namespace std; + +class Graph { + + // No. of vertices + int V; + + // Stores the Adjacency List + list* adj; + bool printNodesNotInCycleUtil( + int v, bool visited[], bool* rs, + bool* cyclePart); + +public: + // Constructor + Graph(int V); + + // Member Functions + void addEdge(int v, int w); + void printNodesNotInCycle(); +}; + +// Function to initialize the graph +Graph::Graph(int V) +{ + this->V = V; + adj = new list[V]; +} + +// Function that adds directed edges +// between node v with node w +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); +} + +// Function to perform DFS Traversal +// and return true if current node v +// formes cycle +bool Graph::printNodesNotInCycleUtil( + int v, bool visited[], + bool* recStack, bool* cyclePart) +{ + + // If node v is unvisited + if (visited[v] == false) { + + // Mark the current node as + // visited and part of + // recursion stack + visited[v] = true; + recStack[v] = true; + + // Traverse the Adjacency + // List of current node v + for (auto& child : adj[v]) { + + // If child node is unvisited + if (!visited[child] + && printNodesNotInCycleUtil( + child, visited, + recStack, cyclePart)) { + + // If child node is a part + // of cycle node + cyclePart[child] = 1; + return true; + } + + // If child node is visited + else if (recStack[child]) { + cyclePart[child] = 1; + return true; + } + } + } + + // Remove vertex from recursion stack + recStack[v] = false; + return false; +} + +// Function that print the nodes for +// the given directed graph that are +// not present in any cycle +void Graph::printNodesNotInCycle() +{ + + // Stores the visited node + bool* visited = new bool[V]; + + // Stores nodes in recursion stack + bool* recStack = new bool[V]; + + // Stores the nodes that are + // part of any cycle + bool* cyclePart = new bool[V]; + + for (int i = 0; i < V; i++) { + visited[i] = false; + recStack[i] = false; + cyclePart[i] = false; + } + + // Traverse each node + for (int i = 0; i < V; i++) { + + // If current node is unvisited + if (!visited[i]) { + + // Perform DFS Traversal + if (printNodesNotInCycleUtil( + i, visited, recStack, + cyclePart)) { + + // Mark as cycle node + // if it return true + cyclePart[i] = 1; + } + } + } + + // Traverse the cyclePart[] + for (int i = 0; i < V; i++) { + + // If node i is not a part + // of any cycle + if (cyclePart[i] == 0) { + cout << i << " "; + } + } +} + +// Function that print the nodes for +// the given directed graph that are +// not present in any cycle +void solve(int N, int E, + int Edges[][2]) +{ + + // Initialize the graph g + Graph g(N); + + // Create a directed Graph + for (int i = 0; i < E; i++) { + g.addEdge(Edges[i][0], + Edges[i][1]); + } + + // Function Call + g.printNodesNotInCycle(); +} + +// Driver Code +int main() +{ + // Given Number of nodes + int N = 6; + + // Given Edges + int E = 7; + + int Edges[][2] = { { 0, 1 }, { 0, 2 }, + { 1, 3 }, { 2, 1 }, + { 2, 5 }, { 3, 0 }, + { 4, 5 } }; + + // Function Call + solve(N, E, Edges); + + return 0; +} From 1c04031a133e11399512a9408ee7b48b6049e769 Mon Sep 17 00:00:00 2001 From: NaprKnight <86531684+NaprKnight@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:12:02 +0530 Subject: [PATCH 158/278] =?UTF-8?q?Create=20Dijkstra=E2=80=99s=20Shortest?= =?UTF-8?q?=20Path=20Algorithm.cpp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hacktoberfest-2022 please add it under the label hacktoberfest-2022 --- ...\342\200\231s Shortest Path Algorithm.cpp" | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 "CPP/Dijkstra\342\200\231s Shortest Path Algorithm.cpp" diff --git "a/CPP/Dijkstra\342\200\231s Shortest Path Algorithm.cpp" "b/CPP/Dijkstra\342\200\231s Shortest Path Algorithm.cpp" new file mode 100644 index 0000000..4d4ce6e --- /dev/null +++ "b/CPP/Dijkstra\342\200\231s Shortest Path Algorithm.cpp" @@ -0,0 +1,103 @@ +#include +using namespace std; +#include + +// Number of vertices in the graph +#define V 9 + +// A utility function to find the vertex with minimum +// distance value, from the set of vertices not yet included +// in shortest path tree +int minDistance(int dist[], bool sptSet[]) +{ + + // Initialize min value + int min = INT_MAX, min_index; + + for (int v = 0; v < V; v++) + if (sptSet[v] == false && dist[v] <= min) + min = dist[v], min_index = v; + + return min_index; +} + +// A utility function to print the constructed distance +// array +void printSolution(int dist[]) +{ + cout << "Vertex \t Distance from Source" << endl; + for (int i = 0; i < V; i++) + cout << i << " \t\t\t\t" << dist[i] << endl; +} + +// Function that implements Dijkstra's single source +// shortest path algorithm for a graph represented using +// adjacency matrix representation +void dijkstra(int graph[V][V], int src) +{ + int dist[V]; // The output array. dist[i] will hold the + // shortest + // distance from src to i + + bool sptSet[V]; // sptSet[i] will be true if vertex i is + // included in shortest + // path tree or shortest distance from src to i is + // finalized + + // Initialize all distances as INFINITE and stpSet[] as + // false + for (int i = 0; i < V; i++) + dist[i] = INT_MAX, sptSet[i] = false; + + // Distance of source vertex from itself is always 0 + dist[src] = 0; + + // Find shortest path for all vertices + for (int count = 0; count < V - 1; count++) { + // Pick the minimum distance vertex from the set of + // vertices not yet processed. u is always equal to + // src in the first iteration. + int u = minDistance(dist, sptSet); + + // Mark the picked vertex as processed + sptSet[u] = true; + + // Update dist value of the adjacent vertices of the + // picked vertex. + for (int v = 0; v < V; v++) + + // Update dist[v] only if is not in sptSet, + // there is an edge from u to v, and total + // weight of path from src to v through u is + // smaller than current value of dist[v] + if (!sptSet[v] && graph[u][v] + && dist[u] != INT_MAX + && dist[u] + graph[u][v] < dist[v]) + dist[v] = dist[u] + graph[u][v]; + } + + // print the constructed distance array + printSolution(dist); +} + +// driver's code +int main() +{ + + /* Let us create the example graph discussed above */ + int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, + { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, + { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, + { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, + { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, + { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, + { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, + { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, + { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; + + // Function call + dijkstra(graph, 0); + + return 0; +} + From 4607f4e6843301eb816e98253d6e046caa902ae0 Mon Sep 17 00:00:00 2001 From: NILADRI BIT Date: Sun, 2 Oct 2022 11:12:11 +0530 Subject: [PATCH 159/278] Create bubblesort.py --- Python/bubblesort.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Python/bubblesort.py diff --git a/Python/bubblesort.py b/Python/bubblesort.py new file mode 100644 index 0000000..9d2a86a --- /dev/null +++ b/Python/bubblesort.py @@ -0,0 +1,33 @@ +def bubbleSort(arr): + n = len(arr) + # optimize code, so if the array is already sorted, it doesn't need + # to go through the entire process + swapped = False + # Traverse through all array elements + for i in range(n-1): + # range(n) also work but outer loop will + # repeat one time more than needed. + # Last i elements are already in place + for j in range(0, n-i-1): + + # traverse the array from 0 to n-i-1 + # Swap if the element found is greater + # than the next element + if arr[j] > arr[j + 1]: + swapped = True + arr[j], arr[j + 1] = arr[j + 1], arr[j] + + if not swapped: + # if we haven't needed to make a single swap, we + # can just exit the main loop. + return + + +# Driver code to test above +arr = [64, 34, 25, 12, 22, 11, 90] + +bubbleSort(arr) + +print("Sorted array is:") +for i in range(len(arr)): + print("% d" % arr[i], end=" ") From 3b4b58ed030d2573ba02cff88e818a282acd541e Mon Sep 17 00:00:00 2001 From: NILADRI BIT Date: Sun, 2 Oct 2022 11:14:38 +0530 Subject: [PATCH 160/278] binary search --- Python/binary_search.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/binary_search.py diff --git a/Python/binary_search.py b/Python/binary_search.py new file mode 100644 index 0000000..3dd51db --- /dev/null +++ b/Python/binary_search.py @@ -0,0 +1,35 @@ +def binary_search(arr, low, high, x): + + # Check base case + if high >= low: + + mid = (high + low) // 2 + + # If element is present at the middle itself + if arr[mid] == x: + return mid + + # If element is smaller than mid, then it can only + # be present in left subarray + elif arr[mid] > x: + return binary_search(arr, low, mid - 1, x) + + # Else the element can only be present in right subarray + else: + return binary_search(arr, mid + 1, high, x) + + else: + # Element is not present in the array + return -1 + +# Test array +arr = [ 2, 3, 4, 10, 40 ] +x = 10 + +# Function call +result = binary_search(arr, 0, len(arr)-1, x) + +if result != -1: + print("Element is present at index", str(result)) +else: + print("Element is not present in array") From c8eb4624c6958934b9cbb357ab1b391c79c213ad Mon Sep 17 00:00:00 2001 From: patel armin Date: Sun, 2 Oct 2022 11:15:01 +0530 Subject: [PATCH 161/278] =?UTF-8?q?Prim=E2=80=99s=20Algorithm?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- "CPP/Prim\342\200\231s Algorithm.cpp" | 90 +++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 "CPP/Prim\342\200\231s Algorithm.cpp" diff --git "a/CPP/Prim\342\200\231s Algorithm.cpp" "b/CPP/Prim\342\200\231s Algorithm.cpp" new file mode 100644 index 0000000..49d81de --- /dev/null +++ "b/CPP/Prim\342\200\231s Algorithm.cpp" @@ -0,0 +1,90 @@ +#include +using namespace std; +int main() +{ + int n; + char c = 'a'; + cout << "enter number of nodes"; + cin >> n; + int g[n][n]; + int stree[n][3]; + for (int i = 0; i < n; i++) + stree[i][0] = stree[i][1] = stree[i][2] = -1; + cout << "enter graph egdes 0 for no egde and weight for edge\n"; + for (int i = 0; i < n; i++) + { + for (int j = i; j < n; j++) + { + g[i][j] = 0; + if (i != j) + { + cout << "(" << ((char)(c + i)) << "," << (char)(c + j) << "):-"; + cin >> g[i][j]; + g[j][i] = g[i][j]; + } + } + } + cout << "\t "; + for (int i = 0; i < n; i++) + cout << (char)(c + i) << "\t"; + for (int i = 0; i < n; i++) + { + cout << endl + << (char)(c + i) << "\t "; + for (int j = 0; j < n; j++) + { + if (g[i][j] != 0) + cout << "|" << g[i][j]; + else + cout << "|-"; + cout << "\t"; + } + } + // root node + stree[0][0] = stree[0][1] = 0; + stree[0][2] = 1; + // making stree + int counter = 0, i = 0; + while (counter < n) + { + for (int k = 0; k < n; k++) + { + if (g[i][k] != 0) + { + if (stree[k][0] == -1 && stree[k][2] != 1) + { + stree[k][0] = i; + stree[k][1] = g[i][k]; + } + else + { + if (stree[k][1] > g[i][k] && stree[k][2] != 1) + { + stree[k][0] = i; + stree[k][1] = g[i][k]; + } + } + } + } + int temp = -1; + for (int k = 0; k < n; k++) + { + if (stree[k][2] != 1 && stree[k][0] != -1) + { + if (temp == -1) + temp = k; + else + { + if (stree[temp][1] > stree[k][1]) + temp = k; + } + } + } + i = temp; + stree[i][2] = 1; + counter++; + } + for (i = 0; i < n; i++) + cout << endl + << (char)(c + i) << ":-" << (char)(c + stree[i][0]) << "," << stree[i][1]; +} \ No newline at end of file From 187b9aa32242a006c31ff5daa5140206da491f7c Mon Sep 17 00:00:00 2001 From: VarunBhattacharya <76221455+VarunBhattacharya@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:15:35 +0530 Subject: [PATCH 162/278] Queue Operations Introduction to the operations performed in a Queue using the FIFO principle with all the functionalities. --- C/QueueOperations.c | 148 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 C/QueueOperations.c diff --git a/C/QueueOperations.c b/C/QueueOperations.c new file mode 100644 index 0000000..32d657e --- /dev/null +++ b/C/QueueOperations.c @@ -0,0 +1,148 @@ +/* +Write a Menu - Driven Program for the user to use the simple operations of Queue +using the concept of arrays. +Basic Functions are: + i.) enqueue - add an element to the tail of a queue + ii.) dequeue - remove an element from the head of a queue + iii.) first - examine the element at the head of the queue + iv.) isfull - examine the queue is full or not + v.) isempty - examine the queue is empty or not + vi.) size - determines the number of elements in the queue + +Short Algorithm +---> +*/ + +//Including Libraries +#include +#include + +//Global Variable Declaration +int max = 4 + 1; +int frnt = -1; +int back = -1; +int arr[4+1]; + +//Function Declarations +void enqueue(); +void dequeue(); +void disp(); +void first(); +void isfull(); +void isempty(); +void size(); + +//Main Function +int main() +{ + int opt; + while(1) + { + printf("\nBasic Operations on Queue\n"); + printf("1_Enqueue \n2_Dequeue \n3_Display \n4_First \n5_IsFull \n6_IsEmpty \n7_Size \n8_Exit"); + printf("\nEnter Your Choice: "); + scanf("%d", &opt); + switch(opt) + { + case 1: enqueue(); break; + case 2: dequeue(); break; + case 3: disp(); break; + case 4: first(); break; + case 5: isfull(); break; + case 6: isempty(); break; + case 7: size(); break; + case 8: exit(0); //printf("You are ending the program"); return 0; + default: printf("\nInvalid Choice\n"); + } + } + return 0; +} + +//Function Implementation +void enqueue() //Enqueue Function - For inserting at the end +{ + int inp; + if(back == max - 1) + { + printf("\nQueue Overflow\n"); + } + else + { + if(frnt == -1) {frnt = 0;} + printf("\nEnter Element to be inserted: "); + scanf("%d", &inp); + back++; + arr[back] = inp; + } +} + +void dequeue() //Dequeue Function - For deleting at the start +{ + if(frnt == -1 || frnt > back) + { + printf("\nNo Elements There\n"); + } + else + { + printf("\nThe Dequeued elements is: %d\n", arr[frnt]); + frnt++; + } +} + +void disp() //Display Function - For displaying all the elements +{ + int i; + if(frnt == -1) + { + printf("\nNo Element There\n"); + } + else + { + printf("\nElements present in the queue are: \n"); + for(i = frnt; i <= back; i++) + { + printf("%d\n ", arr[i]); + } + } +} + +void first() //First Function - For displaying the first element in the queue +{ + if(frnt == -1 || frnt > back) + { + printf("\nNo Element There\n"); + } + else + { + printf("\nThe First element is: %d\n", arr[frnt]); + } +} + +void isfull() //isfull Function - For checking the queue is full or not +{ + if(back == max) + { + printf("\nThe Queue is Full\n"); + } + else + { + printf("\nThe Queue is not Full\n"); + } +} + +void isempty() //isempty Function - For checking the queue is empty or not +{ + if(frnt == -1 || frnt > back) + { + printf("\nThe Queue is Empty\n"); + } + else + { + printf("\nThe Queue is not Empty\n"); + } +} + +void size() //Size Function - Gets the number of elements in the array +{ + printf("\nThe Number of elements in the array are: %d\n",back+1); +} \ No newline at end of file From d63ad79267cd77ca27ad2744b659438859c6de8e Mon Sep 17 00:00:00 2001 From: Sahil Rana <51770809+Rsr0@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:17:48 +0530 Subject: [PATCH 163/278] Create invertBinaryTree.cpp --- CPP/invertBinaryTree.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 CPP/invertBinaryTree.cpp diff --git a/CPP/invertBinaryTree.cpp b/CPP/invertBinaryTree.cpp new file mode 100644 index 0000000..27d696e --- /dev/null +++ b/CPP/invertBinaryTree.cpp @@ -0,0 +1,24 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + if(!root) return NULL; + + TreeNode* rTree = invertTree(root->right); + TreeNode* lTree = invertTree(root->left); + + root->left = rTree; + root->right = lTree; + return root; + } +}; From 0e3b9bd4d7447ffd37a88918f03de3327f967d9d Mon Sep 17 00:00:00 2001 From: Suraj Singh <103835667+suraj-s13@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:17:55 +0530 Subject: [PATCH 164/278] Explanation about stack and its opration --- CPP/stack-oprations/readme.md | 47 +++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 CPP/stack-oprations/readme.md diff --git a/CPP/stack-oprations/readme.md b/CPP/stack-oprations/readme.md new file mode 100644 index 0000000..620d77a --- /dev/null +++ b/CPP/stack-oprations/readme.md @@ -0,0 +1,47 @@ +

Stack and its basic Operations

+ +First, let us see the properties of data structures that we already do know and build-up our concepts towards the stack. + +-Array: Its a random-access container, meaning any element of this container can be accessed instantly + +-Linked List: It's a sequential-access container, meaning that elements of this data structure can only be accessed sequentially + +→ Following a similar definition,A stack is a container where only the top element can be accessed or operated upon. + +*A Stack is a data structure following the LIFO(Last In, First Out) principle.* +
+

+ Material Bread logo +

+

+If you have trouble visualizing stacks, just assume a stack of books. + +1.In a stack of books, you can only see the top book + +2.If you want to access any other book, you would first need to remove the books on top of it + +3.The bottom-most book in the stack was put first and can only be removed at the last after all books on top of it have been removed. + +

+ Material Bread logo +

+ + +***

PUSH Operation

*** + +Push operation refers to inserting an element in the stack. Since there’s only one position at which the new element can be inserted — Top of the stack, the new element is inserted at the top of the stack. + +***

POP Operation

*** +Pop operation refers to the removal of an element. Again, since we only have access to the element at the top of the stack, there’s only one element that we can remove. We just remove the top of the stack. Note: We can also choose to return the value of the popped element back, its completely at the choice of the programmer to implement this. + +***

PEEK Operation

*** + +Peek operation allows the user to see the element on the top of the stack. The stack is not modified in any manner in this operation. + +***

isEmpty: Check if stack is empty or not

*** + +To prevent performing operations on an empty stack, the programmer is required to internally maintain the size of the stack which will be updated during push and pop operations accordingly. isEmpty() conventionally returns a boolean value: True if size is 0, else False. + + + + From cb277991f074b37fc718c52dcbca42ac0eb534dd Mon Sep 17 00:00:00 2001 From: Suraj Singh <103835667+suraj-s13@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:18:42 +0530 Subject: [PATCH 165/278] using STL --- CPP/stack-oprations/STL-stack.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 CPP/stack-oprations/STL-stack.cpp diff --git a/CPP/stack-oprations/STL-stack.cpp b/CPP/stack-oprations/STL-stack.cpp new file mode 100644 index 0000000..f0539ff --- /dev/null +++ b/CPP/stack-oprations/STL-stack.cpp @@ -0,0 +1,18 @@ +#include +#include +using namespace std; + +int main() { + // create a stack of strings + stack languages; + + // add element to the Stack + languages.push("C++"); + languages.push("Java"); + languages.push("Python"); + + // print top element + cout << languages.top(); + + return 0; +} From fc088b0788a415a335568beb6e467a5d3d12a29b Mon Sep 17 00:00:00 2001 From: Suraj Singh <103835667+suraj-s13@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:19:26 +0530 Subject: [PATCH 166/278] add_element in stack --- CPP/stack-oprations/add-element.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 CPP/stack-oprations/add-element.cpp diff --git a/CPP/stack-oprations/add-element.cpp b/CPP/stack-oprations/add-element.cpp new file mode 100644 index 0000000..3573127 --- /dev/null +++ b/CPP/stack-oprations/add-element.cpp @@ -0,0 +1,23 @@ +#include +#include +using namespace std; + +int main() { + + // create a stack of strings + stack colors; + + // push elements into the stack + colors.push("Red"); + colors.push("Orange"); + + cout << "Stack: "; + + // print elements of stack + while(!colors.empty()) { + cout << colors.top() << ", "; + colors.pop(); + } + + return 0; +} From 3a7c6fbd265263bb710b60d9242a1d21bc4dde93 Mon Sep 17 00:00:00 2001 From: harendrabhardwaj <40700440+harendrabhardwaj@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:20:08 +0530 Subject: [PATCH 167/278] hacktoberfest event --- Java/Combination.java | 52 ++++++++++++++++++++++++++++++++ Java/FloodFill.java | 69 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 Java/Combination.java create mode 100644 Java/FloodFill.java diff --git a/Java/Combination.java b/Java/Combination.java new file mode 100644 index 0000000..1298621 --- /dev/null +++ b/Java/Combination.java @@ -0,0 +1,52 @@ +package com.thealgorithms.backtracking; + +import java.util.*; + +/** + * Finds all permutations of given array + * @author Alan Piao (https://github.com/cpiao3) + */ +public class Combination { + private static int length; + /** + * Find all combinations of given array using backtracking + * @param arr the array. + * @param n length of combination + * @param the type of elements in the array. + * @return a list of all combinations of length n. If n == 0, return null. + */ + public static List> combination(T[] arr, int n) { + if (n == 0) { + return null; + } + length = n; + T[] array = arr.clone(); + Arrays.sort(array); + List> result = new LinkedList<>(); + backtracking(array, 0, new TreeSet(), result); + return result; + } + /** + * Backtrack all possible combinations of a given array + * @param arr the array. + * @param index the starting index. + * @param currSet set that tracks current combination + * @param result the list contains all combination. + * @param the type of elements in the array. + */ + private static void backtracking(T[] arr, int index, TreeSet currSet, List> result) { + if (index + length - currSet.size() > arr.length) return; + if (length - 1 == currSet.size()) { + for (int i = index; i < arr.length; i++) { + currSet.add(arr[i]); + result.add((TreeSet) currSet.clone()); + currSet.remove(arr[i]); + } + } + for (int i = index; i < arr.length; i++) { + currSet.add(arr[i]); + backtracking(arr, i + 1, currSet, result); + currSet.remove(arr[i]); + } + } +} diff --git a/Java/FloodFill.java b/Java/FloodFill.java new file mode 100644 index 0000000..d7842a6 --- /dev/null +++ b/Java/FloodFill.java @@ -0,0 +1,69 @@ +package com.thealgorithms.backtracking; + +/** + * Java program for Flood fill algorithm. + * @author Akshay Dubey (https://github.com/itsAkshayDubey) + */ +public class FloodFill { + + /** + * Get the color at the given co-odrinates of a 2D image + * + * @param image The image to be filled + * @param x The x co-ordinate of which color is to be obtained + * @param y The y co-ordinate of which color is to be obtained + */ + + public static int getPixel(int[][] image, int x, int y) { + + return image[x][y]; + + } + + /** + * Put the color at the given co-odrinates of a 2D image + * + * @param image The image to be filed + * @param x The x co-ordinate at which color is to be filled + * @param y The y co-ordinate at which color is to be filled + */ + public static void putPixel(int[][] image, int x, int y, int newColor) { + + image[x][y] = newColor; + + } + + + /** + * Fill the 2D image with new color + * + * @param image The image to be filed + * @param x The x co-ordinate at which color is to be filled + * @param y The y co-ordinate at which color is to be filled + * @param newColor The new color which to be filled in the image + * @param oldColor The old color which is to be replaced in the image + * @return + */ + public static void floodFill(int[][] image, int x, int y, int newColor, int oldColor) { + + if(x < 0 || x >= image.length) return; + if(y < 0 || y >= image[x].length) return; + if(getPixel(image, x, y) != oldColor) return; + + putPixel(image, x, y, newColor); + + /* Recursively check for horizontally & vertically adjacent coordinates */ + floodFill(image, x + 1, y, newColor, oldColor); + floodFill(image, x - 1, y, newColor, oldColor); + floodFill(image, x, y + 1, newColor, oldColor); + floodFill(image, x, y - 1, newColor, oldColor); + + /* Recursively check for diagonally adjacent coordinates */ + floodFill(image, x + 1, y - 1, newColor, oldColor); + floodFill(image, x - 1, y + 1, newColor, oldColor); + floodFill(image, x + 1, y + 1, newColor, oldColor); + floodFill(image, x - 1, y - 1, newColor, oldColor); + + } + +} \ No newline at end of file From 87be875bed0c2cba3f693d4d7c52aee73b875d43 Mon Sep 17 00:00:00 2001 From: Suraj Singh <103835667+suraj-s13@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:20:15 +0530 Subject: [PATCH 168/278] Remove Elements From the Stack --- CPP/stack-oprations/remove-element.cpp | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 CPP/stack-oprations/remove-element.cpp diff --git a/CPP/stack-oprations/remove-element.cpp b/CPP/stack-oprations/remove-element.cpp new file mode 100644 index 0000000..ba4c731 --- /dev/null +++ b/CPP/stack-oprations/remove-element.cpp @@ -0,0 +1,42 @@ +#include +#include +using namespace std; + +// function prototype for display_stack utility +void display_stack(stack st); + +int main() { + + // create a stack of strings + stack colors; + + // push elements into the stack + colors.push("Red"); + colors.push("Orange"); + colors.push("Blue"); + + cout << "Initial Stack: "; + // print elements of stack + display_stack(colors); + + // removes "Blue" as it was inserted last + colors.pop(); + + cout << "Final Stack: "; + + // print elements of stack + display_stack(colors); + + return 0; +} + +// utility function to display stack elements +void display_stack(stack st) { + + while(!st.empty()) { + cout << st.top() << ", "; + st.pop(); + } + + cout << endl; +} From 5395b004c47d435166567048892020ea01199ecc Mon Sep 17 00:00:00 2001 From: Sahil Rana <51770809+Rsr0@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:24:36 +0530 Subject: [PATCH 169/278] Delete invertBinaryTree.cpp --- CPP/invertBinaryTree.cpp | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 CPP/invertBinaryTree.cpp diff --git a/CPP/invertBinaryTree.cpp b/CPP/invertBinaryTree.cpp deleted file mode 100644 index 27d696e..0000000 --- a/CPP/invertBinaryTree.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* invertTree(TreeNode* root) { - if(!root) return NULL; - - TreeNode* rTree = invertTree(root->right); - TreeNode* lTree = invertTree(root->left); - - root->left = rTree; - root->right = lTree; - return root; - } -}; From 2c69c41d496e1029e8142fd02e5887f09613625d Mon Sep 17 00:00:00 2001 From: Jeevan Dsouza <55314395+JeevanDsouzajd@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:24:38 +0530 Subject: [PATCH 170/278] Mergesort --- Merge_sort.cpp | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Merge_sort.cpp diff --git a/Merge_sort.cpp b/Merge_sort.cpp new file mode 100644 index 0000000..802e48f --- /dev/null +++ b/Merge_sort.cpp @@ -0,0 +1,75 @@ +#include +using namespace std ; + +class Solution { +public: + void merge(int arr[], int l, int mid, int r) + { + int i = l ; // starting index of left half of arr + int j = mid + 1; // starting index of right half of arr + int f = l ; // index used to transfer elements in temporary array + int temp[100000] ; // temporary array + + //storing elements in the temporary array in a sorted manner// + + while (i <= mid && j <= r) { + if (arr[i] < arr[j]) { + temp[f] = arr[i] ; + i++ ; + } + else { + temp[f] = arr[j] ; + j++ ; + } + f++ ; + } + + // if elements on the left half are still left // + + if (i > mid) { + while (j <= r) { + temp[f] = arr[j] ; + f++ ; j++ ; + } + } + else { + // if elements on the right half are still left // + while (i <= mid) { + temp[f] = arr[i] ; + f++ ; i++ ; + } + } + + // transfering all elements from temporary to arr // + for (int f = l ; f <= r; f++) { + arr[f] = temp[f] ; + } + } + void mergeSort(int arr[], int l, int r) + { + if (l < r) { + int mid = (l + r) / 2 ; + mergeSort(arr, l, mid) ; // left half + mergeSort(arr, mid + 1, r) ; // right half + merge(arr, l, mid, r) ; // merging sorted halves + } + } +}; +int main() { + + int arr[] = {9, 4, 7, 6, 3, 1, 5} ; + int n = 7; + + Solution obj ; + cout << "Before Sorting Array: "< Date: Sun, 2 Oct 2022 11:34:35 +0530 Subject: [PATCH 171/278] Create yourname.html hacktoberfest event --- yourname.html | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 yourname.html diff --git a/yourname.html b/yourname.html new file mode 100644 index 0000000..3e2106b --- /dev/null +++ b/yourname.html @@ -0,0 +1,15 @@ + + + + + My Home Page + + + + + +

Hello My Name is ABC

+ + + + From 810f8b26482573da97f29840df9903f7fca20d42 Mon Sep 17 00:00:00 2001 From: MEET9926 <71933483+MEET9926@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:51:00 +0530 Subject: [PATCH 172/278] Selection.py Selection Sort Code in Python --- Selection..py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Selection..py diff --git a/Selection..py b/Selection..py new file mode 100644 index 0000000..ae9438e --- /dev/null +++ b/Selection..py @@ -0,0 +1,24 @@ +# Selection sort in Python + + +def selectionSort(array, size): + + for step in range(size): + min_idx = step + + for i in range(step + 1, size): + + # to sort in descending order, change > to < in this line + # select the minimum element in each loop + if array[i] < array[min_idx]: + min_idx = i + + # put min at the correct position + (array[step], array[min_idx]) = (array[min_idx], array[step]) + + +data = [-2, 45, 0, 11, -9] +size = len(data) +selectionSort(data, size) +print('Sorted Array in Ascending Order:') +print(data) From 850603ec99fb13e35a85fe4a372cf440852b32b4 Mon Sep 17 00:00:00 2001 From: Rohan Khandewal <12112127@nitkkr.ac.in> Date: Sun, 2 Oct 2022 11:53:18 +0530 Subject: [PATCH 173/278] adding stack in C --- C/stack_array.c | 120 ++++++++++++++++++++++++++ max3num (2020_12_18 18_56_42 UTC).exe | Bin 45558 -> 0 bytes 2 files changed, 120 insertions(+) create mode 100644 C/stack_array.c delete mode 100644 max3num (2020_12_18 18_56_42 UTC).exe diff --git a/C/stack_array.c b/C/stack_array.c new file mode 100644 index 0000000..93eb88a --- /dev/null +++ b/C/stack_array.c @@ -0,0 +1,120 @@ +#include +#include +#include +#include +struct stack +{ + int size; + int *arr; +}; +bool isEmpty(int top) +{ + if (top == -1) + { + return 1; + } + return 0; +} +bool isFull(int top, struct stack *st) +{ + if (top == st->size - 1) + { + return 1; + } + return 0; +} +int create(struct stack *st) +{ + st->arr = (int *)malloc((st->size) * sizeof(int)); + printf("\nEnter the number of values you want to add in stack : "); + int val; + scanf("%d", &val); + getchar(); + int i = 0; + printf("\nEnter the values you want to add : \n"); + for (i = 0; i < val; i++) + { + scanf("%d", &st->arr[i]); + getchar(); + } + return i - 1; +} +int push(struct stack *st, int top) +{ + if (isFull(top, st)) + { + printf("\nStack overflowed !!!!"); + return top; + } + else + { + top++; + printf("\nEnter the value you want to push in : "); + scanf("%d", &st->arr[top]); + getchar(); + return top; + } +} +int pop(struct stack *st, int top) +{ + if (isEmpty(top)) + { + printf("\nStack underflowed!!!!"); + return top; + } + else + { + printf("\nElement poped out is : %d", st->arr[top]); + top--; + return top; + } +} +void display(int top, struct stack *st) +{ + if (isEmpty(top)) + { + printf("\nStack is empty nothing to display"); + } + else + { + printf("\nStack elements are : \n"); + for (int i = 0; i < top + 1; i++) + { + printf("%d\t", st->arr[i]); + } + } +} +int main() +{ + struct stack *s = (struct stack *)malloc(sizeof(struct stack)); + printf("\nEnter the size of array : "); + scanf("%d", &s->size); + getchar(); + int top = -1; + top = create(s); + int loop = 1; + while (loop) + { + printf("\nEnter your choice : \n1.'A' for pushing \n2.'B' for poping\n3.'C' for exit/display stack : \n"); + char choice; + scanf("%c", &choice); + getchar(); + switch (choice) + { + case 'A': + top = push(s, top); + display(top, s); + break; + case 'B': + top = pop(s, top); + display(top ,s); + break; + case 'C': + display(top, s); + loop = 0; + break; + } + } + + return 0; +} \ No newline at end of file diff --git a/max3num (2020_12_18 18_56_42 UTC).exe b/max3num (2020_12_18 18_56_42 UTC).exe deleted file mode 100644 index 74cb47682c41aa6fa6a8761b65b9594eb2e557c4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 45558 zcmeIb3w%`7)i=D)%p@5|$V?zy)Tjd;6cj?j&0s+@NhTM`&0M%BcnHY^qLYis8SY4M z66JJEo2QTO^VpWQUR&+s*V?BPsP(boBEi<$XuY6fOBL(Hpv6m(i)Ft5+WVY2b27p9 z*SGKc_4m~SC+F<7*IIk6wbx$za?aUPc2h62GRAB;BN4{-;z~y@|NHrWI+2}v`ID(^ z*Qj4l-Yb>T}w-=;#%!UO)aj1ifUJLYlAOy%$U(` zjdi7$u~I3OwN@RK85n*jF?Nh4Ny(DM#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J32{ARJk5%gG zu^$iiUu&xGAPe(7cI4JZlDGag>?qRQj0i{>*hQMQJ%&4pk=Jlk+K##%8#ECv-=0nG z2&~2iZ;G#3)_#mo@F6Bx9f?*d;u%4jMu3Qsp=Jp6RoyVbT% zr)_<$d+_iIjMr2|4eAU0N=E}WHpU* z`d*7&xMlH-nPsl`)!mi}qmS@Yodot4%c70vd5cQQxm~&Q!A3Mg(KXdK0heXGG8Jpz z3%64(XhioHH>!E9udXfDAw;7R3uX{0W>0gicvu8`r|UboQ&WhCXq8VJZE0;>R9tj_ zZ=%VM**%_`XOzh7A7YN670%bCP?fYRAhr}VxgeKZd-YXAkM3kH<5S-{UJrVE$IahX=J1d~K^M7L_IH zEs*BIm50L7qiP$g>rN0G?V^#0$uax;8$!Z=_y+7+;MK)2ZD`NKHvcUEP8a*t7g{9t z7NZT}QAd!(*v4LXpw5qG@umPQR>1U%t&i$2hAIs{+C*Q33EGg)wuAH9d7PSE#6`k$z&pu$(p@g_t5*MEiLE`eqV-gcd8J2y}8QOYD)S=hJ{Ja88tC_}#g2P6 zeGyaRb>XPdA8ClzmN^cXDx(3j5v?n&88#r|%q}>-`TVvxQkTK`jU1UFU^HZ2IJW8? xBYJ4VxY4niOsa@zh4E6%?1y03MS>cx-XioU$VJkAoI@UNw+psCPNl7p|GySdLX7|b From 513e60d2a256eaf04a8f2835570f717e588ddeb4 Mon Sep 17 00:00:00 2001 From: Pasindu Madhusankha <42806288+Madhusankha@users.noreply.github.com> Date: Sun, 2 Oct 2022 12:07:30 +0530 Subject: [PATCH 174/278] Calculater(tkinter) --- Python/Calculater.py | 83 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Python/Calculater.py diff --git a/Python/Calculater.py b/Python/Calculater.py new file mode 100644 index 0000000..fece818 --- /dev/null +++ b/Python/Calculater.py @@ -0,0 +1,83 @@ +import tkinter as tk + +window=tk.Tk() +window.title('TK CALCULATOR') + +eqn=" " + +def btnprs(btn): + global eqn + + if(btn=='c'): + eqn='0' + + elif(btn=='='): + result=eval(eqn) + eqn=str(result) + + else: + if(eqn=='0'): + eqn=' ' + + + eqn=eqn+btn + + label2.config(text=eqn) + + +label1=tk.Label(window,text='Tk Calcutator',fg='black',font='HELVITICA 15 bold') +label1.grid(row=0,columnspan=8,padx=5,pady=3) + +label2=tk.Label(window,text='0',bg='white',font='HELVITICA 15 bold',width=15,height=1) +label2.grid(row=1,columnspan=8,padx=5,pady=3) + + +buttons=[tk.Button for i in range(16)] + +buttons[0]=tk.Button(window,text='1',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('1')) +buttons[0].grid(row=2,column=0,padx=8,pady=8) + +buttons[1]=tk.Button(window,text='2',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('2')) +buttons[1].grid(row=2,column=1,padx=8,pady=8) + +buttons[2]=tk.Button(window,text='3',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('3')) +buttons[2].grid(row=2,column=2,padx=8,pady=8) + +buttons[3]=tk.Button(window,text='+',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('+')) +buttons[3].grid(row=2,column=3,padx=8,pady=8) + +buttons[4]=tk.Button(window,text='4',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('4')) +buttons[4].grid(row=3,column=0,padx=8,pady=8) + +buttons[5]=tk.Button(window,text='5',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('5')) +buttons[5].grid(row=3,column=1,padx=8,pady=8) + +buttons[6]=tk.Button(window,text='6',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('6')) +buttons[6].grid(row=3,column=2,padx=8,pady=8) + +buttons[7]=tk.Button(window,text='-',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('-')) +buttons[7].grid(row=3,column=3,padx=8,pady=8) + +buttons[8]=tk.Button(window,text='7',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('7')) +buttons[8].grid(row=4,column=0,padx=8,pady=8) + +buttons[9]=tk.Button(window,text='8',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('8')) +buttons[9].grid(row=4,column=1,padx=8,pady=8) + +buttons[10]=tk.Button(window,text='9',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('9')) +buttons[10].grid(row=4,column=2,padx=8,pady=8) + +buttons[11]=tk.Button(window,text='X',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('*')) +buttons[11].grid(row=4,column=3,padx=8,pady=8) + +buttons[12]=tk.Button(window,text='C',font='HELVITICA 12 bold',width=2,height=1,bg='red',command=lambda:btnprs('c')) +buttons[12].grid(row=5,column=0,padx=8,pady=8) + +buttons[13]=tk.Button(window,text='0',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('0')) +buttons[13].grid(row=5,column=1,padx=8,pady=8) + +buttons[14]=tk.Button(window,text='=',font='HELVITICA 12 bold',width=2,height=1,bg='light green',command=lambda:btnprs('=')) +buttons[14].grid(row=5,column=2,padx=8,pady=8) + +buttons[15]=tk.Button(window,text='/',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('/')) +buttons[15].grid(row=5,column=3,padx=8,pady=8) From 3a37f40baca36e3226534aa925914b6df35fe337 Mon Sep 17 00:00:00 2001 From: ShalabhDevliyal <76624340+ShalabhDevliyal@users.noreply.github.com> Date: Sun, 2 Oct 2022 12:07:31 +0530 Subject: [PATCH 175/278] Create AvlTree.cpp --- AvlTree.cpp | 193 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 AvlTree.cpp diff --git a/AvlTree.cpp b/AvlTree.cpp new file mode 100644 index 0000000..5e843cd --- /dev/null +++ b/AvlTree.cpp @@ -0,0 +1,193 @@ + +#include +using namespace std; + +class Node { + public: + int key; + Node *left; + Node *right; + int height; +}; + +int max(int a, int b); + +int height(Node *N) { + if (N == NULL) + return 0; + return N->height; +} + +int max(int a, int b) { + return (a > b) ? a : b; +} + +Node *newNode(int key) { + Node *node = new Node(); + node->key = key; + node->left = NULL; + node->right = NULL; + node->height = 1; + return (node); +} + +Node *rightRotate(Node *y) { + Node *x = y->left; + Node *T2 = x->right; + x->right = y; + y->left = T2; + y->height = max(height(y->left), + height(y->right)) + + 1; + x->height = max(height(x->left), + height(x->right)) + + 1; + return x; +} + +Node *leftRotate(Node *x) { + Node *y = x->right; + Node *T2 = y->left; + y->left = x; + x->right = T2; + x->height = max(height(x->left), + height(x->right)) + + 1; + y->height = max(height(y->left), + height(y->right)) + + 1; + return y; +} + +int getBalanceFactor(Node *N) { + if (N == NULL) + return 0; + return height(N->left) - + height(N->right); +} + +// Insert a node +Node *insertNode(Node *node, int key) { + + if (node == NULL) + return (newNode(key)); + if (key < node->key) + node->left = insertNode(node->left, key); + else if (key > node->key) + node->right = insertNode(node->right, key); + else + return node; + + node->height = 1 + max(height(node->left), + height(node->right)); + int balanceFactor = getBalanceFactor(node); + if (balanceFactor > 1) { + if (key < node->left->key) { + return rightRotate(node); + } else if (key > node->left->key) { + node->left = leftRotate(node->left); + return rightRotate(node); + } + } + if (balanceFactor < -1) { + if (key > node->right->key) { + return leftRotate(node); + } else if (key < node->right->key) { + node->right = rightRotate(node->right); + return leftRotate(node); + } + } + return node; +} + + +Node *nodeWithMimumValue(Node *node) { + Node *current = node; + while (current->left != NULL) + current = current->left; + return current; +} + + +Node *deleteNode(Node *root, int key) { + + if (root == NULL) + return root; + if (key < root->key) + root->left = deleteNode(root->left, key); + else if (key > root->key) + root->right = deleteNode(root->right, key); + else { + if ((root->left == NULL) || + (root->right == NULL)) { + Node *temp = root->left ? root->left : root->right; + if (temp == NULL) { + temp = root; + root = NULL; + } else + *root = *temp; + free(temp); + } else { + Node *temp = nodeWithMimumValue(root->right); + root->key = temp->key; + root->right = deleteNode(root->right, + temp->key); + } + } + + if (root == NULL) + return root; + + root->height = 1 + max(height(root->left), + height(root->right)); + int balanceFactor = getBalanceFactor(root); + if (balanceFactor > 1) { + if (getBalanceFactor(root->left) >= 0) { + return rightRotate(root); + } else { + root->left = leftRotate(root->left); + return rightRotate(root); + } + } + if (balanceFactor < -1) { + if (getBalanceFactor(root->right) <= 0) { + return leftRotate(root); + } else { + root->right = rightRotate(root->right); + return leftRotate(root); + } + } + return root; +} + +void printTree(Node *root, string indent, bool last) { + if (root != nullptr) { + cout << indent; + if (last) { + cout << "R----"; + indent += " "; + } else { + cout << "L----"; + indent += "| "; + } + cout << root->key << endl; + printTree(root->left, indent, false); + printTree(root->right, indent, true); + } +} + +int main() { + Node *root = NULL; + root = insertNode(root, 33); + root = insertNode(root, 13); + root = insertNode(root, 53); + root = insertNode(root, 9); + root = insertNode(root, 21); + root = insertNode(root, 61); + root = insertNode(root, 8); + root = insertNode(root, 11); + printTree(root, "", true); + root = deleteNode(root, 13); + cout << "After deleting " << endl; + printTree(root, "", true); +} From 02a44c60d01d2549a46140d434e0d9c970ed26cc Mon Sep 17 00:00:00 2001 From: Swetaswa Date: Sun, 2 Oct 2022 12:09:22 +0530 Subject: [PATCH 176/278] Finding the sum of the digits of a number without using modulus operator --- SumWithoutMOD.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 SumWithoutMOD.java diff --git a/SumWithoutMOD.java b/SumWithoutMOD.java new file mode 100644 index 0000000..bb71684 --- /dev/null +++ b/SumWithoutMOD.java @@ -0,0 +1,14 @@ +import java.util.*; +public class SumWithoutMOD{ + int summation(String s) + { + int sum=0; + for(int i=0;i Date: Sun, 2 Oct 2022 12:09:34 +0530 Subject: [PATCH 177/278] Bubble Sort Example --- BubbleSortExampleJava.java | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 BubbleSortExampleJava.java diff --git a/BubbleSortExampleJava.java b/BubbleSortExampleJava.java new file mode 100644 index 0000000..f91b7c5 --- /dev/null +++ b/BubbleSortExampleJava.java @@ -0,0 +1,35 @@ +public class BubbleSortExampleJava { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} \ No newline at end of file From ee1e8f1b7f173c6035279e4f16bd73044b2e41ff Mon Sep 17 00:00:00 2001 From: Shubh Agrawal <49271775+shubhagrawal123456@users.noreply.github.com> Date: Sun, 2 Oct 2022 12:23:17 +0530 Subject: [PATCH 178/278] Group_Anagrams Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. --- CPP/Group_Anagrams.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 CPP/Group_Anagrams.cpp diff --git a/CPP/Group_Anagrams.cpp b/CPP/Group_Anagrams.cpp new file mode 100644 index 0000000..e13c0d4 --- /dev/null +++ b/CPP/Group_Anagrams.cpp @@ -0,0 +1,21 @@ +//49:- Group Anagrams +// https://leetcode.com/problems/group-anagrams/ + +vector> groupAnagrams(vector& strs) { + unordered_map>mp; + for(auto x:strs){ + string a=x; + sort(x.begin(),x.end()); + mp[x].push_back(a); + } + + + vector>v; + //sort(strs.begin(),strs.end()); + + for(auto it:mp){ + v.push_back(it.second); + } + return v; + + } From 4ac741c7bf82472035e99db16e40abd9577a733a Mon Sep 17 00:00:00 2001 From: Muhammad Hammad Sani <58339378+mhammadsaani@users.noreply.github.com> Date: Sun, 2 Oct 2022 11:55:37 +0500 Subject: [PATCH 179/278] AVL Tree implementation added --- Python/AVLTree.py | 105 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 Python/AVLTree.py diff --git a/Python/AVLTree.py b/Python/AVLTree.py new file mode 100644 index 0000000..5461deb --- /dev/null +++ b/Python/AVLTree.py @@ -0,0 +1,105 @@ +class treeNode(object): + def __init__(self, value): + self.value = value + self.l = None + self.r = None + self.h = 1 + +class AVLTree(object): + + def insert(self, root, key): + + if not root: + return treeNode(key) + elif key < root.value: + root.l = self.insert(root.l, key) + else: + root.r = self.insert(root.r, key) + + root.h = 1 + max(self.getHeight(root.l), + self.getHeight(root.r)) + + b = self.getBal(root) + + if b > 1 and key < root.l.value: + return self.rRotate(root) + + if b < -1 and key > root.r.value: + return self.lRotate(root) + + if b > 1 and key > root.l.value: + root.l = self.lRotate(root.l) + return self.rRotate(root) + + if b < -1 and key < root.r.value: + root.r = self.rRotate(root.r) + return self.lRotate(root) + + return root + + def lRotate(self, z): + + y = z.r + T2 = y.l + + y.l = z + z.r = T2 + + z.h = 1 + max(self.getHeight(z.l), + self.getHeight(z.r)) + y.h = 1 + max(self.getHeight(y.l), + self.getHeight(y.r)) + + return y + + def rRotate(self, z): + + y = z.l + T3 = y.r + + y.r = z + z.l = T3 + + z.h = 1 + max(self.getHeight(z.l), + self.getHeight(z.r)) + y.h = 1 + max(self.getHeight(y.l), + self.getHeight(y.r)) + + return y + + def getHeight(self, root): + if not root: + return 0 + + return root.h + + def getBal(self, root): + if not root: + return 0 + + return self.getHeight(root.l) - self.getHeight(root.r) + + def preOrder(self, root): + + if not root: + return + + print("{0} ".format(root.value), end="") + self.preOrder(root.l) + self.preOrder(root.r) + +Tree = AVLTree() +root = None + +root = Tree.insert(root, 1) +root = Tree.insert(root, 2) +root = Tree.insert(root, 3) +root = Tree.insert(root, 4) +root = Tree.insert(root, 5) +root = Tree.insert(root, 6) + +# Preorder Traversal +print("Preorder traversal of the", + "constructed AVL tree is") +Tree.preOrder(root) +print() From 501cad9a1361fcc5fd25bfab11af1fcb847576c1 Mon Sep 17 00:00:00 2001 From: Aalim aslam <67648366+aalimaslam@users.noreply.github.com> Date: Sun, 2 Oct 2022 00:03:55 -0700 Subject: [PATCH 180/278] create quicksort.js --- Javascript/quicksort.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Javascript/quicksort.js diff --git a/Javascript/quicksort.js b/Javascript/quicksort.js new file mode 100644 index 0000000..c7e5488 --- /dev/null +++ b/Javascript/quicksort.js @@ -0,0 +1,28 @@ +function quick_Sort(origArray) { + if (origArray.length <= 1) { + return origArray; + } else { + + var left = []; + var right = []; + var newArray = []; + var pivot = origArray.pop(); + var length = origArray.length; + + for (var i = 0; i < length; i++) { + if (origArray[i] <= pivot) { + left.push(origArray[i]); + } else { + right.push(origArray[i]); + } + } + + return newArray.concat(quick_Sort(left), pivot, quick_Sort(right)); + } +} + +var myArray = [3, 0, 2, 5, -1, 4, 1 ]; + +console.log("Original array: " + myArray); +var sortedArray = quick_Sort(myArray); +console.log("Sorted array: " + sortedArray); From 401b4256f0601a10af038b25ee94731069ff0e64 Mon Sep 17 00:00:00 2001 From: Aalim aslam <67648366+aalimaslam@users.noreply.github.com> Date: Sun, 2 Oct 2022 00:05:06 -0700 Subject: [PATCH 181/278] Create mergesort.js --- Javascript/mergesort.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Javascript/mergesort.js diff --git a/Javascript/mergesort.js b/Javascript/mergesort.js new file mode 100644 index 0000000..246b068 --- /dev/null +++ b/Javascript/mergesort.js @@ -0,0 +1,24 @@ +function merge_sort(left_part,right_part) +{ + var i = 0; + var j = 0; + var results = []; + + while (i < left_part.length || j < right_part.length) { + if (i === left_part.length) { + // j is the only index left_part + results.push(right_part[j]); + j++; + } + else if (j === right_part.length || left_part[i] <= right_part[j]) { + results.push(left_part[i]); + i++; + } else { + results.push(right_part[j]); + j++; + } + } + return results; +} + +console.log(merge_sort([1,3,4], [3,7,9])); From 8429e0e04a6892a27b5422bd8aa97173d7321b2e Mon Sep 17 00:00:00 2001 From: Shubh Agrawal <49271775+shubhagrawal123456@users.noreply.github.com> Date: Sun, 2 Oct 2022 12:39:26 +0530 Subject: [PATCH 182/278] The_Skyline_Problem /* * This sorting is required to handle the scenario when you have -ve and * +ve height on the same pos. * consider [2, 3, 3] [3, 5, 3], On position 3 you have -ve and +ve -> first * process the +ve height and then process the -ve height */ --- CPP/The_Skyline_Problem.cpp | 59 +++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 CPP/The_Skyline_Problem.cpp diff --git a/CPP/The_Skyline_Problem.cpp b/CPP/The_Skyline_Problem.cpp new file mode 100644 index 0000000..a8150ed --- /dev/null +++ b/CPP/The_Skyline_Problem.cpp @@ -0,0 +1,59 @@ +//218. The Skyline Problem +//https://leetcode.com/problems/the-skyline-problem/ + +//Code + +bool compare(vector& a, vector& b) { + if(a[0] == b[0]) return a[1] < b[1]; + else return a[0] < b[0]; +} +class Solution { +public: + vector> getSkyline(vector>& arr) { + vector> ans; + vector> dir; + + for(auto it : arr){ + dir.push_back({it[0],-it[2]}); + dir.push_back({it[1],it[2]}); + } + + sort(dir.begin(),dir.end(),compare); + + priority_queue pq; + + int maxVal = 0; + pq.push(0); + + int n = dir.size(); + unordered_map mp; + for(int i=0; i=0){ + mp[v]++; + while(mp[pq.top()]>0){ + mp[pq.top()]--; + pq.pop(); + } + if(pq.empty()){ + if(i==n-1 || dir[i+1][0]!=dir[i][0]){ + ans.push_back({dir[i][0],0}); + maxVal = 0; + } + } + else if(pq.top()maxVal){ + maxVal = pq.top(); + ans.push_back({dir[i][0], maxVal}); + } + } + } + return ans; + } +}; From cf5531ac59c17dabf562dfde40b1cdc40ab0b2a6 Mon Sep 17 00:00:00 2001 From: KrishnaS97 <114850288+KrishnaS97@users.noreply.github.com> Date: Sun, 2 Oct 2022 12:48:42 +0530 Subject: [PATCH 183/278] Perfect Binary Tree Code In Java --- PerfectBinaryTreeCode.java | 63 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 PerfectBinaryTreeCode.java diff --git a/PerfectBinaryTreeCode.java b/PerfectBinaryTreeCode.java new file mode 100644 index 0000000..abf2c90 --- /dev/null +++ b/PerfectBinaryTreeCode.java @@ -0,0 +1,63 @@ +class PerfectBinaryTreeCode { + + static class Node { + int key; + Node left, right; + } + + // Calculate the depth + static int depth(Node node) { + int d = 0; + while (node != null) { + d++; + node = node.left; + } + return d; + } + + // Check if the tree is perfect binary tree + static boolean is_perfect(Node root, int d, int level) { + + // Check if the tree is empty + if (root == null) + return true; + + // If for children + if (root.left == null && root.right == null) + return (d == level + 1); + + if (root.left == null || root.right == null) + return false; + + return is_perfect(root.left, d, level + 1) && is_perfect(root.right, d, level + 1); + } + + // Wrapper function + static boolean is_Perfect(Node root) { + int d = depth(root); + return is_perfect(root, d, 0); + } + + // Create a new node + static Node newNode(int k) { + Node node = new Node(); + node.key = k; + node.right = null; + node.left = null; + return node; + } + + public static void main(String args[]) { + Node root = null; + root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + + if (is_Perfect(root) == true) + System.out.println("The tree is a perfect binary tree"); + else + System.out.println("The tree is not a perfect binary tree"); + } +} \ No newline at end of file From 7e383e3b562e2d6549b2dd7bb49d8c9e15ee02bd Mon Sep 17 00:00:00 2001 From: Shubh Agrawal <49271775+shubhagrawal123456@users.noreply.github.com> Date: Sun, 2 Oct 2022 12:49:27 +0530 Subject: [PATCH 184/278] Minimum Interval to include each query This can be solved using some clever sorting (missed this by less than a minute during the contest :O/ ) This is both 100% faster and 100% more memory efficient than other C++ solutions Sort the intervals by their range (shorter ranges first) Then take each range one by one, find all queries that belong in that range and set their value to (end - start + 1) For implementation, I used a set to track queries and after populating each query, I'd remove it from the set as we no longer need to worry about it To enhance performance, once I find the lower_bound, I increment the iterator and keep deleting any values that are within the interval. --- CPP/Minimum_Interval_to_Include_Each_Query | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 CPP/Minimum_Interval_to_Include_Each_Query diff --git a/CPP/Minimum_Interval_to_Include_Each_Query b/CPP/Minimum_Interval_to_Include_Each_Query new file mode 100644 index 0000000..6d5988e --- /dev/null +++ b/CPP/Minimum_Interval_to_Include_Each_Query @@ -0,0 +1,27 @@ +//1851. Minimum Interval to Include Each Query +//https://leetcode.com/problems/minimum-interval-to-include-each-query/ + +class Solution { +public: + vector minInterval(vector>& intervals, vector& queries) { + sort(intervals.begin(), intervals.end(), [&](const vector &x, const vector &y) { + return x[1] - x[0] < y[1] - y[0]; + }); + int i, n = queries.size(); + vector ret(n, -1); + set> st; + for(i=0; ifirst <= end) { + auto it2 = next(it); + ret[it->second] = end - start + 1; + st.erase(it); + it = it2; + } + } + return ret; + } +}; From 32718d2b800122d3ab8702431e57568be89300d7 Mon Sep 17 00:00:00 2001 From: shubham-7430 <114841302+shubham-7430@users.noreply.github.com> Date: Sun, 2 Oct 2022 12:59:22 +0530 Subject: [PATCH 185/278] bst From 08928963ede1255d879543a4f4dfc320cb5efc5d Mon Sep 17 00:00:00 2001 From: Aalim aslam <67648366+aalimaslam@users.noreply.github.com> Date: Sun, 2 Oct 2022 00:35:31 -0700 Subject: [PATCH 186/278] Hacktoberfest-2022 --- Javascript/bucketsort.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Javascript/bucketsort.js diff --git a/Javascript/bucketsort.js b/Javascript/bucketsort.js new file mode 100644 index 0000000..dbd5d9a --- /dev/null +++ b/Javascript/bucketsort.js @@ -0,0 +1,28 @@ +const bucketSort = (arr, n = arr.length) => { + //Create a bucket array + let bucket = new Array(n); + + //Add bucket group + for(let i = 0; i < n; i++){ + bucket[i] = []; + } + + //Add the elements in a same range in bucket + for(let i = 0; i < n; i++){ + let bucketIndex = Math.floor(arr[i]) * n; + bucket[bucketIndex].push(arr[i]); + } + + //Sort each bucket separately + for(let i = 0; i < n; i++){ + bucket[i].sort(); + } + + // Get the sorted array + let index = 0; + for (let i = 0; i < n; i++) { + for (let j = 0, size = bucket[i].length; j < size; j++) { + arr[index++] = bucket[i][j]; + } + } +} From 6178fcc1128be2c3f9ce29b45401b1232b90142d Mon Sep 17 00:00:00 2001 From: fiza0786 <92218448+fiza0786@users.noreply.github.com> Date: Sun, 2 Oct 2022 13:21:54 +0530 Subject: [PATCH 187/278] Create twoDigitSum_and_divide.c --- C/twoDigitSum_and_divide.c | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C/twoDigitSum_and_divide.c diff --git a/C/twoDigitSum_and_divide.c b/C/twoDigitSum_and_divide.c new file mode 100644 index 0000000..66370e7 --- /dev/null +++ b/C/twoDigitSum_and_divide.c @@ -0,0 +1,29 @@ + #include +void main() +{ + int number= 10; + int t , rem, sum=0; + + + + // printf("%d",sum); + + for(int i=1 ; i<=1000; i++) + { + if(i%number==0 && i!=number) + { + t=i; + while(t!=0) + { + rem = t%10; + sum=sum+rem; + t=t/10; + } + if(sum==number) + { + printf("%d\n",i); + } + } + + } +} From 250d7faaf2bdde4900949a0f4d4eb6e6f055f895 Mon Sep 17 00:00:00 2001 From: Harsh Kashiwal <77677724+KashiwalHarsh@users.noreply.github.com> Date: Sun, 2 Oct 2022 13:22:31 +0530 Subject: [PATCH 188/278] Radix sort code --- Radix-sort.exe | Bin 0 -> 51986 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Radix-sort.exe diff --git a/Radix-sort.exe b/Radix-sort.exe new file mode 100644 index 0000000000000000000000000000000000000000..c2a9ea90d56f0a25cc3952e00761148959af124b GIT binary patch literal 51986 zcmeIb4SZDBbuYT-Lue2}A0T1bmc!T)ws1g5AY`z?(MTGh38N2dMi?;mVVD_76Gocx ze1LFq0}+au4oa2ZbyBBwZ=vSh`lU|d_PRDs{1Rb^!LgH2*GWiB5|Wa32)H3N&!ILq z^Zsk^^D$?Rgl$55f4R>Gj?Ov%z4lsbuf6u#ALqSJ&4*0x@7(Mi48`rySY#mP8?yU-!^4q;eM`_DOAgyZ!}hjrk9{Z-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W}shHCv<`OR0Mo_!(!6~tj zr8ug7D0{`wExUGZh*Sd=ijp6uV0C=(9aTk9T@gy1Ax&K{VCI7Zgj+SR=qFvPSGLiRlRaJ}NlXq3F^<5LiRGWC zTIjwrqbZ_q#;yRlr7&=g@hQ+Dzz-<}@ZubmmuLA6jWCN6qOT~qASX4 z%hYzX3Lwvirzr-3J&_f!Ay)x7IWB(N69Qi&3lcqGhFe&0zBpi2QD(%EX zFg8^WF9@~D)U56uL<hi6$8i z@&yUujFB+fk3XuuQAnYa?_{6~!S4Ons?@E zi^@WOZ!Cq@422^rOQ*7Jx2a88BpdpC_W Tm*>~em7}TrJi-45=6=qg literal 0 HcmV?d00001 From 2a030baa886546bcb212f12585408163c5fd2a59 Mon Sep 17 00:00:00 2001 From: Harsh Kashiwal <77677724+KashiwalHarsh@users.noreply.github.com> Date: Sun, 2 Oct 2022 13:25:21 +0530 Subject: [PATCH 189/278] Radix-sort-code --- Radix-sort.cpp | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Radix-sort.cpp diff --git a/Radix-sort.cpp b/Radix-sort.cpp new file mode 100644 index 0000000..a7c2e8f --- /dev/null +++ b/Radix-sort.cpp @@ -0,0 +1,55 @@ +#include +using namespace std; + +int getMax(int arr[], int n) +{ + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; +} + +void countSort(int arr[], int n, int exp) +{ + int output[n]; + int i, count[10] = { 0 }; + + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + for (i = 0; i < n; i++) + arr[i] = output[i]; +} + +void radixsort(int arr[], int n) +{ + int m = getMax(arr, n); + + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); +} + +void print(int arr[], int n) +{ + for (int i = 0; i < n; i++) + cout << arr[i] << " "; +} + +int main() +{ + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = sizeof(arr) / sizeof(arr[0]); + + radixsort(arr, n); + print(arr, n); + return 0; +} \ No newline at end of file From 32e4e2d8db1dcf566e70c77a030ee6e59fe14906 Mon Sep 17 00:00:00 2001 From: rs2028 <114852198+rs2028@users.noreply.github.com> Date: Sun, 2 Oct 2022 13:28:16 +0530 Subject: [PATCH 190/278] Bubble Sort Program In Java --- BubbleSortProgram.java | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 BubbleSortProgram.java diff --git a/BubbleSortProgram.java b/BubbleSortProgram.java new file mode 100644 index 0000000..f91b7c5 --- /dev/null +++ b/BubbleSortProgram.java @@ -0,0 +1,35 @@ +public class BubbleSortExampleJava { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} \ No newline at end of file From ce627a4a3837f329f337eabecadcf174fae15adf Mon Sep 17 00:00:00 2001 From: SREERAGRAYIRATH404 <90212360+SREERAGRAYIRATH404@users.noreply.github.com> Date: Sun, 2 Oct 2022 13:33:25 +0530 Subject: [PATCH 191/278] main --- main.cpp | 4165 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 4165 insertions(+) create mode 100644 main.cpp diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..4706d4b --- /dev/null +++ b/main.cpp @@ -0,0 +1,4165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Snake-CPP/main.cpp at main · imharris24/Snake-CPP + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+ Skip to content + + + + + + + + + + + + + + +
+ +
+ + + + + + + +
+ + + + + +
+ + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + +
+ +
+ + + + imharris24  /   + Snake-CPP  /   + +
+
+ + + +
+ + +
+
+ Clear Command Palette +
+
+ + + +
+
+ Tip: + Type # to search pull requests +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type # to search issues +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type # to search discussions +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type ! to search projects +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type @ to search teams +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type @ to search people and organizations +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type > to activate command mode +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Go to your accessibility settings to change your keyboard shortcuts +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type author:@me to search your content +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:pr to filter to pull requests +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:issue to filter to issues +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:project to filter to projects +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:open to filter to open content +
+
+ Type ? for help and tips +
+
+
+ +
+ +
+
+ We’ve encountered an error and some results aren't available at this time. Type a new search or try again later. +
+
+ + No results matched your search + + + + + + + + + + +
+ + + + + Search for issues and pull requests + + # + + + + Search for issues, pull requests, discussions, and projects + + # + + + + Search for organizations, repositories, and users + + @ + + + + Search for projects + + ! + + + + Search for files + + / + + + + Activate command mode + + > + + + + Search your issues, pull requests, and discussions + + # author:@me + + + + Search your issues, pull requests, and discussions + + # author:@me + + + + Filter to pull requests + + # is:pr + + + + Filter to issues + + # is:issue + + + + Filter to discussions + + # is:discussion + + + + Filter to projects + + # is:project + + + + Filter to open issues, pull requests, and discussions + + # is:open + + + + + + + + + + + + + + + + +
+
+
+ +
+ + + + + + + + + + +
+ + +
+
+
+ + + + + + + + + +
+ +
+ +
+ +
+ + + + / + + Snake-CPP + + + Public +
+ + +
+ +
    + + + +
  • + +
    + + + + + + + Watch + + + 1 + + + +
    +
    +

    Notifications

    + +
    + +
    +
    + + + + + + + + +
    + + +
    + + + + + Get push notifications on iOS or Android. + +
    +
    +
    +
    + + + + +
    +
    +
    + + + +
  • + +
  • +
    + Fork + 1 + +
    + + + +
    + +
    +
    + + + + + + + +
    + +
    +
    +
    +
    +
  • + +
  • + + +
    +
    + + +
    +
    + +
    + + + +
    + +
    +
    + + + + + + + +
    + +
    +
    +
    +
    +
    +
  • + + + +
+ +
+ +
+
+ + + + +
+ + + + + +
+ Open in github.dev + Open in a new github.dev tab + + + + + + +
+ + +
+ + + + + + + + +Permalink + +
+ +
+
+ + + main + + + + +
+
+
+ Switch branches/tags + +
+ + + +
+ +
+ +
+ + +
+ +
+ + + + + + + + + + + + + + + +
+ + +
+
+
+
+ +
+ +
+ + + Go to file + +
+ + + + +
+
+
+ + + + + + + + + +
+ +
+
+
 
+
+ +
+
 
+ Cannot retrieve contributors at this time +
+
+ + + + + + + + + + + + + +
+ +
+ + +
+ + 351 lines (347 sloc) + + 11.7 KB +
+ +
+ + + + +
+ +
+
+
+
+ +
+ +
+
+
+ + + +
+
+ + +
+ +
+
+ +
+ +
+
+ + + +
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#include <iostream>
#include <conio.h>
#include <string>
#include <windows.h>
using namespace std;
+
class SnakeGame {
private:
enum Direction {
STOP = 0,
LEFT,
RIGHT,
UP,
DOWN
};
Direction SnakeDirection;
int SnakeBodyCount;
bool GameOver;
bool BodyPrintFlag;
const int Width;
const int Height;
int SnakeHeadX, SnakeHeadY, FruitX, FruitY;
int SnakeX[100], SnakeY[100];
static void DisplayMainMenu();
static void DisplayGameOver();
static void DisplayInstructions();
static void DisplayCredits();
void ControllerInput();
void SetupGame();
void PrintStage();
void PlayStage();
void PlayGame();
public:
SnakeGame();
void StartGame();
};
+
SnakeGame::SnakeGame() :Height(22), Width(52) {
SnakeBodyCount = 0;
GameOver = false;
BodyPrintFlag = false;
SnakeHeadX = 0;
SnakeHeadY = 0;
FruitX = 0;
FruitY = 0;
for (int i = 0; i < 100; i++) {
SnakeX[i] = 0;
SnakeY[i] = 0;
}
}
void SnakeGame::DisplayMainMenu() {
cout << " ===========================================================================\n";
cout << " || ||\n";
cout << " || *SNAKE GAME* ||\n";
cout << " || ||\n";
cout << " || __ __ __ __ ||\n";
cout << " || / \\ / \\ / \\ / \\ ||\n";
cout << " ||____________________/ __\\/ __\\/ __\\/ __\\___________________________||\n";
cout << " ||___________________/ /__/ /__/ /__/ /______________________________||\n";
cout << " || | / \\ / \\ / \\ / \\ \\____ ||\n";
cout << " || |/ \\_/ \\_/ \\_/ \\ o \\ ||\n";
cout << " || \\_____/--< ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || *Menu* ||\n";
cout << " || ||\n";
cout << " || -> 1. Play Game ||\n";
cout << " || -> 2. Instructions ||\n";
cout << " || -> 3. Credits ||\n";
cout << " || -> 4. Exit ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " ===========================================================================\n";
}
void SnakeGame::DisplayGameOver() {
cout << " ===========================================================================\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ____ _ __ __ _____ _____ _______ ____ ||\n";
cout << " || / ___| / \\ | \\/ | ____/ _ \\ \\ / / ____| _ \\ ||\n";
cout << " || | | _ / _ \\ | |\\/| | _|| | | \\ \\ / /| _| | |_) | ||\n";
cout << " || | |_| |/ ___ \\| | | | |__| |_| |\\ \V / | |___| _ < ||\n";
cout << " || \\____/_/ \\_\\_| |_|_____\\___/ \\_/ |_____|_| \\_\\ ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || PRESS ANY KEY TO RETURN TO MENU ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " ===========================================================================\n";
}
void SnakeGame::DisplayInstructions() {
cout << " ===========================================================================\n";
cout << " || ||\n";
cout << " || *Instructions* ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ____ ||\n";
cout << " || ________________________/ O \\___/ ||\n";
cout << " || <_____________________________/ \\ ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || 1. W,A,S,D to change direction of the Snake. ||\n";
cout << " || 2. Eat the Fruit to Make the Snake Grow. With ||\n";
cout << " || each fruit 10 Points will be Added to the ||\n";
cout << " || score. ||\n";
cout << " || 3. If Snake eats itself, game will be over. ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || PRESS ANY KEY TO RETURN TO MENU ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " ===========================================================================\n";
}
void SnakeGame::DisplayCredits() {
cout << " ===========================================================================\n";
cout << " || ||\n";
cout << " || *Credits* ||\n";
cout << " || ||\n";
cout << " || Game Developed by ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ) ( ( ( ( ||\n";
cout << " || ( /( ( )\\ ) )\\ ) )\\ ) )\\ ) ||\n";
cout << " || )\\()) )\\ (()/( (()/( (()/( (()/( ||\n";
cout << " || ((_)\\ ((((_)( /(_)) /(_)) /(_)) /(_)) ||\n";
cout << " || _((_) )\\ _ )\\ (_)) (_)) (_)) (_)) ||\n";
cout << " || | || | (_)_\\(_) | _ \\ | _ \\ |_ _| / __| ||\n";
cout << " || | __ | / _ \\ | / | / | | \\__ \\\ ||\n";
cout << " || |_||_| /_/ \\_\\ |_|_\\ |_|_\\ |___| |___/ ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || PRESS ANY KEY TO RETURN TO MENU ||\n";
cout << " || ||\n";
cout << " ===========================================================================\n";
}
void SnakeGame::ControllerInput() {
if (_kbhit())
{
switch (_getch())
{
case 'a':
SnakeDirection = LEFT;
break;
case 'd':
SnakeDirection = RIGHT;
break;
case 'w':
SnakeDirection = UP;
break;
case 's':
SnakeDirection = DOWN;
break;
case 'A':
SnakeDirection = LEFT;
break;
case 'D':
SnakeDirection = RIGHT;
break;
case 'W':
SnakeDirection = UP;
break;
case 'S':
SnakeDirection = DOWN;
break;
default:
break;
}
}
}
void SnakeGame::SetupGame() {
GameOver = false;
SnakeDirection = STOP;
SnakeHeadX = Width / 2;
SnakeHeadY = Height / 2;
FruitX = rand() % Width;
FruitY = rand() % Height;
}
void SnakeGame::PrintStage() {
cout << flush;
system("cls");
for (int i = 0; i < Width + 4; i++)
{
printf("=");
}
cout << "\n";
for (int i = 0; i < Height; i++)
{
for (int j = 0; j < Width; j++)
{
if (j == 0)
{
printf("||");
}
if (i == SnakeHeadY && j == SnakeHeadX)
{
cout << "O";
}
else if (i == FruitY && j == FruitX)
{
cout << "#";
}
else
{
BodyPrintFlag = false;
for (int k = 0; k < SnakeBodyCount; k++)
{
if (SnakeX[k] == j && SnakeY[k] == i)
+
{
cout << "o";
BodyPrintFlag = true;
}
}
if (!BodyPrintFlag)
{
printf(" ");
}
}
if (j == Width - 1)
{
printf("||");
}
}
cout << "\n";
}
for (int i = 0; i < Width + 4; i++)
{
printf("=");
}
}
void SnakeGame::PlayStage() {
int prevX = SnakeX[0];
int prevY = SnakeY[0];
int prev2X, prev2Y;
SnakeX[0] = SnakeHeadX;
SnakeY[0] = SnakeHeadY;
for (int i = 1; i < SnakeBodyCount; i++)
{
prev2X = SnakeX[i];
prev2Y = SnakeY[i];
SnakeX[i] = prevX;
SnakeY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (SnakeDirection)
{
case 1:
SnakeHeadX--;
break;
case 2:
SnakeHeadX++;
break;
case 3:
SnakeHeadY--;
break;
case 4:
SnakeHeadY++;
break;
default:
break;
}
if (SnakeHeadX >= Width)
{
SnakeHeadX = 0;
}
else if (SnakeHeadX < 0)
{
SnakeHeadX = Width - 1;
}
if (SnakeHeadY >= Height)
{
SnakeHeadY = 0;
}
else if (SnakeHeadY < 0)
{
SnakeHeadY = Height - 1;
}
for (int i = 0; i < SnakeBodyCount; i++)
{
if (SnakeX[i] == SnakeHeadX && SnakeY[i] == SnakeHeadY)
{
GameOver = true;
}
}
if (SnakeHeadX == FruitX && SnakeHeadY == FruitY)
{
FruitX = rand() % Width;
FruitY = rand() % Height;
SnakeBodyCount += 1;;
}
}
void SnakeGame::PlayGame() {
SetupGame();
while (!GameOver)
{
PrintStage();
ControllerInput();
PlayStage();
Sleep(100);
}
}
void SnakeGame::StartGame() {
char opt = '\0';
while (true) {
system("cls");
DisplayMainMenu();
opt = _getch();
system("cls");
switch (opt) {
case '1':
PlayGame();
system("cls");
DisplayGameOver();
_getch();
break;
case '2':
DisplayInstructions();
_getch();
break;
case '3':
DisplayCredits();
_getch();
break;
case '4':
cout << "Closing Snake Game";
for (int i = 0; i < 4; i++) {
Sleep(600);
cout << ".";
exit(-1);
}
break;
default:
break;
}
}
}
+
int main() {
SnakeGame Snake;
Snake.StartGame();
return 0;
}
+
+ + + +
+ +
+ + + + +
+ + +
+ + +
+
+ + +
+ +
+ + +
+ +
+ + +
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + From 608000446774f30a8b936764a0559620adbbb699 Mon Sep 17 00:00:00 2001 From: Aalim aslam <67648366+aalimaslam@users.noreply.github.com> Date: Sun, 2 Oct 2022 01:04:44 -0700 Subject: [PATCH 192/278] Hacktoberfest-2022 --- Javascript/heapsort.js | 93 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Javascript/heapsort.js diff --git a/Javascript/heapsort.js b/Javascript/heapsort.js new file mode 100644 index 0000000..acde722 --- /dev/null +++ b/Javascript/heapsort.js @@ -0,0 +1,93 @@ +//Heap sort algorithm in Javascript using Max-heap + +const maxHeapify = (arr, n, i) => { + let largest = i; + let l = 2 * i + 1; //left child index + let r = 2 * i + 2; //right child index + + //If left child is smaller than root + if (l < n && arr[l] > arr[largest]) { + largest = l; + } + + // If right child is smaller than smallest so far + if (r < n && arr[r] > arr[largest]) { + largest = r; + } + + // If smallest is not root + if (largest != i) { + let temp = arr[i]; + arr[i] = arr[largest]; + arr[largest] = temp; + + // Recursively heapify the affected sub-tree + maxHeapify(arr, n, largest); + } +} + + // main function to do heap sort + const heapSort = (arr, n) => { + // Build heap (rearrange array) + for (let i = parseInt(n / 2 - 1); i >= 0; i--) { + maxHeapify(arr, n, i); + } + + // One by one extract an element from heap + for (let i = n - 1; i >= 0; i--) { + // Move current root to end + let temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // call max heapify on the reduced heap + maxHeapify(arr, i, 0); + } + } + + // Sort in descending order using Heap sort and Min-heap + + const minHeapify = (arr, n, i) => { + let smallest = i; + let l = 2 * i + 1; //left child index + let r = 2 * i + 2; //right child index + + //If left child is smaller than root + if (l < n && arr[l] < arr[smallest]) { + smallest = l; + } + + // If right child is smaller than smallest so far + if (r < n && arr[r] < arr[smallest]) { + smallest = r; + } + + // If smallest is not root + if (smallest != i) { + let temp = arr[i]; + arr[i] = arr[smallest]; + arr[smallest] = temp; + + // Recursively heapify the affected sub-tree + minHeapify(arr, n, smallest); + } +} + + // main function to do heap sort + const heapSort = (arr, n) => { + // Build heap (rearrange array) + for (let i = parseInt(n / 2 - 1); i >= 0; i--) { + minHeapify(arr, n, i); + } + + // One by one extract an element from heap + for (let i = n - 1; i >= 0; i--) { + // Move current root to end + let temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // call max heapify on the reduced heap + minHeapify(arr, i, 0); + } + } From 14d4f0736052df80385946d683ab3fd2bdb17561 Mon Sep 17 00:00:00 2001 From: Harsh Kashiwal <77677724+KashiwalHarsh@users.noreply.github.com> Date: Sun, 2 Oct 2022 13:36:37 +0530 Subject: [PATCH 193/278] Count-sort-code --- Count-sort.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Count-sort.cpp diff --git a/Count-sort.cpp b/Count-sort.cpp new file mode 100644 index 0000000..524fb38 --- /dev/null +++ b/Count-sort.cpp @@ -0,0 +1,34 @@ +#include +#include +using namespace std; +#define RANGE 255 + +void countSort(char arr[]) +{ + char output[strlen(arr)]; + + int count[RANGE + 1], i; + memset(count, 0, sizeof(count)); + for (i = 0; arr[i]; ++i) + ++count[arr[i]]; + + for (i = 1; i <= RANGE; ++i) + count[i] += count[i - 1]; + for (i = 0; arr[i]; ++i) { + output[count[arr[i]] - 1] = arr[i]; + --count[arr[i]]; + } + + for (i = 0; arr[i]; ++i) + arr[i] = output[i]; +} + +int main() +{ + char arr[] = "harshkashiwal"; + + countSort(arr); + + cout << "Sorted array" << arr; + return 0; +} \ No newline at end of file From 442836ff9b247d7ac57e08e96e68d200fc9b115b Mon Sep 17 00:00:00 2001 From: Aneesh Tripathi <85986613+Aneesh-07@users.noreply.github.com> Date: Sun, 2 Oct 2022 13:40:26 +0530 Subject: [PATCH 194/278] Add files via upload --- CPP/Concatenation_of_consecutive_binary.cpp | 38 +++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 CPP/Concatenation_of_consecutive_binary.cpp diff --git a/CPP/Concatenation_of_consecutive_binary.cpp b/CPP/Concatenation_of_consecutive_binary.cpp new file mode 100644 index 0000000..685f35b --- /dev/null +++ b/CPP/Concatenation_of_consecutive_binary.cpp @@ -0,0 +1,38 @@ + +/*Approach: + +Iterate through the numbers from 1 to n and add the binary representation of each number to the answer. +ans = ans<<(number of bits in the binary representation of the current number) + binary representation of the current number.*/ + + + +#include + +using namespace std; +typedef long long ll; +class Solution { +public: + int concatenatedBinary(int n) { + const unsigned int m = 1000000007; + + ll res = 1,sum=0; + for(ll j=2;j<=n;j++){ + ll i=j,c=0; + while(i){ + c++; + i= i >> 1; + + }res = ((res << c)+j) %m; + + } + return res; + + } +}; +int main() { + Solution S; + int n; + std::cout << "Enter value n" << std::endl; + std::cin >> n; + std::cout << S.concatenatedBinary(n) << std::endl; +} From c3ad6f2a6939d045647d70733ba4e8830e89a908 Mon Sep 17 00:00:00 2001 From: Harsh Kashiwal <77677724+KashiwalHarsh@users.noreply.github.com> Date: Sun, 2 Oct 2022 13:41:53 +0530 Subject: [PATCH 195/278] Heap-sort-code --- CPP/Heap-sort.cpp | 57 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 CPP/Heap-sort.cpp diff --git a/CPP/Heap-sort.cpp b/CPP/Heap-sort.cpp new file mode 100644 index 0000000..b1575c7 --- /dev/null +++ b/CPP/Heap-sort.cpp @@ -0,0 +1,57 @@ + #include +using namespace std; + +void heapify(int arr[], int N, int i) +{ + 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; + + if (largest != i) { + swap(arr[i], arr[largest]); + + heapify(arr, N, largest); + } +} + + +void heapSort(int arr[], int N) +{ + + + for (int i = N / 2 - 1; i >= 0; i--) + heapify(arr, N, i); + + + for (int i = N - 1; i > 0; i--) { + + swap(arr[0], arr[i]); + heapify(arr, i, 0); + } +} + +void printArray(int arr[], int N) +{ + for (int i = 0; i < N; ++i) + cout << arr[i] << " "; + cout << "\n"; +} + +int main() +{ + int arr[] = { 12, 11, 13, 5, 6, 7 }; + int N = sizeof(arr) / sizeof(arr[0]); + + heapSort(arr, N); + + cout << "Sorted array is \n"; + printArray(arr, N); +} \ No newline at end of file From 7ea31ba7432aa6693b8d3bf077802646330f450e Mon Sep 17 00:00:00 2001 From: Harsh Kashiwal <77677724+KashiwalHarsh@users.noreply.github.com> Date: Sun, 2 Oct 2022 13:43:17 +0530 Subject: [PATCH 196/278] Shell-sort-code --- Shell-sort.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Shell-sort.cpp diff --git a/Shell-sort.cpp b/Shell-sort.cpp new file mode 100644 index 0000000..2f33202 --- /dev/null +++ b/Shell-sort.cpp @@ -0,0 +1,41 @@ +#include +using namespace std; + +int shellSort(int arr[], int n) +{ + for (int gap = n/2; gap > 0; gap /= 2) + { + for (int i = gap; i < n; i += 1) + { + int temp = arr[i]; + int j; + for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) + arr[j] = arr[j - gap]; + + arr[j] = temp; + } + } + return 0; +} + +void printArray(int arr[], int n) +{ + for (int i=0; i Date: Sun, 2 Oct 2022 13:44:49 +0530 Subject: [PATCH 197/278] Bucket-sort-code --- Bucket-sort.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Bucket-sort.cpp diff --git a/Bucket-sort.cpp b/Bucket-sort.cpp new file mode 100644 index 0000000..76f719a --- /dev/null +++ b/Bucket-sort.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +using namespace std; + +void bucketSort(float arr[], int n) +{ + + vector b[n]; + + for (int i = 0; i < n; i++) { + int bi = n * arr[i]; + b[bi].push_back(arr[i]); + } + + for (int i = 0; i < n; i++) + sort(b[i].begin(), b[i].end()); + + int index = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < b[i].size(); j++) + arr[index++] = b[i][j]; +} + +int main() +{ + float arr[] + = { 0.8, 0.5, 0.6, 0.1, 0.6, 0.3 }; + int n = sizeof(arr) / sizeof(arr[0]); + bucketSort(arr, n); + + cout << "Sorted array : \n"; + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + return 0; +} \ No newline at end of file From 2ae2b2c8f9dac9be89c23cd867b6b5d4809111f1 Mon Sep 17 00:00:00 2001 From: Suraj Kumar Sharma <72158521+surajsharma14@users.noreply.github.com> Date: Sun, 2 Oct 2022 13:54:42 +0530 Subject: [PATCH 198/278] Added heap sort.md --- Heapsort.cpp | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Heapsort.cpp diff --git a/Heapsort.cpp b/Heapsort.cpp new file mode 100644 index 0000000..d8e1c40 --- /dev/null +++ b/Heapsort.cpp @@ -0,0 +1,52 @@ +#include +using namespace std; + +void heapify(int arr[], int n, int i) +{ + 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; + + if (largest != i) { + swap(arr[i], arr[largest]); + + heapify(arr, n, largest); + } +} +void heapSort(int arr[], int n) +{ + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + for (int i = n - 1; i > 0; i--) { + + swap(arr[0], arr[i]); + heapify(arr, i, 0); + } +} + + +void printArray(int arr[], int n) +{ + for (int i = 0; i < n; ++i) + cout << arr[i] << " "; + cout << "\n"; +} + + +int main() +{ + int arr[] = { 12, 11, 13, 5, 6, 7 }; + int n = sizeof(arr) / sizeof(arr[0]); + + heapSort(arr, n); + + cout << "Sorted array is \n"; + printArray(arr, n); +} From 7800096489ec6d4790a0e728b1efc42a6c931f8c Mon Sep 17 00:00:00 2001 From: Krishna Bhadauria <103627548+Krishnabhadauria@users.noreply.github.com> Date: Sun, 2 Oct 2022 14:05:10 +0530 Subject: [PATCH 199/278] Create insertionsort.cpp --- insertionsort.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 insertionsort.cpp diff --git a/insertionsort.cpp b/insertionsort.cpp new file mode 100644 index 0000000..d790a2d --- /dev/null +++ b/insertionsort.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; +void insertionSort(int arr[], int n) +{ + int i, key, j; + for (i = 1; i < n; i++) + { + key = arr[i]; + j = i - 1; + while (j >= 0 && arr[j] > key) + { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } +} +void printArray(int arr[], int n) +{ + int i; + for (i = 0; i < n; i++) + cout << arr[i] << " "; + cout << endl; +} +int main() +{ + int arr[] = { 12, 11, 13, 5, 6 }; + int N = sizeof(arr) / sizeof(arr[0]); + insertionSort(arr, N); + printArray(arr, N); + return 0; +} + From 9f88c1f3418ab8c4f44ca01f4acd9892e43ad4f6 Mon Sep 17 00:00:00 2001 From: Akash Das <95500036+MrfoxAK@users.noreply.github.com> Date: Sun, 2 Oct 2022 14:08:40 +0530 Subject: [PATCH 200/278] Update 1_Singly_Linked_List.py --- Python/1_Singly_Linked_List.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/Python/1_Singly_Linked_List.py b/Python/1_Singly_Linked_List.py index 7453d11..461e640 100644 --- a/Python/1_Singly_Linked_List.py +++ b/Python/1_Singly_Linked_List.py @@ -76,6 +76,23 @@ def display(self): print(ptr.data, end = "->") ptr = ptr.next print("Null") + + + +# Linked List class contains a Node object +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + # This function prints contents of linked list + # starting from head + def printList(self): + temp = self.head + while (temp): + print(temp.data) + temp = temp.next if __name__ == "__main__": listObject = SingleLinkedList() @@ -95,4 +112,4 @@ def display(self): listObject.insertion_at_beg(Node(10)) listObject.display() listObject.deletion_at_end() - listObject.display() \ No newline at end of file + listObject.display() From e32865864b160396b1ab042255d29c55943453a4 Mon Sep 17 00:00:00 2001 From: STREIN_11 <71601569+STREIN-11@users.noreply.github.com> Date: Sun, 2 Oct 2022 14:15:20 +0530 Subject: [PATCH 201/278] Create Array_Rotate.c --- Array_Rotate.c | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Array_Rotate.c diff --git a/Array_Rotate.c b/Array_Rotate.c new file mode 100644 index 0000000..60f788a --- /dev/null +++ b/Array_Rotate.c @@ -0,0 +1,34 @@ +#include + +void rotate(int arr[], int n) +{ + int x = arr[n - 1], i; + for (i = n - 1; i > 0; i--) + arr[i] = arr[i - 1]; + arr[0] = x; +} + +int main() +{ + int size, i; + printf("Enter Size : "); + scanf("%d", &size); + int arr[size]; + printf("Enter Array Elements : "); + for (i = 0; i < size; i++) + { + scanf("%d", &arr[i]); + } + + printf("Given array is\n"); + for (i = 0; i < size; i++) + printf("%d ", arr[i]); + + rotate(arr, size); + + printf("\nRotated array is\n"); + for (i = 0; i < size; i++) + printf("%d ", arr[i]); + + return 0; +} From 1330f33bcf4ad9a61d37c1837ff1250c314c261e Mon Sep 17 00:00:00 2001 From: Ritanshusharma2 <72288468+Ritanshusharma2@users.noreply.github.com> Date: Sun, 2 Oct 2022 14:19:37 +0530 Subject: [PATCH 202/278] added radix sort program.md Added radix sort program in Cpp --- radixsort.cpp | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 radixsort.cpp diff --git a/radixsort.cpp b/radixsort.cpp new file mode 100644 index 0000000..36b69a8 --- /dev/null +++ b/radixsort.cpp @@ -0,0 +1,75 @@ +// C++ implementation of Radix Sort + +#include +using namespace std; + +// A utility function to get maximum value in arr[] +int getMax(int arr[], int n) +{ + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; +} + +// A function to do counting sort of arr[] according to +// the digit represented by exp. +void countSort(int arr[], int n, int exp) +{ + int output[n]; // output array + int i, count[10] = { 0 }; + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains actual + // position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current digit + for (i = 0; i < n; i++) + arr[i] = output[i]; +} + +// The main function to that sorts arr[] of size n using +// Radix Sort +void radixsort(int arr[], int n) +{ + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // 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 + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); +} + +// A utility function to print an array +void print(int arr[], int n) +{ + for (int i = 0; i < n; i++) + cout << arr[i] << " "; +} + +// Driver Code +int main() +{ + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = sizeof(arr) / sizeof(arr[0]); + + // Function Call + radixsort(arr, n); + print(arr, n); + return 0; +} From a09e293ea80423860fabc132e64527a0b1ee92ce Mon Sep 17 00:00:00 2001 From: STREIN_11 <71601569+STREIN-11@users.noreply.github.com> Date: Sun, 2 Oct 2022 14:20:15 +0530 Subject: [PATCH 203/278] Create Binary_Array_sorting.c --- Binary_Array_sorting.c | 56 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Binary_Array_sorting.c diff --git a/Binary_Array_sorting.c b/Binary_Array_sorting.c new file mode 100644 index 0000000..e4b7102 --- /dev/null +++ b/Binary_Array_sorting.c @@ -0,0 +1,56 @@ +// { Driver Code Starts +//Initial template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function template for C++ + +// binArray is an array that consists only 0s and 1s +// return sorted binary array +class Solution{ + public: + vector SortBinaryArray(vector binArray) + { + // Your code goes here + int oneInd = -1; + for(int ind=0; ind>t; + + while(t--) + { + int n; + cin>>n; + vector binArray(n); + + for(int i = 0; i < n; i++) + cin>>binArray[i]; + Solution ob; + vector result = ob.SortBinaryArray(binArray); + for(int i=0; i Date: Sun, 2 Oct 2022 14:22:02 +0530 Subject: [PATCH 204/278] Create insertion.java --- insertion.java | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 insertion.java diff --git a/insertion.java b/insertion.java new file mode 100644 index 0000000..f7e432b --- /dev/null +++ b/insertion.java @@ -0,0 +1,29 @@ +class InsertionSort { + void sort(int arr[]) + { + int n = arr.length; + for (int i = 1; i < n; ++i) { + int key = arr[i]; + int j = i - 1; + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + } + 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[] = { 12, 11, 13, 5, 6 }; + InsertionSort ob = new InsertionSort(); + ob.sort(arr); + printArray(arr); + } +} From 51304304dd8d138ab2b62d7e45711fa358e0546c Mon Sep 17 00:00:00 2001 From: Abhijit Ganguly <105243912+Abhijit-011@users.noreply.github.com> Date: Sun, 2 Oct 2022 14:24:06 +0530 Subject: [PATCH 205/278] Create missing_reapeat.c --- missing_reapeat.c | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 missing_reapeat.c diff --git a/missing_reapeat.c b/missing_reapeat.c new file mode 100644 index 0000000..01b634c --- /dev/null +++ b/missing_reapeat.c @@ -0,0 +1,29 @@ +#include +#include + +void cal(int arr[],int size){ + int c; + for (int i = 0; i < size; i++) + { + if (arr[i] == arr[i+1]) + { + printf("%d it is same to %d\n",arr[i+1],arr[i]); + c = arr[i+1]-1; + printf("missing : %d\n",c); + } + } +} + +int main(int argc, char const *argv[]){ + int size; + printf("Enter Size : "); + scanf("%d",&size); + int arr[size]; + printf("Enter elements : "); + for (int i = 0; i < size; i++){ + scanf("%d",&arr[i]); + } + cal(arr,size); + + return 0; +} From 5f945dd4daf85520eb5dcc436c9c19a5a4929a43 Mon Sep 17 00:00:00 2001 From: STREIN_11 <71601569+STREIN-11@users.noreply.github.com> Date: Sun, 2 Oct 2022 14:25:31 +0530 Subject: [PATCH 206/278] Create missing_jump.cpp --- missing_jump.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 missing_jump.cpp diff --git a/missing_jump.cpp b/missing_jump.cpp new file mode 100644 index 0000000..a472c85 --- /dev/null +++ b/missing_jump.cpp @@ -0,0 +1,43 @@ +#include +using namespace std; + +class Solution{ + public: + int minJumps(int a[], int n){ + int pos = 0; + int jump = 0; + int destination = 0; + for (int i = 0; i < n-1; i++) + { + destination = max(destination, a[i] + i); + if (pos == i) + { + jump++; + if(destination<=i) + { + return -1; + } + pos = destination; + } + } + return jump; + } +}; + +int main() +{ + int t; + cin>>t; + while(t--) + { + int n,i,j; + cin>>n; + int arr[n]; + for(int i=0; i>arr[i]; + Solution obj; + cout< Date: Sun, 2 Oct 2022 14:28:56 +0530 Subject: [PATCH 207/278] Create merger_array.c --- merger_array.c | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 merger_array.c diff --git a/merger_array.c b/merger_array.c new file mode 100644 index 0000000..48300b1 --- /dev/null +++ b/merger_array.c @@ -0,0 +1,60 @@ +#include + +int sorting(int arr[], int n){ + for (int i = 0; i < n; ++i){ + for (int j = i + 1; j < n; ++j){ + if (arr[i] > arr[j]){ + int a = arr[i]; + arr[i] = arr[j]; + arr[j] = a; + } + } + } + for (int i = 0; i < n; ++i){ + // printf("After sorting Result is : %d\n",arr[i]); + } +} + +int plusar(int arr[], int ar[], int cal[], int size,int length,int sum){ + for(int i=0;i< size;i++) + { + cal[i]=arr[i]; + } + + printf("Sum of arrays:-"); + for(int i = 0, j = size; j < sum && i < length; i++, j++) + { + cal[j] = ar[i]; + } +} +int finalsort(int sorting, int plusar,int cal[],int sum){ + for (int i = 0; i < sum; i++) + { + printf(" %d",cal[i]); + } +} + +int main(){ + int size,length,sum,j; + printf("Enter Length for 1st Array : "); + scanf("%d",&size); + printf("Enter Length for 2nd Array : "); + scanf("%d",&length); + sum = size + length; + int arr[size],ar[length]; + int cal[sum]; + printf("Enter 1st Array elements : "); + for (int i = 0; i < size; i++) + { + scanf("%d",&arr[i]); + } + printf("Enter 2nd Array elements : "); + for (int i = 0; i < length; i++) + { + scanf("%d",&ar[i]); + } + int p = plusar(arr,ar,cal,size,length,sum); + int t = sorting(cal,sum); + finalsort(t,p,cal,sum); + return 0; +} From 270875d0e2eae22870b73450cb0f0b83d3193d7b Mon Sep 17 00:00:00 2001 From: STREIN_11 <71601569+STREIN-11@users.noreply.github.com> Date: Sun, 2 Oct 2022 14:32:37 +0530 Subject: [PATCH 208/278] Create kth_small_element.c --- kth_small_element.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 kth_small_element.c diff --git a/kth_small_element.c b/kth_small_element.c new file mode 100644 index 0000000..4e4c4d5 --- /dev/null +++ b/kth_small_element.c @@ -0,0 +1,44 @@ +#include +#include +void sorting(int *arr, int size){ + int temp, sorted = 0; + for (int i = 0; i < size - 1; i++){ + for (int j = 0; j < size - i - 1; j++) + { + if (arr[j] > arr[j + 1]) + { + temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } +} + +void cal(int* arr,int size,int data){ + sorting(arr,size); + for (int i = 0; i < size; i++) + { + if (arr[i]==data) + { + printf("R : %d",arr[i]); + break; + } + } +} + +int main(int argc, char const *argv[]){ + int size,data; + printf("Enter Size : "); + scanf("%d",&size); + int arr[size]; + printf("Enter Array Elements: "); + for (int i = 0; i < size; i++) + { + scanf("%d",&arr[i]); + } + printf("Data : "); + scanf("%d",&data); + cal(arr,size,data); + return 0; +} From 65655a97d6d9803bebacbb07ddc51d76de18556e Mon Sep 17 00:00:00 2001 From: STREIN_11 <71601569+STREIN-11@users.noreply.github.com> Date: Sun, 2 Oct 2022 14:37:00 +0530 Subject: [PATCH 209/278] Create insert.c --- insert.c | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 insert.c diff --git a/insert.c b/insert.c new file mode 100644 index 0000000..7fdaaac --- /dev/null +++ b/insert.c @@ -0,0 +1,62 @@ +#include +#include + +void cal(int arr[], int size) +{ + int pos, el; + printf("Enter new Element : "); + scanf("%d", &el); + printf("Enter The Position : "); + scanf("%d", &pos); + + for (int i = size - 1; i >= pos - 1; i--) + { + arr[i + 1] = arr[i]; + } + arr[pos - 1] = el; +} + +void print(int arr[], int size) +{ + printf("Array : \n"); + for (int i = 0; i < size; i++) + { + printf("%d", arr[i]); + } +} + +void new (int arr[], int size, int t) +{ + cal(arr, size); + for (int i = 0; i < t-1; i++) + { + cal(arr, size); + } + print(arr, size); +} + +int main(int argc, char const *argv[]) +{ + int size, t; + printf("Enter Array Size : "); + scanf("%d", &size); + int arr[size + 10]; + printf("Enter Array Elements : "); + for (int i = 0; i < size; i++) + { + scanf("%d", &arr[i]); + } + printf("How many Elements : "); + scanf("%d", &t); + if (t == 1) + { + cal(arr, size); + print(arr, size); + } + else + { + new (arr, size, t); + } + + return 0; +} From 319bb56febb4efa6669db91f59e3f4345c60e7da Mon Sep 17 00:00:00 2001 From: Rishabh Jain <70846152+Rishabhjain2002@users.noreply.github.com> Date: Sun, 2 Oct 2022 14:38:46 +0530 Subject: [PATCH 210/278] Hactoberfest-2022 please add my file to your repository with label as hacktoberfest-accepted --- infix to postfix using stack.txt | 82 ++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 infix to postfix using stack.txt diff --git a/infix to postfix using stack.txt b/infix to postfix using stack.txt new file mode 100644 index 0000000..6326414 --- /dev/null +++ b/infix to postfix using stack.txt @@ -0,0 +1,82 @@ +/* C++ implementation to convert +infix expression to postfix*/ + +#include +using namespace std; + +// Function to return precedence of operators +int prec(char c) +{ + if (c == '^') + return 3; + else if (c == '/' || c == '*') + return 2; + else if (c == '+' || c == '-') + return 1; + else + return -1; +} + +// The main function to convert infix expression +// to postfix expression +void infixToPostfix(string s) +{ + + stack st; // For stack operations, we are using + // C++ built in stack + string result; + + for (int i = 0; i < s.length(); i++) { + char c = s[i]; + + // If the scanned character is + // an operand, add it to output string. + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') + || (c >= '0' && c <= '9')) + result += c; + + // If the scanned character is an + // ‘(‘, push it to the stack. + else if (c == '(') + st.push('('); + + // If the scanned character is an ‘)’, + // pop and to output string from the stack + // until an ‘(‘ is encountered. + else if (c == ')') { + while (st.top() != '(') { + result += st.top(); + st.pop(); + } + st.pop(); + } + + // If an operator is scanned + else { + while (!st.empty() + && prec(s[i]) <= prec(st.top())) { + result += st.top(); + st.pop(); + } + st.push(c); + } + } + + // Pop all the remaining elements from the stack + while (!st.empty()) { + result += st.top(); + st.pop(); + } + + cout << result << endl; +} + +// Driver's code +int main() +{ + string exp = "a+b*(c^d-e)^(f+g*h)-i"; + + // Function call + infixToPostfix(exp); + return 0; +} From defab8a2f0f6f6c568a0dfe8955994435697ea81 Mon Sep 17 00:00:00 2001 From: Kshitiz Sharma <110187324+kshitiz11101@users.noreply.github.com> Date: Sun, 2 Oct 2022 14:44:29 +0530 Subject: [PATCH 211/278] First and Last Occurrence Binary Search --- First and last binary search .cpp | 66 +++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 First and last binary search .cpp diff --git a/First and last binary search .cpp b/First and last binary search .cpp new file mode 100644 index 0000000..8e77beb --- /dev/null +++ b/First and last binary search .cpp @@ -0,0 +1,66 @@ +#include +using namespace std; +int firstOcurrence(int arr[], int n, int key) +{ + int s = 0; + int e = n - 1; + int mid = s + (e - s) / 2; + int ans = -1; + + while (s <= e) + { + if (arr[mid] == key) + { + ans = mid; + e = mid - 1; + } + else if (key > arr[mid]) // go to right part + { + s = mid + 1; + } + else if (key < arr[mid]) // go to left part + { + e = mid - 1; + } + mid = s + (e - s) / 2; + } +} +int lastOcurrence(int arr[], int n, int key) +{ + int s = 0; + int e = n - 1; + int mid = s + (e - s) / 2; + int ans = -1; + + while (s <= e) + { + if (arr[mid] == key) + { + ans = mid; + s = mid + 1; + } + else if (key > arr[mid]) // Right wale part mei jaana h + { + s = mid + 1; + } + else if (key < arr[mid]) // Left wale part mei jaana h + { + e = mid - 1; + } + mid = s + (e - s) / 2; + } +} + +int main() +{ + int arr[4] = {3, 4, 5, 1}; + int ans = PeakElement(arr, 4); + cout << ans << endl; + // int arr[8] = {1, 2, 3, 3, 3, 3, 3, 5}; + // cout << "First Occurrence of 3 is at index : " << firstOcurrence(arr, 8, 3) << endl; + // cout << "Last Occurence of 3 is at index : " << lastOcurrence(arr, 8, 3) << endl; + // int totalCount = (lastOcurrence(arr, 8, 3) - firstOcurrence(arr, 8, 3)); + // cout << totalCount << endl; + + return 0; +} \ No newline at end of file From aeb35776b130f05e85891e698c3393b04a5b0f82 Mon Sep 17 00:00:00 2001 From: Aneesh Tripathi <85986613+Aneesh-07@users.noreply.github.com> Date: Sun, 2 Oct 2022 15:34:09 +0530 Subject: [PATCH 212/278] Added code for creation of BST from given preorder --- C/BST_from_preorder_in_c.c | 97 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 C/BST_from_preorder_in_c.c diff --git a/C/BST_from_preorder_in_c.c b/C/BST_from_preorder_in_c.c new file mode 100644 index 0000000..dde8e33 --- /dev/null +++ b/C/BST_from_preorder_in_c.c @@ -0,0 +1,97 @@ +/****************************************************************************** + + Given a distinct sequence of keys representing the + preorder sequence of a binary search tree (BST), construct a BST from it.it. + +*******************************************************************************/ + +#include +#include + +// Data structure to store a binary tree node +struct Node +{ + int key; + struct Node *left, *right; +}; + +// Function to create a new binary tree node having a given key +struct Node* newNode(int key) +{ + struct Node* node = (struct Node*)malloc(sizeof(struct Node)); + node->key = key; + node->left = node->right = NULL; + + return node; +} + +// Recursive function to perform inorder traversal on a given binary tree +void inorder(struct Node* root) +{ + if (root == NULL) { + return; + } + + inorder(root->left); + printf("%d ", root->key); + inorder(root->right); +} + +// Recursive function to build a BST from a preorder sequence. +struct Node* constructBST(int preorder[], int start, int end) +{ + // base case + if (start > end) { + return NULL; + } + + // Construct the root node of the subtree formed by keys of the + // preorder sequence in range `[start, end]` + struct Node* node = newNode(preorder[start]); + + // search the index of the first element in the current range of preorder + // sequence larger than the root node's value + int i; + for (i = start; i <= end; i++) + { + if (preorder[i] > node->key) { + break; + } + } + + // recursively construct the left subtree + node->left = constructBST(preorder, start + 1, i - 1); + + // recursively construct the right subtree + node->right = constructBST(preorder, i, end); + + // return current node + return node; +} + +int main(void) +{ + /* Construct the following BST + 15 + / \ + / \ + 10 20 + / \ / \ + / \ / \ + 8 12 16 25 + */ + + int preorder[] = { 15, 10, 8, 12, 20, 16, 25 }; + int n = sizeof(preorder)/sizeof(preorder[0]); + + // construct the BST + struct Node* root = constructBST(preorder, 0, n - 1); + + // print the BST + printf("Inorder traversal of BST is "); + + // inorder on the BST always returns a sorted sequence + inorder(root); + + return 0; +} From 5164266376493df1ab100ffe8b05aa72ef58b70e Mon Sep 17 00:00:00 2001 From: anshika9946 <91412230+anshika9946@users.noreply.github.com> Date: Sun, 2 Oct 2022 15:54:03 +0530 Subject: [PATCH 213/278] TowerOfHanoi --- toweofhanoi.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 toweofhanoi.java diff --git a/toweofhanoi.java b/toweofhanoi.java new file mode 100644 index 0000000..455f5f8 --- /dev/null +++ b/toweofhanoi.java @@ -0,0 +1,27 @@ +/** + * toweofhanoi + */ + +public class toweofhanoi { + + static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) + { + if (n == 1) + { + System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod); + return; + } + towerOfHanoi(n-1, from_rod, aux_rod, to_rod); + System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod); + towerOfHanoi(n-1, aux_rod, to_rod, from_rod); + } + + // Driver method + public static void main(String args[]) + { + int n = 4; // Number of disks + towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods + } + + } + \ No newline at end of file From 5b4ab9bef0ce159a61a2ebd0133e376b26a63242 Mon Sep 17 00:00:00 2001 From: Satyam Srivastava <71383127+SrivastavaSatyam@users.noreply.github.com> Date: Sun, 2 Oct 2022 17:49:01 +0530 Subject: [PATCH 214/278] Added Reverse Integer(Leetcode) --- Python/reverseInteger.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Python/reverseInteger.py diff --git a/Python/reverseInteger.py b/Python/reverseInteger.py new file mode 100644 index 0000000..9289ede --- /dev/null +++ b/Python/reverseInteger.py @@ -0,0 +1,21 @@ +class Solution: + def reverse(self, x: int) -> int: + + f=0 + if(x<0): + f=1 + x=abs(x) + rev=0 + while(x!=0): + d=x%10 + x//=10 + rev=rev*10+d + + if -abs(rev)<= -2147483648 and rev >= 2147483647: + return 0 + + if(f==1): + # print(-abs(rev)) + return -abs(rev) + + return rev \ No newline at end of file From 8de1023d2a609346de2eac9d26a6254d67c2c96b Mon Sep 17 00:00:00 2001 From: ashish-nhk <89041437+ashish-nhk@users.noreply.github.com> Date: Sun, 2 Oct 2022 18:25:48 +0530 Subject: [PATCH 215/278] Permutations --- CPP/permutations.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 CPP/permutations.cpp diff --git a/CPP/permutations.cpp b/CPP/permutations.cpp new file mode 100644 index 0000000..b427cb5 --- /dev/null +++ b/CPP/permutations.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + void rec(int pos, vector &nums, vector> &ans){ + if(pos == nums.size()){ + ans.push_back(nums); + } + else{ + for(int i=pos; i> permute(vector& nums) { + vector>ans; + rec(0,nums,ans); + return ans; + } +}; \ No newline at end of file From dca36c6673ee9af8da866bd2c211e209c42060d9 Mon Sep 17 00:00:00 2001 From: ashish-nhk <89041437+ashish-nhk@users.noreply.github.com> Date: Sun, 2 Oct 2022 18:31:45 +0530 Subject: [PATCH 216/278] permutations.cpp --- CPP/permutations.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/CPP/permutations.cpp b/CPP/permutations.cpp index b427cb5..8ab10c9 100644 --- a/CPP/permutations.cpp +++ b/CPP/permutations.cpp @@ -4,12 +4,12 @@ class Solution { if(pos == nums.size()){ ans.push_back(nums); } - else{ - for(int i=pos; i> permute(vector& nums) { @@ -17,4 +17,4 @@ class Solution { rec(0,nums,ans); return ans; } -}; \ No newline at end of file +}; From 693a84e4040c19cb7f6d5c9b227f14e44e5ee093 Mon Sep 17 00:00:00 2001 From: Tharuka Wijekoon <79237086+tharuka01@users.noreply.github.com> Date: Sun, 2 Oct 2022 18:34:49 +0530 Subject: [PATCH 217/278] hacktoberfest-2022 please add my file to your repository with label as hacktoberfest --- Python/ytviddownloader.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/ytviddownloader.py diff --git a/Python/ytviddownloader.py b/Python/ytviddownloader.py new file mode 100644 index 0000000..beab1a4 --- /dev/null +++ b/Python/ytviddownloader.py @@ -0,0 +1,30 @@ +from tkinter import * +from pytube import YouTube + +window = Tk() +window.geometry("600x700") +window.config(bg="red") +window.title("Youtube Video Downloader by Tharuka") + +youtube_logo = PhotoImage(file="yt.png") +window.iconphoto(False, youtube_logo) + +Label(window, text="Video Downloader", font=("Arial 30 bold"), bg="lightgreen").pack(padx=5, pady=50) + +video_link = StringVar() + +Label(window, text="Enter the Link : ", font=("Arial",25,"bold")).place(x=170, y=150) + +Entry_link = Entry(window, width=50, font=35 , textvariable=video_link, bd=4).place(x=60, y=200) + +def video_download(): + video_url = YouTube(str(video_link.get())) + videos = video_url.streams.first() + videos.download() + + Label(window, text="Download Completed !!!", font=("Arial",35,"bold"),bg="lightpink",fg="Black").place(x=60, y=350) + Label(window, text="Check out Download Folder", font=("Arial", 30, "bold"), bg="yellow").place(x=60, y=400) + +Button(window, text=".DOWNLOAD.", font=("Arial", 25, "bold"), bg="lightblue", command=video_download).place(x=180, y=300) + +window.mainloop() From 664f8715b41bcb6ee5e1b478a136c5d08b9b768c Mon Sep 17 00:00:00 2001 From: Sona Elizebeth Shaji <56604740+Sonaelizebeth@users.noreply.github.com> Date: Sun, 2 Oct 2022 19:03:34 +0530 Subject: [PATCH 218/278] Bubblesort --- Java/bubbley.java | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Java/bubbley.java diff --git a/Java/bubbley.java b/Java/bubbley.java new file mode 100644 index 0000000..436662e --- /dev/null +++ b/Java/bubbley.java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} From 103fa668756d1fec789e3862029cd83020e811bb Mon Sep 17 00:00:00 2001 From: Sarthak Wakchaure <78649337+Sarthak88-tech@users.noreply.github.com> Date: Sun, 2 Oct 2022 19:13:44 +0530 Subject: [PATCH 219/278] Add files via upload --- CPP/Circular Queue.cpp | 287 ++++++++++++++++--------- CPP/Queue using Array.cpp | 158 ++++++++++++++ CPP/SLL(practice with info).cpp | 365 ++++++++++++++++++++++++++++++++ CPP/Selection sort.cpp | 75 +++++++ CPP/bal_paranthesis.cpp | 45 ++++ CPP/inclusion and exclusion.cpp | 245 +++++++++++++++++++++ 6 files changed, 1078 insertions(+), 97 deletions(-) create mode 100644 CPP/Queue using Array.cpp create mode 100644 CPP/SLL(practice with info).cpp create mode 100644 CPP/Selection sort.cpp create mode 100644 CPP/bal_paranthesis.cpp create mode 100644 CPP/inclusion and exclusion.cpp diff --git a/CPP/Circular Queue.cpp b/CPP/Circular Queue.cpp index 711333d..3093a6d 100644 --- a/CPP/Circular Queue.cpp +++ b/CPP/Circular Queue.cpp @@ -1,97 +1,190 @@ -#include -using namespace std; - -int cqueue[10]; -int front = -1, rear = -1, n=5; - -void insertCQ(int val) { - if ((front == 0 && rear == n-1) || (front == rear+1)) { - cout<<"Queue is full\n"; - return; - } - if (front == -1) { - front = 0; - rear = 0; - } else { - if (rear == n - 1) - rear = 0; - else - rear = rear + 1; - } - cqueue[rear] = val ; -} -void deleteCQ() { - if (front == -1) { - cout<<"Queue Underflow\n"; - return ; - } - cout<<"Element deleted from queue is : "<>ch; - switch(ch) { - case 1: - cout<<"Enter the value"<>val; - insertCQ(val); - break; - - case 2: - deleteCQ(); - break; - - case 3: - displayCQ(); - break; - - case 4: - cout<<"Exit\n"; - break; - default: cout<<"Enter valid option!\n"; - } - } while(ch != 4); - return 0; -} \ No newline at end of file +#include +#define MAX 5 +using namespace std; + + +class Queue +{ + public: + int que[MAX]; + int front,rear; + int data; + + Queue() + { + front=-1; + rear=-1; + } + + bool isEmpty() + { + if(front==-1) + { + return true; + } + + else + { + return false; + } + } + + bool isFull() + { + if( (front==0 && rear==MAX-1) || (front==rear+1) ) + { + return true; + } + + else + { + return false; + } + } + + + void enqueue(); + void dequeue(); + void display(); + +}; + +void Queue :: enqueue() +{ + if(isFull()) + { + cout<<"\nQueue is Full\n"; + } + + else + { + cout<<"\nEnter element in queue: "; + cin>>data; + + if(front==-1) + { + front=rear=0; + } + + else + { + rear=(rear+1)%MAX; + } + + que[rear]=data; + } + +} + + +void Queue :: dequeue() +{ + if(isEmpty()) + { + cout<<"\nCan't perform delete operation\n"; + } + + else + { + int item=que[front]; + + if(front==rear) + { + front=rear=-1; + } + + else + { + front=(front+1)% MAX; + } + } +} + +void Queue :: display() +{ + int f=front; + int r=rear; + + + if(isEmpty()) + { + cout<<"\nQueue is empty"; + } + + if(f <= r) + { + while (f <= r) + { + cout<<"| "<>ch; + + switch(ch) + { + + case 1: + q.enqueue(); + q.display(); + + break; + + case 2: + q.dequeue(); + q.display(); + + break; + + case 3: + q.display(); + break; + + default: + cout<<"\nSorry!!! you have entered wrong choice"; + } + + cout<<"\n\nDo you want to continue (y/n): "; + cin>>start; + + } + + cout<<"\nThank you!!!"; + + return 0; +} diff --git a/CPP/Queue using Array.cpp b/CPP/Queue using Array.cpp new file mode 100644 index 0000000..8d7ba03 --- /dev/null +++ b/CPP/Queue using Array.cpp @@ -0,0 +1,158 @@ +#include +#define MAX 10 +using namespace std; + + +class Queue +{ + public: + int que[MAX]; + int front,rear; + int data; + + Queue() + { + front=-1; + rear=-1; + } + + bool isEmpty() + { + if(front==-1) + { + return true; + } + + else + { + return false; + } + } + + bool isFull() + { + if(rear==MAX-1) + { + return true; + } + + else + { + return false; + } + } + + + void enqueue(); + void dequeue(); + void display(); + +}; + +void Queue :: enqueue() +{ + if(isFull()) + { + cout<<"\nQueue is Full"; + } + + else + { + cout<<"\nEnter element in queue: "; + cin>>data; + + rear++; + que[rear]=data; + + if(front==-1) + { + front=0; + } + } + +} + + +void Queue :: dequeue() +{ + if(isEmpty()) + { + cout<<"\nCan't perform delete operation\n"; + } + + else + { + int item=que[front]; + + if(front==rear) + { + front=rear=-1; + } + + else + { + front++; + } + } +} + +void Queue :: display() +{ + + if(isEmpty()) + { + cout<<"\nQueue is empty"; + } + + else + { + for(int i=front;i<=rear;i++) + { + cout<<"| "<>ch; + + switch(ch) + { + + case 1: + q.enqueue(); + q.display(); + + break; + + case 2: + q.dequeue(); + q.display(); + + break; + + default: + cout<<"\nSorry!!! you have entered wrong choice"; + } + + cout<<"\n\nDo you want to continue (y/n): "; + cin>>start; + + } + + cout<<"\nThank you!!!"; + + return 0; +} diff --git a/CPP/SLL(practice with info).cpp b/CPP/SLL(practice with info).cpp new file mode 100644 index 0000000..9d88cce --- /dev/null +++ b/CPP/SLL(practice with info).cpp @@ -0,0 +1,365 @@ + +#include +using namespace std; + +class node +{ + public: + int data; + node* next; +}; + +class list +{ + public: + node* head; + int len; + + list() //Default constructor + { + head==NULL; + len=0; + + } + +void create(); +void display(); +void insert(int pos,int data); +void search(int info); +void del(int info); +void update(int info,int new_data); + +}; + +void list :: create() +{ + node *temp,*ptr; + int add; + + do + { + temp=new node; + cout<<"Enter your data: "; + cin>>temp->data; + temp->next=NULL; + len++; + + if(head==NULL) + { + head=temp; + } + + else + { + ptr=head; + while(ptr->next!=NULL) + { + ptr=ptr->next; + + } + ptr->next=temp; + } + + cout<<"If you want to add more nodes enter 1: "; + cin>>add; + + } while(add==1); + +} + + +void list :: display() +{ + node *ptr; + ptr=head; + + + while(ptr!=NULL) + { + + cout<data<<" ->"; + ptr=ptr->next; + } + cout<<"NULL"; + +} + + +void list :: insert(int pos,int data) +{ + + if(pos==1) + { + + node *temp,*ptr; + temp=new node; + temp->data=data; + + temp->next=head; + head=temp; + + + } + + else if(pos>len) + { + + node *temp,*ptr; + temp=new node; + temp->data=data; + + + ptr=head; + while(ptr->next!=NULL) + { + ptr=ptr->next; + + } + ptr->next=temp; + + } + + else + { + node *temp,*ptr; + temp=new node; + temp->data=data; + + + ptr=head; + + for(int i=1;i<(pos-1);i++) + { + ptr=ptr->next; + + } + + temp->next=ptr->next; + ptr->next=temp; + + + + } + +} + +void list :: search(int info) +{ + node *ptr; + ptr=head; + int flag=0,count=1; + + while(ptr!=NULL) + { + if(ptr->data==info) + { + flag=1; + break; + } + + else + { + ptr=ptr->next; + } + count++; + + } + + if(flag==1) + { + cout<<"Your data has been found at pos: "<data==info) + { + if(curr==head) + { + head=head->next; + delete curr; + flag=1; + cout<<"\nData has been deleted successfully!!!"; + len--; + break; + } + + if(curr->next==NULL) + { + prev->next=NULL; + delete curr; + flag=1; + cout<<"\nData has been deleted successfully!!!"; + len--; + break; + } + + else + { + prev->next=curr->next; + delete curr; + flag=1; + cout<<"\nData has been deleted successfully!!!"; + len--; + break; + } + break; + } + + else + { + prev=curr; + curr=curr->next; + } + + + + + } + + if(flag==0) + { + cout<<"\nSorry!!! data not found"; + } +} + + + + +void list :: update(int info,int new_data) //using info +{ + node *ptr; + ptr=head; + int flag=0; + + while(ptr!=NULL) + { + if(ptr->data==info) + { + if(ptr==head) + { + ptr->data=new_data; + flag=1; + break; + } + + + if(ptr->next==NULL) + { + ptr->data=new_data; + flag=1; + break; + } + + else + { + ptr->data=new_data; + flag=1; + break; + } + } + + else + { + ptr=ptr->next; + } + + } + + + if(flag==0) + { + cout<<"\nSorry!!! data not found"; + } + + +} + + + +int main() +{ + int pos,ch,start=1,data,info,new_data; + node n; + list l; + l.create(); + cout<<"\n"; + l.display(); + + cout<<"\n\n1)Insert\n2)Search\n3)Delete\n4)Update\n5)Exit"; + + while(start==1) + { + cout<<"\n\nEnter your choice: "; + cin>>ch; + + switch(ch) + { + + case 1: + cout<<"\nEnter position where you want to insert data: "; + cin>>pos; + cout<<"Enter data: "; + cin>>data; + l.insert(pos,data); + cout<<"\nData inserted successfully!!!\n"; + l.display(); + break; + + + case 2: + cout<<"Enter data to search: "; + cin>>info; + l.search(info); + break; + + case 3: + cout<<"Enter data that you want to delete: "; + cin>>info; + + l.del(info); + cout<<"\n"; + l.display(); + break; + + case 4: + cout<<"Enter data that you want to update: "; + cin>>info; + cout<<"Enter new data: "; + cin>>new_data; + l.update(info,new_data); + cout<<"\n"; + l.display(); + break; + + case 5: + cout<<"\nThankyou!!!"; + break; + + default: + cout<<"\nSorry!!! you have entered wrong choice"; + } + + cout<<"\n\nPress 1 to contionue or press any key to exit: "; + cin>>start; + + } + + cout<<"\nThankyou!!!"; + + return 0; +} diff --git a/CPP/Selection sort.cpp b/CPP/Selection sort.cpp new file mode 100644 index 0000000..4fc7282 --- /dev/null +++ b/CPP/Selection sort.cpp @@ -0,0 +1,75 @@ +#include +#define size 4 +using namespace std; + +class select +{ + public: + int arr[size]; + + void get_data(); + void display(); + void selection_sort(); + +}; + +void select::get_data() +{ + for(int i=0;i>arr[i]; + + } +} + +void select::display() +{ + cout<<"\nSorted data \n\n"; + for(int i=0;i +#include +using namespace std; + +int main() +{ + string s="{()}]["; + + stack st; + int flag=0; + + for(int i=0;i +#include +using namespace std; + +class sport +{ + public: + int hockey[20],cricket[20],football[20]; + int n1,n2,n3,count,count1,count2,count3,intersection; + void get_set1_info(); + void get_set2_info(); + void get_set3_info(); + + void display(int arr[]); + void intersection_2_teams(); + void intersection_3_teams(); + void union_2_teams(); + void union_3_teams(); + +}; + +void sport::get_set1_info() +{ + cout<<"\nEnter total no of players in Hockey team : "; + cin>>n1; + cout<<"\nEnter jersey no : \n"; + for(int i=0;i>hockey[i]; + cout<<"\t"; + + } +} + +void sport::get_set2_info() +{ + cout<<"\nEnter total no of players in Cricket team : "; + cin>>n2; + cout<<"\nEnter jersey no :\n "; + for(int i=0;i>cricket[i]; + cout<<"\t"; + + } +} + +void sport::get_set3_info() +{ + cout<<"\nEnter total no of players in Football team : "; + cin>>n3; + cout<<"\nEnter jersey no : \n"; + for(int i=0;i>football[i]; + cout<<"\t"; + + } +} + + +void sport::display(int arr[]) +{ + + for(int i=0;in2) + { + for(int i=0;in2) + { + for(int i=0;in3) + { + for(int i=0;in3) + { + for(int i=0;i Date: Sun, 2 Oct 2022 19:26:22 +0530 Subject: [PATCH 220/278] Create reverse.cpp --- reverse.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 reverse.cpp diff --git a/reverse.cpp b/reverse.cpp new file mode 100644 index 0000000..483fe2d --- /dev/null +++ b/reverse.cpp @@ -0,0 +1,30 @@ +#include +using namespace std; + +int main () +{ + int arr[50], num, temp, i, j; + cout<<"Enter the number of terms: "; + cin >> num; + + cout<<"Enter all the terms: "; + for (i = 0; i < num; i++) + { + cin >> arr[i]; + } + + + for ( i = 0, j = num - 1; i < num/2; i++, j--) + { + temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + + for ( i = 0; i < num; i++) + { + cout << arr[i] << " "; + } + return 0; + +} From 5bbc4fd61c7d198fbbaa590307e638fa7dd1aaa0 Mon Sep 17 00:00:00 2001 From: muke267 <92973548+muke267@users.noreply.github.com> Date: Sun, 2 Oct 2022 19:30:28 +0530 Subject: [PATCH 221/278] Maximum Width of Binary Tree --- Maximum width of binary tree.cpp | 42 ++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Maximum width of binary tree.cpp diff --git a/Maximum width of binary tree.cpp b/Maximum width of binary tree.cpp new file mode 100644 index 0000000..f6a7763 --- /dev/null +++ b/Maximum width of binary tree.cpp @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int widthOfBinaryTree(TreeNode* root) { + if(!root) + return 0; + int ans = 0; + queue> q; + q.push({root,0}); + while(!q.empty()){ + int size=q.size(); + int mini=q.front().second; + int first,last; + for(int itr = 0; itrleft) + q.push({temp->left,cur_id*2+1}); + if(temp->right) + q.push({temp->right,cur_id*2+2}); + } + ans = max(ans, (last-first+1)); + } + return ans; + } +}; \ No newline at end of file From c554df3455e974019e530e644c63e998cdd77b9f Mon Sep 17 00:00:00 2001 From: lifeashaze <34096693+lifeashaze@users.noreply.github.com> Date: Sun, 2 Oct 2022 21:08:04 +0530 Subject: [PATCH 222/278] Created QuickSort.c --- C/QuickSort.c | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 C/QuickSort.c diff --git a/C/QuickSort.c b/C/QuickSort.c new file mode 100644 index 0000000..9965fd0 --- /dev/null +++ b/C/QuickSort.c @@ -0,0 +1,50 @@ +#include +void swap(int *a, int *b) +{ + int t = *a; + *a = *b; + *b = t; +} +int partition(int array[], int low, int high) +{ + int pivot = array[high]; + int i = (low - 1); + for (int j = low; j < high; j++) + { + if (array[j] <= pivot) + { + i++; + swap(&array[i], &array[j]); + } + } + + swap(&array[i + 1], &array[high]); + return (i + 1); +} +void quicksort(int array[], int low, int high) +{ + if (low < high) + { + int pi = partition(array, low, high); + quicksort(array, low, pi - 1); + quicksort(array, pi + 1, high); + } +} +void printArray(int array[], int size) +{ + for (int i = 0; i < size; ++i) + { + printf("%d", array[i]); + } + printf("\n"); +} +int main() +{ + int data[] = {8, 7, 2, 1, 0, 9, 6}; + int n = sizeof(data) / sizeof(data[0]); + printf("unsorted Array \n"); + printArray(data, n); + quicksort(data, 0, n - 1); + printf("sorted array in ascending order :\n"); + printArray(data, n); +} From e00ff34de467ada2bd61137002a6d0c395796ade Mon Sep 17 00:00:00 2001 From: PullambhatlaPoojitha <92459788+PullambhatlaPoojitha@users.noreply.github.com> Date: Sun, 2 Oct 2022 21:13:34 +0530 Subject: [PATCH 223/278] Brick Breaker game --- Java Games/Gameplay.java | 130 +++++++++++++++++++++++++++++++++++ Java Games/Main.java | 14 ++++ Java Games/MapGenerator.java | 33 +++++++++ 3 files changed, 177 insertions(+) create mode 100644 Java Games/Gameplay.java create mode 100644 Java Games/Main.java create mode 100644 Java Games/MapGenerator.java diff --git a/Java Games/Gameplay.java b/Java Games/Gameplay.java new file mode 100644 index 0000000..4379d97 --- /dev/null +++ b/Java Games/Gameplay.java @@ -0,0 +1,130 @@ +import javax.swing.*; +import javax.swing.Timer; + +import java.awt.*; +import java.awt.event.*; +import java.sql.Time; +import java.util.*; + +public class Gameplay extends JPanel implements KeyListener, ActionListener { + private boolean play = false; + private int score = 0; + private int totalBricks = 21; + private Timer timer; + private int delay = 4; + private int playerX = 310; + private int ballposX = 120; + private int ballposY = 350; + private int ballXdir = -1; + private int ballYdir = -2; + private MapGenerator map; + + public Gameplay() { + map=new MapGenerator(3, 7); + addKeyListener(this); + setFocusable(true); + setFocusTraversalKeysEnabled(false); + timer = new Timer(delay, this); + timer.start(); + + } + + public void paint(Graphics g) { + // background + g.setColor(Color.black); + g.fillRect(1, 1, 692, 592); + // borders + g.setColor(Color.yellow); + g.fillRect(0, 0, 3, 592); + g.fillRect(0, 0, 692, 3); + g.fillRect(691, 0, 3, 592); + // map + map.draw((Graphics2D) g); + // the paddle + g.setColor(Color.green); + g.fillRect(playerX, 500, 100, 8); + // the ball + g.setColor(Color.red); + g.fillOval(ballposX, ballposY, 20, 20); + g.dispose(); + + } + + @Override + public void actionPerformed(ActionEvent e) { + timer.start(); + if (play) { + if (new Rectangle(ballposX, ballposY, 20, 20).intersects(playerX, 500, 100, 8)) { + ballYdir = -ballYdir; + } + for(int i=0;i0){ + int brickX=j*map.brickwidth+80; + int brickY=i*map.brickheight+50; + int brickwidth=map.brickwidth; + int brickheight=map.brickheight; + Rectangle rect=new Rectangle(brickX,brickY,brickwidth,brickheight); + Rectangle ballRect=new Rectangle(ballposX,ballposY,20,20); + Rectangle brickRect=rect; + if(ballRect.intersects(brickRect)){ + // map.setBrick(0,i,j); + totalBricks--; + score+=5; + } + } + } + } + ballposX += ballXdir; + ballposY += ballYdir; + if (ballposX < 0) { + ballXdir = -ballXdir; + } + if (ballposY < 0) { + ballYdir = -ballYdir; + } + if (ballposX > 670) { + ballXdir = -ballXdir; + } + } + repaint(); + } + + @Override + public void keyTyped(KeyEvent e) { + } + + @Override + public void keyPressed(KeyEvent e) { + } + + @Override + public void keyReleased(KeyEvent e) { + if (e.getKeyCode() == e.VK_RIGHT) { + if (playerX >= 580) { + playerX = 580; + } else { + moveRight(); + } + } + if (e.getKeyCode() == e.VK_LEFT) { + if (playerX < 10) { + playerX = 10; + } else { + moveLeft(); + } + } + } + + public void moveRight() { + play = true; + playerX += 20; + + } + + public void moveLeft() { + play = true; + playerX -= 20; + + } +} diff --git a/Java Games/Main.java b/Java Games/Main.java new file mode 100644 index 0000000..93899b1 --- /dev/null +++ b/Java Games/Main.java @@ -0,0 +1,14 @@ +import javax.swing.JFrame; + +public class Main{ + public static void main(String[] args){ + JFrame obj=new JFrame(); + Gameplay gameplay=new Gameplay(); + obj.setBounds(10,10,700,600); + obj.setTitle("Breakout ball"); + obj.setResizable(false); + obj.setVisible(true); + obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + obj.add(gameplay); + } +} \ No newline at end of file diff --git a/Java Games/MapGenerator.java b/Java Games/MapGenerator.java new file mode 100644 index 0000000..cd4e7fa --- /dev/null +++ b/Java Games/MapGenerator.java @@ -0,0 +1,33 @@ +import java.awt.*; + +public class MapGenerator { + public int map[][]; + public int brickwidth; + public int brickheight; + + public MapGenerator(int row, int col) { + map = new int[row][col]; + for (int i = 0; i < map.length; i++) { + for (int j = 0; j < map[0].length; j++) { + map[i][j] = 1; + } + } + brickwidth = 540 / col; + brickheight = 150 / row; + + } + + public void draw(Graphics2D g) { + for (int i = 0; i < map.length; i++) { + for (int j = 0; j < map[0].length; j++) { + if(map[i][j]>0){ + g.setColor(Color.white); + g.fillRect(j*brickwidth+80,i*brickheight+50,brickwidth,brickheight); + g.setStroke(new BasicStroke(3)); + g.setColor(Color.BLACK); + g.drawRect(j*brickwidth+80,i*brickheight+50,brickwidth,brickheight); + } + } + } + } +} From 37741698adbd84fbb7ce876d3d4dc58015eb5030 Mon Sep 17 00:00:00 2001 From: Seema Patel Date: Sun, 2 Oct 2022 21:16:21 +0530 Subject: [PATCH 224/278] Linked List problem --- CPP/LinkedList.cpp | 70 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 CPP/LinkedList.cpp diff --git a/CPP/LinkedList.cpp b/CPP/LinkedList.cpp new file mode 100644 index 0000000..69a5ffb --- /dev/null +++ b/CPP/LinkedList.cpp @@ -0,0 +1,70 @@ +//Program to detect loop in a linked list using fast and slow pointers + +#include +using namespace std; + +/* Link list node */ +struct Node { + int data; + struct Node* next; +}; + +void push(struct Node** head_ref, int new_data) +{ + /* allocate node */ + struct Node* new_node = new Node; + + /* put in the data */ + new_node->data = new_data; + + /* link the old list off the new node */ + new_node->next = (*head_ref); + + /* move the head to point to the new node */ + (*head_ref) = new_node; +} + +// Returns true if there is a loop in linked list +// else returns false. +bool detectLoop(struct Node* h) +{ + unordered_set s; + while (h != NULL) { + // If this node is already present + // in hashmap it means there is a cycle + // (Because you will be encountering the + // node for the second time). + if (s.find(h) != s.end()) + return true; + + // If we are seeing the node for + // the first time, insert it in hash + s.insert(h); + + h = h->next; + } + + return false; +} + +/* Driver program to test above function*/ +int main() +{ + /* Start with the empty list */ + struct Node* head = NULL; + + push(&head, 20); + push(&head, 4); + push(&head, 15); + push(&head, 10); + + /* Create a loop for testing */ + head->next->next->next->next = head; + + if (detectLoop(head)) + cout << "Loop found"; + else + cout << "No Loop"; + + return 0; +} From c5d1081dbc951c0b39affe7ee102988162535cbf Mon Sep 17 00:00:00 2001 From: Himanshi Sharma <78836404+Himanshi2511@users.noreply.github.com> Date: Sun, 2 Oct 2022 21:21:54 +0530 Subject: [PATCH 225/278] Create level_order_traversal.cpp --- CPP/level_order_traversal.cpp | 92 +++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 CPP/level_order_traversal.cpp diff --git a/CPP/level_order_traversal.cpp b/CPP/level_order_traversal.cpp new file mode 100644 index 0000000..dc5da8d --- /dev/null +++ b/CPP/level_order_traversal.cpp @@ -0,0 +1,92 @@ +// Recursive CPP program for level +// order traversal of Binary Tree +#include +using namespace std; + +/* A binary tree node has data, +pointer to left child +and a pointer to right child */ +class node { +public: + int data; + node *left, *right; +}; + +/* Function prototypes */ +void printCurrentLevel(node* root, int level); +int height(node* node); +node* newNode(int data); + +/* Function to print level +order traversal a tree*/ +void printLevelOrder(node* root) +{ + int h = height(root); + int i; + for (i = 1; i <= h; i++) + printCurrentLevel(root, i); +} + +/* Print nodes at a current level */ +void printCurrentLevel(node* root, int level) +{ + if (root == NULL) + return; + if (level == 1) + cout << root->data << " "; + else if (level > 1) { + printCurrentLevel(root->left, level - 1); + printCurrentLevel(root->right, level - 1); + } +} + +/* Compute the "height" of a tree -- the number of + nodes along the longest path from the root node + down to the farthest leaf node.*/ +int height(node* node) +{ + if (node == NULL) + return 0; + else { + /* compute the height of each subtree */ + int lheight = height(node->left); + int rheight = height(node->right); + + /* use the larger one */ + if (lheight > rheight) { + return (lheight + 1); + } + else { + return (rheight + 1); + } + } +} + +/* Helper function that allocates +a new node with the given data and +NULL left and right pointers. */ +node* newNode(int data) +{ + node* Node = new node(); + Node->data = data; + Node->left = NULL; + Node->right = NULL; + + return (Node); +} + +/* Driver code*/ +int main() +{ + node* root = newNode(1); + root->left = newNode(2); + root->right = newNode(3); + root->left->left = newNode(4); + root->left->right = newNode(5); + + cout << "Level Order traversal of binary tree is \n"; + printLevelOrder(root); + + return 0; +} + From a37d3dfae22d19e169c7960fad6fd8cb4a6b42e5 Mon Sep 17 00:00:00 2001 From: Chiroyce <97374054+Chiroyce1@users.noreply.github.com> Date: Sun, 2 Oct 2022 21:22:47 +0530 Subject: [PATCH 226/278] Add bubble sort for Python --- Python/bubble_sort.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Python/bubble_sort.py diff --git a/Python/bubble_sort.py b/Python/bubble_sort.py new file mode 100644 index 0000000..dffe605 --- /dev/null +++ b/Python/bubble_sort.py @@ -0,0 +1,12 @@ +def bubble_sort(array): + for i in range(len(array) - 1): + for i in range(len(array)-1): + if array[i+1] < array[i]: + greater = array[i+1] + array[i+1] = array[i] + array[i] = greater + + return array + +if __name__ == '__main__': + print(bubble_sort([5, 10, 15, 3])) From c7ad64fff117941bc17634d97e044a68ce63e9b2 Mon Sep 17 00:00:00 2001 From: aashishjakhar <113769749+aashishjakhar@users.noreply.github.com> Date: Sun, 2 Oct 2022 21:26:11 +0530 Subject: [PATCH 227/278] Add files via upload --- leap year.java | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 leap year.java diff --git a/leap year.java b/leap year.java new file mode 100644 index 0000000..ecc14c0 --- /dev/null +++ b/leap year.java @@ -0,0 +1,36 @@ +public class Main { + + public static void main(String[] args) { + + // year to be checked + int year = 1900; + boolean leap = false; + + // if the year is divided by 4 + if (year % 4 == 0) { + + // if the year is century + if (year % 100 == 0) { + + // if year is divided by 400 + // then it is a leap year + if (year % 400 == 0) + leap = true; + else + leap = false; + } + + // if the year is not century + else + leap = true; + } + + else + leap = false; + + if (leap) + System.out.println(year + " is a leap year."); + else + System.out.println(year + " is not a leap year."); + } +} \ No newline at end of file From 558b8f74a4f35c55ac492bcb29720c114314b5ed Mon Sep 17 00:00:00 2001 From: Vaghela Ajitkumar <91899491+ajitkumar1264@users.noreply.github.com> Date: Sun, 2 Oct 2022 21:27:18 +0530 Subject: [PATCH 228/278] Revert "Create mergesort.js" --- Javascript/mergesort.js | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 Javascript/mergesort.js diff --git a/Javascript/mergesort.js b/Javascript/mergesort.js deleted file mode 100644 index 246b068..0000000 --- a/Javascript/mergesort.js +++ /dev/null @@ -1,24 +0,0 @@ -function merge_sort(left_part,right_part) -{ - var i = 0; - var j = 0; - var results = []; - - while (i < left_part.length || j < right_part.length) { - if (i === left_part.length) { - // j is the only index left_part - results.push(right_part[j]); - j++; - } - else if (j === right_part.length || left_part[i] <= right_part[j]) { - results.push(left_part[i]); - i++; - } else { - results.push(right_part[j]); - j++; - } - } - return results; -} - -console.log(merge_sort([1,3,4], [3,7,9])); From 4c23e02793b87a43962e2c7e3f8fccb9ec7668ab Mon Sep 17 00:00:00 2001 From: subhash-iiitm <7554597+subhash-iiitm@users.noreply.github.com> Date: Sun, 2 Oct 2022 21:31:23 +0530 Subject: [PATCH 229/278] Create is_palindrome.py --- Python/is_palindrome.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Python/is_palindrome.py diff --git a/Python/is_palindrome.py b/Python/is_palindrome.py new file mode 100644 index 0000000..4776a5f --- /dev/null +++ b/Python/is_palindrome.py @@ -0,0 +1,28 @@ +def is_palindrome(s: str) -> bool: + """ + Determine whether the string is palindrome + :param s: + :return: Boolean + >>> is_palindrome("a man a plan a canal panama".replace(" ", "")) + True + >>> is_palindrome("Hello") + False + >>> is_palindrome("Able was I ere I saw Elba") + True + >>> is_palindrome("racecar") + True + >>> is_palindrome("Mr. Owl ate my metal worm?") + True + """ + # Since Punctuation, capitalization, and spaces are usually ignored while checking + # Palindrome, we first remove them from our string. + s = "".join([character for character in s.lower() if character.isalnum()]) + return s == s[::-1] + + +if __name__ == "__main__": + s = input("Enter string to determine whether its palindrome or not: ").strip() + if is_palindrome(s): + print("Given string is palindrome") + else: + print("Given string is not palindrome") From 5a47250ddce2a98910dde565860ab6c974dfea97 Mon Sep 17 00:00:00 2001 From: Muhammad Hammad Sani <58339378+mhammadsaani@users.noreply.github.com> Date: Sun, 2 Oct 2022 21:04:57 +0500 Subject: [PATCH 230/278] dfs code in python added --- Python/dfs.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Python/dfs.py diff --git a/Python/dfs.py b/Python/dfs.py new file mode 100644 index 0000000..fb0e43a --- /dev/null +++ b/Python/dfs.py @@ -0,0 +1,23 @@ +# DFS algorithm in Python + + +# DFS algorithm +def dfs(graph, start, visited=None): + if visited is None: + visited = set() + visited.add(start) + + print(start) + + for next in graph[start] - visited: + dfs(graph, next, visited) + return visited + + +graph = {'0': set(['1', '2']), + '1': set(['0', '3', '4']), + '2': set(['0']), + '3': set(['1']), + '4': set(['2', '3'])} + +dfs(graph, '0') From 4f2dcab17a1c0fb236285a0424760d449b054521 Mon Sep 17 00:00:00 2001 From: Ankush Malhotra <114765498+AnkushMalhotragithub@users.noreply.github.com> Date: Sun, 2 Oct 2022 09:15:43 -0700 Subject: [PATCH 231/278] Add files via upload --- attendance.txt | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 attendance.txt diff --git a/attendance.txt b/attendance.txt new file mode 100644 index 0000000..e75ad09 --- /dev/null +++ b/attendance.txt @@ -0,0 +1,20 @@ + + +Login form Design + +
+ +Login Here +
+

Username

+ +

Password

+ + +Lost your password?
+Don't have an account?
+
+
+ + + \ No newline at end of file From a00da4fb30b2728f75148e65ab566e7d6adfd20a Mon Sep 17 00:00:00 2001 From: Sahil Rajesh Shriwardhankar <102847495+notsointresting@users.noreply.github.com> Date: Sun, 2 Oct 2022 21:53:41 +0530 Subject: [PATCH 232/278] Dice Roller Using Python --- Dice.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Dice.py diff --git a/Dice.py b/Dice.py new file mode 100644 index 0000000..eae21d9 --- /dev/null +++ b/Dice.py @@ -0,0 +1,13 @@ +import random + +#Dice Roller + +print("Initially number on Dice is: {0}".format(random.randint(1,6))) + +C = int(input("To Roll Dice Press any number or To Exit Press 0---> ")) + +while C !=0: + print("Number on Dice is: {0}".format(random.randint(1,6))) + + C = int(input("To Roll Dice Press 1 or To Exit Press 0---> ")) + From 7e68eba19a96c2a86827b4bb3ee8c439b2e81533 Mon Sep 17 00:00:00 2001 From: Sanket Anand Jaiswal <103429178+SanketJ29@users.noreply.github.com> Date: Sun, 2 Oct 2022 21:54:36 +0530 Subject: [PATCH 233/278] Create CycleSort.java --- Java/CycleSort.java | 52 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Java/CycleSort.java diff --git a/Java/CycleSort.java b/Java/CycleSort.java new file mode 100644 index 0000000..32b7e77 --- /dev/null +++ b/Java/CycleSort.java @@ -0,0 +1,52 @@ +// java program to check implement cycle sort +import java.util.*; +public class MissingNumber { + public static void main(String[] args) + { + int[] arr = { 3, 2, 4, 5, 1 }; + int n = arr.length; + System.out.println("Before sort :"); + System.out.println(Arrays.toString(arr)); + CycleSort(arr, n); + + } + + static void CycleSort(int[] arr, int n) + { + int i = 0; + while (i < n) { + // as array is of 1 based indexing so the + // correct position or index number of each + // element is element-1 i.e. 1 will be at 0th + // index similarly 2 correct index will 1 so + // on... + int correctpos = arr[i] - 1; + if (arr[i] < n && arr[i] != arr[correctpos]) { + // if array element should be lesser than + // size and array element should not be at + // its correct position then only swap with + // its correct position or index value + swap(arr, i, correctpos); + } + else { + // if element is at its correct position + // just increment i and check for remaining + // array elements + i++; + } + } + System.out.println("After sort : "); + System.out.print(Arrays.toString(arr)); + + + } + + static void swap(int[] arr, int i, int correctpos) + { + // swap elements with their correct indexes + int temp = arr[i]; + arr[i] = arr[correctpos]; + arr[correctpos] = temp; + } +} +// this code is contributed by Sanket Jaiswal From 221e95c97125d5132d0215fbdff35540f92db60e Mon Sep 17 00:00:00 2001 From: Brijesh124 <114356566+Brijesh124@users.noreply.github.com> Date: Sun, 2 Oct 2022 22:04:09 +0530 Subject: [PATCH 234/278] product --- Product.java | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Product.java diff --git a/Product.java b/Product.java new file mode 100644 index 0000000..5b208b4 --- /dev/null +++ b/Product.java @@ -0,0 +1,39 @@ +import java.util.*; + +class Product +{ + public static void main(String arg[]) + { + Scanner sc = new Scanner(System.in); + + int [][] a = new int[3][3]; + System.out.println("enter the integers:"); + for(int i=0;i<3;i++) + { + for(int j=0;j<3;j++) + { + a[i][j] = sc.nextInt(); + } + } + + for(int i=0;i<3;i++) + { + for(int j=0;j<3;j++) + { + System.out.print(""+a[i][j]); + } + + System.out.print("\n"); + } + System.out.println("transpose is:"); + for(int j=0;j<3;j++) + { + for(int i=0;i<3;i++) + { + System.out.print(""+a[i][j]); + + } + System.out.print("\n"); + } + } +} \ No newline at end of file From 07f25f643f2e6b6927349aa2f119f41e2c26f362 Mon Sep 17 00:00:00 2001 From: alokya88 <114597324+alokya88@users.noreply.github.com> Date: Sun, 2 Oct 2022 22:05:39 +0530 Subject: [PATCH 235/278] Create factorial2.cpp --- factorial2.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 factorial2.cpp diff --git a/factorial2.cpp b/factorial2.cpp new file mode 100644 index 0000000..17a4da1 --- /dev/null +++ b/factorial2.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} From 819cef8ce5b3a46633be5035a6f42b125e710c40 Mon Sep 17 00:00:00 2001 From: ravinainn <91778452+ravinainn@users.noreply.github.com> Date: Sun, 2 Oct 2022 22:10:28 +0530 Subject: [PATCH 236/278] N Queen problem MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The n-queens puzzle is the problem of placing n queens on a (n×n) chessboard such that no two queens can attack each other. Given an integer n, find all distinct solutions to the n-queens puzzle. solution is done using backtracking algorithm Thank you --- CPP/n Queen problem.cpp | 98 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 CPP/n Queen problem.cpp diff --git a/CPP/n Queen problem.cpp b/CPP/n Queen problem.cpp new file mode 100644 index 0000000..05cf6b0 --- /dev/null +++ b/CPP/n Queen problem.cpp @@ -0,0 +1,98 @@ +//N Queen problem + +//The n-queens puzzle is the problem of placing n queens on a (n*n) chessboard such that no two queens can attack each other. +//Given an integer n, find all distinct solutions to the n-queens puzzle. + +#include +using namespace std; + +void addSolution(vector > &board , vector > &ans , int n){ + vector temp; + + for(int i = 0 ;i > &board , int n ){ + int x = row; + int y = col; + while(y>= 0){ + if(board[x][y] == 1){ + return false; + + } + y--; + } + x= row; + y = col; + while(y>=0 && x>=0){ + if(board[x][y]==1){ + return false; + } + x--; + y--; + } + x= row; + y= col; + while(y>=0 && x > &ans , vector > &board , int n){ + if(col == n){ + addSolution(board , ans , n); + return ; + } + + for(int row= 0 ; row< n; row++){ + + if(isSafe(row, col , board, n)){ + board[row][col] = 1; + nQueen(col+1 , ans, board, n); + board[row][col] = 0 ; + + } + } +} + +int main(){ + int n ; + cout<<"Enter the number of queens: "<>n; + + vector> board(n,vector(n,0)); + vector> ans; + + nQueen(0 , ans , board , n); + + + if(ans.size() == 0){ + cout<<"not possible"< Date: Sun, 2 Oct 2022 22:13:45 +0530 Subject: [PATCH 237/278] Create binary_search.c --- C/binary_search.c | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C/binary_search.c diff --git a/C/binary_search.c b/C/binary_search.c new file mode 100644 index 0000000..5aad9b4 --- /dev/null +++ b/C/binary_search.c @@ -0,0 +1,40 @@ +#include +#include +void main() +{ +int a[10],i,n,low,high,mid,item; +clrscr(); +printf("Enter the number of elements in the array); +scanf("%d",&n); +printf("Enter the elements in the array"); +for(i=0;ihigh) +{ +printf("The element is not found"); +} +getch(); +} From 6007a77314651ce6704c08328df073ce2f45deff Mon Sep 17 00:00:00 2001 From: Shubh Agrawal <49271775+shubhagrawal123456@users.noreply.github.com> Date: Sun, 2 Oct 2022 22:18:04 +0530 Subject: [PATCH 238/278] Graph_Is_Bipartite We will start with each node, color it 0 and find all the neighbor and color them 1. If the neighbor is already colored but not with the color we want, we will return false. Return true when we find a node that is already colored with the color we want to avoid infinite loop. --- CPP/Is_Graph_Bipartite | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 CPP/Is_Graph_Bipartite diff --git a/CPP/Is_Graph_Bipartite b/CPP/Is_Graph_Bipartite new file mode 100644 index 0000000..49abad9 --- /dev/null +++ b/CPP/Is_Graph_Bipartite @@ -0,0 +1,29 @@ +//785. Is Graph Bipartite? +//https://leetcode.com/problems/is-graph-bipartite/ + +class Solution { +public: + bool dfs(int node,vector>& adj,vector&color){ + if(color[node]==-1) color[node]=1; + for(auto it :adj[node]){ + + if(color[it]==-1){ + color[it]=1-color[node]; + if(dfs(it,adj,color)==false ) return false; + } + else if(color[node]==color[it]) return false; + } + return true; + } + bool isBipartite(vector>& graph) { + int n= graph.size(); + vectorcolor(n,-1); + for(int i=0;i Date: Sun, 2 Oct 2022 22:18:36 +0530 Subject: [PATCH 239/278] Stack using Linked List Implementation of Stack using Linked List Data Structure. --- C/StackUsingLinkedList.c | 110 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 C/StackUsingLinkedList.c diff --git a/C/StackUsingLinkedList.c b/C/StackUsingLinkedList.c new file mode 100644 index 0000000..4925205 --- /dev/null +++ b/C/StackUsingLinkedList.c @@ -0,0 +1,110 @@ +/* +Write a Program to implement Stack using Linked List. +Function to be included: +--> Push +--> Pop +--> Display +*/ + +//Including Libraries +#include +#include + +//Function Declaration +void push(); +void pop(); +void disp(); + +//Creating structure +struct node +{ + int data; + struct node *frnt; +}; +struct node *head; + +//Main Function +int main() +{ + int opt; + while(1) + { + printf("\nOperations of Stack using Linked List\n"); + printf("1_Push \n2_Pop \n3_Display \n4_Exit"); + printf("\nEnter the option: "); + scanf("%d", &opt); + switch(opt) + { + case 1: push(); break; + case 2: pop(); break; + case 3: disp(); break; + case 4: exit(0); + default: printf("\nInvalid Choice\n"); + } + } +} + +//Function Implementation +void push() +{ + int ele; + struct node *ptr; + ptr = (struct node *)malloc(sizeof(struct node)); + if(ptr == NULL) + { + printf("\nMemory Allocation Failed\n"); + } + else + { + printf("\nEnter Element to be inserted at end: "); + scanf("%d", &ele); + ptr->data = ele; + if(head == NULL) + { + ptr->frnt = NULL; + head = ptr; + } + else + { + ptr->data = ele; + ptr->frnt = head; + head = ptr; + } + } +} + +void pop() +{ + struct node *ptr; + if(head == NULL) + { + printf("\nNo Elements There\n"); + } + else + { + ptr = head; + head = ptr->frnt; + printf("\nElement removed is: %d\n", ptr->data); + free(ptr); + } +} + +void disp() +{ + struct node *ptr; + ptr = head; + if(ptr == NULL) + { + printf("\nNo Elements There\n"); + } + else + { + printf("\nThe Values are: "); + while (ptr!=NULL) + { + printf("%d ",ptr->data); + ptr = ptr -> frnt; + } + printf("\n"); + } +} \ No newline at end of file From 3edf0965f963fce53e70f54fd4138df5473f6245 Mon Sep 17 00:00:00 2001 From: Riya <96625454+riyasinghal123@users.noreply.github.com> Date: Sun, 2 Oct 2022 22:22:27 +0530 Subject: [PATCH 240/278] Create Sort Words in Dictionary.cpp --- Sort Words in Dictionary.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Sort Words in Dictionary.cpp diff --git a/Sort Words in Dictionary.cpp b/Sort Words in Dictionary.cpp new file mode 100644 index 0000000..e4263d3 --- /dev/null +++ b/Sort Words in Dictionary.cpp @@ -0,0 +1,32 @@ +#include +using namespace std; + +int main() +{ + string str[10], temp; + + cout << "Enter 10 words: " << endl; + for(int i = 0; i < 10; ++i) + { + getline(cin, str[i]); + } + + // Use Bubble Sort to arrange words + for (int i = 0; i < 9; ++i) { + for (int j = 0; j < 9 - i; ++j) { + if (str[j] > str[j + 1]) { + temp = str[j]; + str[j] = str[j + 1]; + str[j + 1] = temp; + } + } + } + + cout << "In lexicographical order: " << endl; + + for(int i = 0; i < 10; ++i) + { + cout << str[i] << endl; + } + return 0; +} From 4810e1070dc48a7d2a2a4bb7d1d2514b11b5c44f Mon Sep 17 00:00:00 2001 From: ashish-nhk <89041437+ashish-nhk@users.noreply.github.com> Date: Sun, 2 Oct 2022 22:27:06 +0530 Subject: [PATCH 241/278] Longest Palindromic Substring --- CPP/Longest Palindromic Substring.cpp | 47 +++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 CPP/Longest Palindromic Substring.cpp diff --git a/CPP/Longest Palindromic Substring.cpp b/CPP/Longest Palindromic Substring.cpp new file mode 100644 index 0000000..8d68461 --- /dev/null +++ b/CPP/Longest Palindromic Substring.cpp @@ -0,0 +1,47 @@ +#include +using namespace std; + +int dp[1001][1001]; +bool rec(int i,int j,string &s){ + if(i==j) + return dp[i][j]=1; + if(i>j) + return 1; + if(dp[i][j]!=-1) + return dp[i][j]; + if(s[i]==s[j]){ + return dp[i][j]= rec(i+1,j-1,s); + } + else + return dp[i][j]=0; + +} +string longestPalindrome(string s) { + int n=s.size(),i, j; + for(i=0;ians) + in=i,ij=j,ans=(j-i+1); + } + } + return s.substr(in,ij-in+1); +} + +int main() +{ + string str; + cin>>str; + cout< Date: Sun, 2 Oct 2022 22:30:28 +0530 Subject: [PATCH 242/278] N-ary Tree Level Order Traversal Please add my file to your repository with label hacktoberfest2022 --- CPP/N-ary Tree Level Order Traversal.cpp | 55 ++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 CPP/N-ary Tree Level Order Traversal.cpp diff --git a/CPP/N-ary Tree Level Order Traversal.cpp b/CPP/N-ary Tree Level Order Traversal.cpp new file mode 100644 index 0000000..b8749b9 --- /dev/null +++ b/CPP/N-ary Tree Level Order Traversal.cpp @@ -0,0 +1,55 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { +public: + vector> levelOrder(Node* root) { + vector>v; + queueq; + q.push(root); + if(root==nullptr) + return v; + while(1) + { + int sz=q.size(); + if(sz==0) + return v; + vectordata; + while(sz>0) + { + Node* temp=q.front(); + q.pop(); + data.push_back(temp->val); + for(Node* ch : temp->children) + q.push(ch); + // if(temp->children!= nullptr) + // q.push(temp->children); + // if(temp->right!=nullptr) + // q.push(temp->right); + sz--; + + } + v.push_back(data); + + } + return v; + + } +}; \ No newline at end of file From acb078b84d837d2c59fbc2703db9383071c1d9fe Mon Sep 17 00:00:00 2001 From: sheikh umaid <73013686+SheikhUmaid@users.noreply.github.com> Date: Sun, 2 Oct 2022 22:36:57 +0530 Subject: [PATCH 243/278] Added Heap Sort Algorithm in Python --- Python/HeapSort.py | 58 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Python/HeapSort.py diff --git a/Python/HeapSort.py b/Python/HeapSort.py new file mode 100644 index 0000000..ec2646a --- /dev/null +++ b/Python/HeapSort.py @@ -0,0 +1,58 @@ +# To heapify subtree rooted at index i. +# n is size of heap + + +def heapify(arr, n, i): + largest = i # Initialize largest as root + l = 2 * i + 1 # left = 2*i + 1 + r = 2 * i + 2 # right = 2*i + 2 + + # See if left child of root exists and is + # greater than root + + if l < n and arr[i] < arr[l]: + largest = l + + # See if right child of root exists and is + # greater than root + + if r < n and arr[largest] < arr[r]: + largest = r + + # Change root, if needed + + if largest != i: + (arr[i], arr[largest]) = (arr[largest], arr[i]) # swap + + # Heapify the root. + + heapify(arr, n, largest) + + +# The main function to sort an array of given size + +def heapSort(arr): + n = len(arr) + + # Build a maxheap. + # Since last parent will be at ((n//2)-1) we can start at that location. + + for i in range(n // 2 - 1, -1, -1): + heapify(arr, n, i) + + # One by one extract elements + + for i in range(n - 1, 0, -1): + (arr[i], arr[0]) = (arr[0], arr[i]) # swap + heapify(arr, i, 0) + + +# Driver code to test above + +arr = [12, 11, 13, 5, 6, 7, ] +heapSort(arr) +n = len(arr) +print('Sorted array is') +for i in range(n): + print(arr[i]) + From 8358dc7b5aa5aa4d9b011bc677362685a0c2d322 Mon Sep 17 00:00:00 2001 From: sheikh umaid <73013686+SheikhUmaid@users.noreply.github.com> Date: Sun, 2 Oct 2022 22:41:05 +0530 Subject: [PATCH 244/278] Added Merge Sort to Python --- Python/MergeSort.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Python/MergeSort.py diff --git a/Python/MergeSort.py b/Python/MergeSort.py new file mode 100644 index 0000000..096e841 --- /dev/null +++ b/Python/MergeSort.py @@ -0,0 +1,44 @@ +# create Merge sort algorithm + + +def merge_sort(arr): + if len(arr) > 1: + mid = len(arr) // 2 + left = arr[:mid] + right = arr[mid:] + + merge_sort(left) + merge_sort(right) + + i = j = k = 0 + + while i < len(left) and j < len(right): + if left[i] < right[j]: + arr[k] = left[i] + i += 1 + else: + arr[k] = right[j] + j += 1 + k += 1 + + while i < len(left): + arr[k] = left[i] + i += 1 + k += 1 + + while j < len(right): + arr[k] = right[j] + j += 1 + k += 1 + + + +if __name__ == '__main__': + arr = [12, 11, 13, 5, 6, 7] + merge_sort(arr) + print(arr) + + +# Output + +[5, 6, 7, 11, 12, 13] From 7b109bdad1221ecf3cfb53f5f51c74f0ab4fa1a0 Mon Sep 17 00:00:00 2001 From: sheikh umaid <73013686+SheikhUmaid@users.noreply.github.com> Date: Sun, 2 Oct 2022 22:48:49 +0530 Subject: [PATCH 245/278] Create SequencialSearch.py --- Python/SequencialSearch.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Python/SequencialSearch.py diff --git a/Python/SequencialSearch.py b/Python/SequencialSearch.py new file mode 100644 index 0000000..2354e75 --- /dev/null +++ b/Python/SequencialSearch.py @@ -0,0 +1,18 @@ +def seq_search(arr, x): + for i in range(len(arr)): + if arr[i] == x: + return i + return -1 + + + +if __name__ == '__main__': + + arr = [12, 11, 13, 5, 6, 7] + x = 11 + result = seq_search(arr, x) + if result != -1: + print("Element is present at index", str(result)) + else: + print("Element is not present in array") + From fe29a368f5ae75d49ce95ef25101a34c4d3b7e2e Mon Sep 17 00:00:00 2001 From: pooja2693 <114874630+pooja2693@users.noreply.github.com> Date: Sun, 2 Oct 2022 22:50:38 +0530 Subject: [PATCH 246/278] Add files via upload --- ck.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 ck.c diff --git a/ck.c b/ck.c new file mode 100644 index 0000000..4b39d09 --- /dev/null +++ b/ck.c @@ -0,0 +1,21 @@ + + +#include + +int main () +{ + int a; + printf ("Enter number for which you want table = "); + scanf ("%d",&a); + printf (" %d x 1 = %d\n",a, a*1); + printf (" %d x 2 = %d\n",a, a*2); + printf (" %d x 3 = %d\n",a, a*3); + printf (" %d x 4 = %d\n",a, a*4); + printf (" %d x 5 = %d\n",a, a*5); + printf (" %d x 6 = %d\n",a, a*6); + printf (" %d x 7 = %d\n",a, a*7); + printf (" %d x 8 = %d\n",a, a*8); + printf (" %d x 9 = %d\n",a, a*9); + printf (" %d x 10 = %d\n",a, a*10); + return 0; +} From 55bfce5c43b05ba317f56a61f6db0493af22806b Mon Sep 17 00:00:00 2001 From: sheikh umaid <73013686+SheikhUmaid@users.noreply.github.com> Date: Sun, 2 Oct 2022 22:57:20 +0530 Subject: [PATCH 247/278] Create InterpolationSearch.py --- Python/InterpolationSearch.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Python/InterpolationSearch.py diff --git a/Python/InterpolationSearch.py b/Python/InterpolationSearch.py new file mode 100644 index 0000000..1f64c17 --- /dev/null +++ b/Python/InterpolationSearch.py @@ -0,0 +1,26 @@ +def interpolation_search(arr, x): + low = 0 + high = len(arr) - 1 + while low <= high and x >= arr[low] and x <= arr[high]: + if low == high: + if arr[low] == x: + return low + return -1 + pos = low + int(((float(high - low) / (arr[high] - arr[low])) * (x - arr[low]))) + if arr[pos] == x: + return pos + if arr[pos] < x: + low = pos + 1 + else: + high = pos - 1 + return -1 + + +if __name__ == '__main__': + arr = [12, 11, 13, 5, 6, 7] + x = 11 + result = interpolation_search(arr, x) + if result != -1: + print("Element is present at index", str(result)) + else: + print("Element is not present in array") From 21002f723a8ca365d8ffe753ca262aaf58f5a4f0 Mon Sep 17 00:00:00 2001 From: Nitin Jaswal <62323476+walkerthecreator@users.noreply.github.com> Date: Sun, 2 Oct 2022 22:57:22 +0530 Subject: [PATCH 248/278] added recursion algorithm --- Java/recursion.java | 158 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 158 insertions(+) create mode 100644 Java/recursion.java diff --git a/Java/recursion.java b/Java/recursion.java new file mode 100644 index 0000000..7870d8b --- /dev/null +++ b/Java/recursion.java @@ -0,0 +1,158 @@ +import java.util.ArrayList; +public class Recursion { + public static void main(String[] args) { + int[] arr={1,2,3,4,5,6,6}; //7 i=7-1 6 + int target=123456; + System.out.println((findallindex(arr,6,0))); +// int digits=(int)(Math.log10(target))+1; +// System.out.println(digits); + } + + public static int fibo(int n) { + if (n<2) { + return n; + } + return fibo(n-1)+fibo(n-2); + } + + public static int bs(int[] arr,int target) { + int s=0; + int e=arr.length - 1; + while(starget) { + e=mid-1; + } + if (arr[mid]e) { + return -1; + } + + if (targetarr[mid]) { + return BSusingRecusrsion(arr, target, s = mid + 1, e); + } + return mid; + } + + public static int sumofn(int n) { + if (n<=1) { + return 1; + } + + return n+sumofn(n-1); + } + + public static int fact(int n) { + if (n<=1) { + return 1; + } + return n*fact(n-1); + + } + + public static int max(int[] nums,int i,int max) { + if (i==nums.length) { + return max; + } + + if (nums[i]>max) { + max=nums[i]; + } + return max(nums,++i,max); + } + + public static int sumofDigits(int n) { + if(n%10==n) { + return n; + } + return sumofDigits(n/10) + n%10; + } + + public static int reverseDigit(int n) { + int rev=0; + while(n!=0) { + rev=(rev*10)+(n%10); + n/=10; + } + return rev; + } + static int rev=0; + static int i=0; + public static int revusingRecursion(int n) { + if (n==0) + { + return rev; + } + rev=(rev*10)+(n%10); + n/=10; + return revusingRecursion(n); + } + + public static Boolean sortedarr(int[] nums) + { + if (i>=nums.length-1) { + return true; + } + + if (nums[i]<=nums[i+1]) { + i++; + return sortedarr(nums); + } + return false; + + } + + public static Boolean sorted(int[] nums,int j) { + if (i>=nums.length-1) { + return true; + } + return (nums[j]<=nums[j+1] && sorted(nums,++i)); + + + } + + public static int linearSearchUsingRecursion(int[] nums,int target) { + if (nums[i]==target ) { + return i; + } + i+=1; + return linearSearchUsingRecursion(nums,target); + + } + + + static ArrayList indexNos = new ArrayList(); + public static ArrayList findallindex(int[] nums,int target,int i ) { + if (i==nums.length-1) { + return indexNos; + } + if (nums[i]==target) { + indexNos.add(i); + } + return findallindex(nums,target,i+=1); + + } + + + +} + From 9b361bb0da31132f6cc104e26b0be5798cedef84 Mon Sep 17 00:00:00 2001 From: sheikh umaid <73013686+SheikhUmaid@users.noreply.github.com> Date: Sun, 2 Oct 2022 22:58:59 +0530 Subject: [PATCH 249/278] Create JumpSearch.py --- Python/JumpSearch.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Python/JumpSearch.py diff --git a/Python/JumpSearch.py b/Python/JumpSearch.py new file mode 100644 index 0000000..88d3c4f --- /dev/null +++ b/Python/JumpSearch.py @@ -0,0 +1,27 @@ +def jump_search(arr, x): + n = len(arr) + step = math.sqrt(n) + prev = 0 + while arr[int(min(step, n) - 1)] < x: + prev = step + step += math.sqrt(n) + if prev >= n: + return -1 + while arr[int(prev)] < x: + prev += 1 + if prev == min(step, n): + return -1 + if arr[int(prev)] == x: + return prev + return -1 + + + +if __name__ == '__main__': + arr = [12, 11, 13, 5, 6, 7] + x = 11 + result = jump_search(arr, x) + if result != -1: + print("Element is present at index", str(result)) + else: + print("Element is not present in array") From baa16757755d7d94bf770d24930fa1b454e62ffa Mon Sep 17 00:00:00 2001 From: sheikh umaid <73013686+SheikhUmaid@users.noreply.github.com> Date: Sun, 2 Oct 2022 23:01:06 +0530 Subject: [PATCH 250/278] Create QuickSort.py --- Python/QuickSort.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Python/QuickSort.py diff --git a/Python/QuickSort.py b/Python/QuickSort.py new file mode 100644 index 0000000..6a87250 --- /dev/null +++ b/Python/QuickSort.py @@ -0,0 +1,13 @@ +def quick_sort(arr): + if len(arr) > 1: + pivot = arr[0] + left = [i for i in arr[1:] if i <= pivot] + right = [i for i in arr[1:] if i > pivot] + return quick_sort(left) + [pivot] + quick_sort(right) + else: + return arr + + +if __name__ == '__main__': + arr = [12, 11, 13, 5, 6, 7] + print(quick_sort(arr)) From d6eea19a76329603631597f8186c7ae58be6d06e Mon Sep 17 00:00:00 2001 From: muke267 <92973548+muke267@users.noreply.github.com> Date: Sun, 2 Oct 2022 23:10:52 +0530 Subject: [PATCH 251/278] Longest Consecutive Sequence --- CPP/Longest Consecutive Sequence.cpp | 45 ++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 CPP/Longest Consecutive Sequence.cpp diff --git a/CPP/Longest Consecutive Sequence.cpp b/CPP/Longest Consecutive Sequence.cpp new file mode 100644 index 0000000..8c37118 --- /dev/null +++ b/CPP/Longest Consecutive Sequence.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + int longestConsecutive(vector& nums) { + int n=nums.size(); + // unordered_sets; + // for(int i=0;i Date: Sun, 2 Oct 2022 14:23:35 -0400 Subject: [PATCH 252/278] hacktober2022 please add this to your repository .pleaseaccept my pull request --- hacktoberfest2022 | 69 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 hacktoberfest2022 diff --git a/hacktoberfest2022 b/hacktoberfest2022 new file mode 100644 index 0000000..bcbf373 --- /dev/null +++ b/hacktoberfest2022 @@ -0,0 +1,69 @@ +#include +using namespace std; + + +class Solution { +public: + void addAll(vector < vector >& res, vector < vector >& temp){ + for(int i = 0; i < temp.size(); i++)res.push_back(temp[i]); + } + vector> fourSum(vector& nums, int target) { + sort(nums.begin(), nums.end()); + return kSum(nums, 0, 4, target); + } + vector < vector > kSum(vector & arr, int start, int k, int target){ + vector < vector > res; + if(k == 2){ + int left = start; + int right = arr.size() - 1; + vector temp(2); + while(left < right){ + if(arr[left] + arr[right] == target){ + temp[0] = arr[left]; + temp[1] = arr[right]; + res.push_back(temp); + while(left < right && arr[left] == arr[left + 1])left++; + while(left < right && arr[right] == arr[right - 1])right--; + left++; + right--; + } + else if(arr[left] + arr[right] > target)right--; + else left ++; + } + } + else{ + for(int i = start; i < (int)arr.size() - k + 1; i++){ + if(i > start && arr[i] == arr[i - 1])continue; + vector < vector > temp = kSum(arr, i + 1, k - 1, target - arr[i]); + for(int j = 0; j < temp.size(); j++){ + temp[j].push_back(arr[i]); + } + addAll(res, temp); + } + } + return res; + } +}; + + + +void print_vector(vector > v){ + cout << "["; + for(int i = 0; i v = {1,0,-1,0,-2,2}; + print_vector(ob.fourSum(v, 0)); +} From 78b3b0624296dc8956da1d3e13bf7fe819993411 Mon Sep 17 00:00:00 2001 From: Sejal Kothari <91632881+Sejzz@users.noreply.github.com> Date: Mon, 3 Oct 2022 00:21:45 +0530 Subject: [PATCH 253/278] inbuilt_sort --- inbuilt_sort.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 inbuilt_sort.cpp diff --git a/inbuilt_sort.cpp b/inbuilt_sort.cpp new file mode 100644 index 0000000..eecd2d7 --- /dev/null +++ b/inbuilt_sort.cpp @@ -0,0 +1,28 @@ +#include +#include +using namespace std; + + + +bool compare(int a,int b){ + //cout<<"Comparing "< Date: Mon, 3 Oct 2022 00:45:25 +0530 Subject: [PATCH 254/278] counting_sort --- counting_sort.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 counting_sort.cpp diff --git a/counting_sort.cpp b/counting_sort.cpp new file mode 100644 index 0000000..28d219b --- /dev/null +++ b/counting_sort.cpp @@ -0,0 +1,43 @@ +#include +#include +using namespace std; + +void counting_sort(int a[],int n){ + //Largest Element + int largest = 0; + + for(int i=0;i freq(largest+1,0); + + //Update the freq array + for(int i=0;i0){ + a[j] = i; + freq[i]--; + j++; + } + } + return; +} + +int main(){ + + int arr[] = {88, 97, 10, 12, 15, 1, 5, 6, 12, 5, 8}; + int n = sizeof(arr) / sizeof(int); + counting_sort(arr, n); + + for (int i = 0; i < n; i++) { + cout << arr[i] << " "; + } + return 0; +} \ No newline at end of file From 451a6602eb00fc73123306b650aa042eb856cdf1 Mon Sep 17 00:00:00 2001 From: Vaibhav Malkar <93985798+vaibhvmalkar@users.noreply.github.com> Date: Mon, 3 Oct 2022 00:45:36 +0530 Subject: [PATCH 255/278] Create Leap.cpp --- Leap.cpp | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Leap.cpp diff --git a/Leap.cpp b/Leap.cpp new file mode 100644 index 0000000..3ac7217 --- /dev/null +++ b/Leap.cpp @@ -0,0 +1,49 @@ +#include + +int main() { + + int year; + + printf("Enter a year: "); + + scanf("%d", &year); + + // leap year if perfectly divisible by 400 + + if (year % 400 == 0) { + + printf("%d is a leap year.", year); + + } + + // not a leap year if divisible by 100 + + // but not divisible by 400 + + else if (year % 100 == 0) { + + printf("%d is not a leap year.", year); + + } + + // leap year if not divisible by 100 + + // but divisible by 4 + + else if (year % 4 == 0) { + + printf("%d is a leap year.", year); + + } + + // all other years are not leap years + + else { + + printf("%d is not a leap year.", year); + + } + + return 0; + +} From b4f5f576646b3a87c2c28a3dfe00d0503d89ffff Mon Sep 17 00:00:00 2001 From: sejalkothari45 <114880616+sejalkothari45@users.noreply.github.com> Date: Mon, 3 Oct 2022 01:12:36 +0530 Subject: [PATCH 256/278] shortest_path --- shortest_path.cpp | 66 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 shortest_path.cpp diff --git a/shortest_path.cpp b/shortest_path.cpp new file mode 100644 index 0000000..8539b52 --- /dev/null +++ b/shortest_path.cpp @@ -0,0 +1,66 @@ +#include +using namespace std; + +int main(){ + + char route[1000]; + cin.getline(route,1000); + + int x = 0; + int y = 0; + + for(int i=0; route[i]!='\0'; i++){ + switch(route[i]){ + case 'N': y++; + break; + case 'S': y--; + break; + case 'E': x++; + break; + case 'W': x--; + break; + } + } + + cout<<"Final x and y is "<=0 and y>=0){ + while(y--){ + cout<<"N"; + } + while (x--){ + cout<<"E"; + } + + } + + if(x>=0 and y<=0){ + while(y++){ + cout<<"N"; + } + while (x--){ + cout<<"E"; + } + + } + + if(x<=0 and y>=0){ + while(y--){ + cout<<"N"; + } + while (x++){ + cout<<"E"; + } + + } + + if(x<=0 and y<=0){ + while(y++){ + cout<<"S"; + } + while (x++){ + cout<<"W"; + } + + } +} \ No newline at end of file From b5b23745ddaa083c363f7f22befb3b084ee46091 Mon Sep 17 00:00:00 2001 From: Annex5061 <113541822+Annex5061@users.noreply.github.com> Date: Mon, 3 Oct 2022 01:16:40 +0530 Subject: [PATCH 257/278] heap sort --- HeapSort.java | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 HeapSort.java diff --git a/HeapSort.java b/HeapSort.java new file mode 100644 index 0000000..4722616 --- /dev/null +++ b/HeapSort.java @@ -0,0 +1,74 @@ +package Sorting; + +public class heapify { + + public void sort(int a[]) + { + int n=a.length; + for(int i=(n/2)-1;i>=0;i--) + { + hepify(a,n,i); + } + for(int i=n-1;i>=0;i--) { + + int temp=a[0]; + a[0]=a[i]; + a[i]=temp; + + hepify(a,i,0); + } + } + + + + + + static void hepify(int a[],int n,int i) + { + int larest; + + int left=(2*i)+1; + int right=(2*i)+2; + + if(lefta[i]) + { + larest=left; + } + else{ + larest=i; + } + if(righta[larest]) + { + larest=right; + } + if(larest!=i) + { + int temp; + temp=a[i]; + a[i]=a[larest]; + a[larest]=temp; + + hepify(a,n,larest); + } + } + + static void display(int a[]) + { + for(int i=0;i Date: Mon, 3 Oct 2022 01:16:59 +0530 Subject: [PATCH 258/278] radix sort --- Javascript/radixSort.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Javascript/radixSort.js diff --git a/Javascript/radixSort.js b/Javascript/radixSort.js new file mode 100644 index 0000000..288d4a8 --- /dev/null +++ b/Javascript/radixSort.js @@ -0,0 +1,16 @@ +function radixSort(array) { + let maxCount = maxDigits(array); + + for(let i = 0; i < maxCount; i++) { + let digits = Array.from({length: 10}, () => []); + + for(let j = 0; j < array.length; j++) { + let lastDigit = getDigit(array[j], i); + digits[lastDigit].push(array[j]); + } + + array = [].concat(...digits); + } + + return array; +} \ No newline at end of file From 60799201ae326be9795e8e8001789b2c5b51886a Mon Sep 17 00:00:00 2001 From: sejsam <114881171+sejsam@users.noreply.github.com> Date: Mon, 3 Oct 2022 01:35:58 +0530 Subject: [PATCH 259/278] recursion_tree --- recursion_tree.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 recursion_tree.cpp diff --git a/recursion_tree.cpp b/recursion_tree.cpp new file mode 100644 index 0000000..c370158 --- /dev/null +++ b/recursion_tree.cpp @@ -0,0 +1,14 @@ +#include +using namespace std; + +void fun(int n){ + if(n>0){ + cout< Date: Mon, 3 Oct 2022 01:52:50 +0530 Subject: [PATCH 260/278] Added two-pointer algorithm in cpp --- twopointer.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 twopointer.cpp diff --git a/twopointer.cpp b/twopointer.cpp new file mode 100644 index 0000000..c86c8d8 --- /dev/null +++ b/twopointer.cpp @@ -0,0 +1,42 @@ +// C++ Program Illustrating Naive Approach to +// Find if There is a Pair in A[0..N-1] with Given Sum + +// Importing all libraries +#include + +using namespace std; + +bool isPairSum(int A[], int N, int X) +{ + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + // as equal i and j means same element + if (i == j) + continue; + + // pair exists + if (A[i] + A[j] == X) + return true; + + // as the array is sorted + if (A[i] + A[j] > X) + break; + } + } + + // No pair found with given sum. + return false; +} + +// Driver code +int main() +{ + int arr[] = { 2, 3, 5, 8, 9, 10, 11 }; + int val = 17; + int arrSize = *(&arr + 1) - arr; + sort(arr, arr + arrSize); // Sort the array + // Function call + cout << isPairSum(arr, arrSize, val); + + return 0; +} From a3e0bb338b842c4c4c5a25cd8193eb64ab36174d Mon Sep 17 00:00:00 2001 From: Tdms2589 <103559784+Tdms2589@users.noreply.github.com> Date: Mon, 3 Oct 2022 02:31:51 +0530 Subject: [PATCH 261/278] binary_search --- Python/binary_search.py | 78 +++++++++++++++++++++++------------------ 1 file changed, 43 insertions(+), 35 deletions(-) diff --git a/Python/binary_search.py b/Python/binary_search.py index 3dd51db..f67f9ec 100644 --- a/Python/binary_search.py +++ b/Python/binary_search.py @@ -1,35 +1,43 @@ -def binary_search(arr, low, high, x): - - # Check base case - if high >= low: - - mid = (high + low) // 2 - - # If element is present at the middle itself - if arr[mid] == x: - return mid - - # If element is smaller than mid, then it can only - # be present in left subarray - elif arr[mid] > x: - return binary_search(arr, low, mid - 1, x) - - # Else the element can only be present in right subarray - else: - return binary_search(arr, mid + 1, high, x) - - else: - # Element is not present in the array - return -1 - -# Test array -arr = [ 2, 3, 4, 10, 40 ] -x = 10 - -# Function call -result = binary_search(arr, 0, len(arr)-1, x) - -if result != -1: - print("Element is present at index", str(result)) -else: - print("Element is not present in array") +import random + + +l = [] + +for i in range(32): + l.append(random.randint(1,100)) + +l.sort() +print(l) +k = int(input("enter value of k:")) +def binary_search(l,k): + + b=0 + end=len(l)-1 + + + while(end-b>1): + mid=(end+b)//2 + + if(l[mid]==k): + print("1") + return 1 + if(l[mid]>k): + end=mid-1 + if(l[mid] Date: Mon, 3 Oct 2022 02:51:54 +0530 Subject: [PATCH 262/278] sorting_list_with_recursion --- Python/sorting_list_with_recursion.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Python/sorting_list_with_recursion.py diff --git a/Python/sorting_list_with_recursion.py b/Python/sorting_list_with_recursion.py new file mode 100644 index 0000000..493ef82 --- /dev/null +++ b/Python/sorting_list_with_recursion.py @@ -0,0 +1,17 @@ +def mini(L): + mini = L[0] + for i in range(len(L)): + if (L[i] < mini): + mini = L[i] + return mini + +def sort(L): + if (L==[]) or (len(L)==1): + return L + m = mini(L) + L.remove(m) + return [m]+sort(L) + +n = list(map(int,input().split(","))) + +print(sort(n)) \ No newline at end of file From 349147823740ab6a9e17a473fcf49778f5b4472d Mon Sep 17 00:00:00 2001 From: harshwardhan18t <80379203+harshwardhan18t@users.noreply.github.com> Date: Mon, 3 Oct 2022 03:21:24 +0530 Subject: [PATCH 263/278] Add files via upload --- C/c codes/all functios.c | 60 +++++ C/c codes/array max.c | 24 ++ C/c codes/array sum.c | 25 ++ C/c codes/fibonacci by recursion.c | 42 ++++ C/c codes/found arr.c | 41 ++++ C/c codes/functions.c | 22 ++ C/c codes/loop all.c | 101 ++++++++ C/c codes/matrix arry.c | 30 +++ C/c codes/matrix mul.c | 73 ++++++ C/c codes/matrix substra.c | 68 ++++++ C/c codes/mtrice addition.c | 68 ++++++ C/c codes/pointer madam pr 27 apr.c | 80 +++++++ C/c codes/pointers pr.c | 325 ++++++++++++++++++++++++++ C/c codes/ptr add sub mul div.c | 41 ++++ C/c codes/recursion.c | 60 +++++ C/c codes/revise fun para.c | 44 ++++ C/c codes/str cmp.c | 36 +++ C/c codes/str conversion.c | 62 +++++ C/c codes/str fun pr.c | 264 +++++++++++++++++++++ C/c codes/string.c | 154 ++++++++++++ C/c codes/struct by sir.c | 51 ++++ C/c codes/switch fun all.c | 182 +++++++++++++++ C/c codes/trans matrix.c | 41 ++++ 23 files changed, 1894 insertions(+) create mode 100644 C/c codes/all functios.c create mode 100644 C/c codes/array max.c create mode 100644 C/c codes/array sum.c create mode 100644 C/c codes/fibonacci by recursion.c create mode 100644 C/c codes/found arr.c create mode 100644 C/c codes/functions.c create mode 100644 C/c codes/loop all.c create mode 100644 C/c codes/matrix arry.c create mode 100644 C/c codes/matrix mul.c create mode 100644 C/c codes/matrix substra.c create mode 100644 C/c codes/mtrice addition.c create mode 100644 C/c codes/pointer madam pr 27 apr.c create mode 100644 C/c codes/pointers pr.c create mode 100644 C/c codes/ptr add sub mul div.c create mode 100644 C/c codes/recursion.c create mode 100644 C/c codes/revise fun para.c create mode 100644 C/c codes/str cmp.c create mode 100644 C/c codes/str conversion.c create mode 100644 C/c codes/str fun pr.c create mode 100644 C/c codes/string.c create mode 100644 C/c codes/struct by sir.c create mode 100644 C/c codes/switch fun all.c create mode 100644 C/c codes/trans matrix.c diff --git a/C/c codes/all functios.c b/C/c codes/all functios.c new file mode 100644 index 0000000..19a1a11 --- /dev/null +++ b/C/c codes/all functios.c @@ -0,0 +1,60 @@ +#include"stdio.h" //standard library or header file +void add(); // function prototye +int sub(); // function prototye +void div(int a,int b); // function prototye +int mul(int a,int b); // function prototye = when writing user defined fun below main +void main() +{ int a,b,c; + add(); // 1 + c=sub(); + printf("\n substraction is %d",c); + int sub(); + + printf("\n enter first no "); + scanf("%d",&a); + printf("\n enter second no "); + scanf("%d",&b); + div(a,b); + + printf("\n enter first no "); + scanf("%d",&a); + printf("\n enter second no "); + scanf("%d",&b); + c=mul(a,b); //call of function + printf("\n multiplication is %d",c); +} +void add() +{ int a,b,c; + printf("\n enter first no "); //void as return type and zero parameter + scanf("%d",&a); + printf("\n enter second no "); + scanf("%d",&b); + c=a+b; + printf("\n addition is %d",c); +} +int sub() +{ int a,b,c; + printf("\n enter first no "); + scanf("%d",&a); //int as return type and zero parameter + printf("\n enter second no "); + scanf("%d",&b); + c=a-b; + return c; +} +void div(int a,int b) //function prototype +{ + int c; //void as return type and parameter = input to main fun + c=a/b; + printf("\n division is %d",c); + +} +int mul(int a,int b) //function prototype +{ + int c; //int as return type and parameter + c=a*b; + return c; + + +} + + diff --git a/C/c codes/array max.c b/C/c codes/array max.c new file mode 100644 index 0000000..f967398 --- /dev/null +++ b/C/c codes/array max.c @@ -0,0 +1,24 @@ +#include //header file +void main() //main function +{ + int i,arr[5],num1,num2; //declaration of variable + for(i=1;i<=5;i++) // for loop is use for to take numbers from user + { + printf("enter your %d number",i); + scanf("%d",&arr[i]); + } printf("your enter nmubers\n"); + for(i=1;i<=5;i++) //for loop is use for to print numbers that give by user + printf("%d\n",arr[i]); + for(i=1;i<=5;i++) //for loop is use for to find max number + { + if (num1<=arr[i]) + num1=arr[i]; + } + for(i=1;i<=5;i++) //for loop is use for to find min number + { + if (num2>=arr[i]) + num2=arr[i]; + } + printf("\n max number is %d",num1); //to print max number + printf("\n min number is %d",num2); //to print min number +} diff --git a/C/c codes/array sum.c b/C/c codes/array sum.c new file mode 100644 index 0000000..0635f93 --- /dev/null +++ b/C/c codes/array sum.c @@ -0,0 +1,25 @@ +#include +void main() + +{ +int p,i,sum=0,n[p]; + +printf("enter your choice of number you want for addition = "); +scanf("\n%d",&p); +printf("enter your %d numbers\n",p); +for(i=1;i<=p;i++) +{ + scanf("\n%d",&n[i]); + +} +for(i=1;i<=p;i++) +{ + printf("\n %d",n[i]); +} +for(i=1;i<=p;i++) +{ + sum=n[i]+sum; +} +printf("\n\t addition of your %d numbers is %d",p,sum); +} + diff --git a/C/c codes/fibonacci by recursion.c b/C/c codes/fibonacci by recursion.c new file mode 100644 index 0000000..67860ee --- /dev/null +++ b/C/c codes/fibonacci by recursion.c @@ -0,0 +1,42 @@ +// function to find the nth fibonacci +#include +int main() +{ + int n = 0,m,i; + printf("enter value of m "); + scanf("%d",&m); + for(i=0;i + void main () + { + int i,j,k,a[5] ; + + for (i=0;i<5;i++) + { + scanf("\n%d",&a[i]); + } + for (i=0;i<5;i++) + { + printf("\n%d",a[i]); + } + + printf("\n enter key "); + scanf("\n%d",&j); + + for (i=0;i<5;i++) + { + if (j==a[i]) + { + k=0; + break; + } + else + { + k=1; + } } + + if (k==0) + { + printf("\n found"); + + } + + else{ + + printf("\n not found");} + + +} diff --git a/C/c codes/functions.c b/C/c codes/functions.c new file mode 100644 index 0000000..9988647 --- /dev/null +++ b/C/c codes/functions.c @@ -0,0 +1,22 @@ +#include +void add(); +void sub(); +void main() // grp of statement executed only when it is called +{ + printf("\n inside main fun"); + + add(); + sub (); //calling of fun |imp| at time of call it starts executing from add funcion and then back to previous + + printf("\n hello"); + +} +void add() // not called function so not printed zero parameter fun def or body +{ + printf("\n inside add fun"); //calling itself will recursive +} +void sub () // not called function so not printed zero parameter +{ + printf("\n inside sub fun"); + +} // fun prototype = void add(); write above main function diff --git a/C/c codes/loop all.c b/C/c codes/loop all.c new file mode 100644 index 0000000..3b42bdb --- /dev/null +++ b/C/c codes/loop all.c @@ -0,0 +1,101 @@ +/*#include +void main() +{ + int i,n; + printf("enter number "); + scanf("\n%d",&n); + + for(i=0;i<=n;i++) + { + printf("\t%d",i); + } + } + */ + +/*#include +void main() +{ + int i,n; + printf("enter number "); + scanf("\n%d",&n); + + i=0; + while(i<=n) + { + printf("\t%d",i); + i++; + } + + + +}*/ + + + + +/*#include +void main() +{ + int i,n; + printf("enter number "); + scanf("\n%d",&n); + + i=1; + do + { + printf("\t%d",i); + i++; + } + while(i<=n); ///semicolon required + + }*/ + + //reverse + +/*#include +void main() +{ + int i,n; + printf("enter number "); + scanf("\n%d",&n); + + for(i=n;i>=1;i--) + { + printf("\t%d",i); + } + }*/ + +/* #include +void main() +{ + int i,n; + printf("enter number "); + scanf("\n%d",&n); + + i=n; + while(i>=1) + { + printf("\t%d",i); + i--; +}}*/ + + +/*#include +void main() +{ + int i,n; + printf("enter number "); + scanf("\n%d",&n); + + i=n; + do + { + printf("\t%d",i); + i--; + } + while(i>=1);}*/ + + + + + diff --git a/C/c codes/matrix arry.c b/C/c codes/matrix arry.c new file mode 100644 index 0000000..d7e3232 --- /dev/null +++ b/C/c codes/matrix arry.c @@ -0,0 +1,30 @@ +#include +void main() +{ +int row,col; + float a[2][2]; //2d dimensional array + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + scanf("%f",&a[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + + { + + for (col=0;col<2;col++) + { + + printf("%2.f\t",a[row][col]); + } printf("\n"); + + } + + printf("\n"); +} diff --git a/C/c codes/matrix mul.c b/C/c codes/matrix mul.c new file mode 100644 index 0000000..184fe4e --- /dev/null +++ b/C/c codes/matrix mul.c @@ -0,0 +1,73 @@ +#include +void main() +{ +int row,col; + int a[2][2],b[2][2],c[col][row],k; //2d dimensional array + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + scanf("%d",&a[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",a[row][col]); + } + printf("\n"); + + } + + printf("\n"); + + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + scanf("%d",&b[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",b[row][col]); + } + printf("\n"); + + } + + printf("\n"); + + + printf("multiplication is"); + + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + c[row][col]=0; + + for (k=0;k<2;k++) + { + c[row][col] = c[row][col] + (a[row][k]*b[k][col]); + } + printf("%d\t",c[row][col]); + } + printf("\n"); + } + + +} diff --git a/C/c codes/matrix substra.c b/C/c codes/matrix substra.c new file mode 100644 index 0000000..ae148bc --- /dev/null +++ b/C/c codes/matrix substra.c @@ -0,0 +1,68 @@ +#include +void main() +{ +int row,col; + int a[2][2],addition; //2d dimensional array + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + scanf("%d",&a[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",a[row][col]); + } + printf("\n"); + + } + + printf("\n"); + + int b[2][2]; //2d dimensional array + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + scanf("%d",&b[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",b[row][col]); + } + printf("\n"); + + } + + printf("\n"); + + + printf("substraction is"); + + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",a[row][col]-b[row][col]); + } + printf("\n"); + } + + +} diff --git a/C/c codes/mtrice addition.c b/C/c codes/mtrice addition.c new file mode 100644 index 0000000..9faacf7 --- /dev/null +++ b/C/c codes/mtrice addition.c @@ -0,0 +1,68 @@ +#include +int main() +{ +int row,col; + int a[2][2],addition; //2d dimensional array + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + scanf("%d",&a[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",a[row][col]); + } + printf("\n"); + + } + + printf("\n"); + + int b[2][2]; //2d dimensional array + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + scanf("%d",&b[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",b[row][col]); + } + printf("\n"); + + } + + printf("\n"); + + + printf("addition is"); + + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",a[row][col]+b[row][col]); + } + printf("\n"); + } + + +} diff --git a/C/c codes/pointer madam pr 27 apr.c b/C/c codes/pointer madam pr 27 apr.c new file mode 100644 index 0000000..4258d45 --- /dev/null +++ b/C/c codes/pointer madam pr 27 apr.c @@ -0,0 +1,80 @@ +#include +int ptr_addition (); +int ptr_substraction (); +int ptr_increment (); +int ptr_decrement (); +void main () +{ ptr_addition (); + ptr_substraction (); + ptr_increment (); + ptr_decrement (); +} + +int ptr_addition () +{ + int n = 4 ; + int *ptr1; + ptr1=&n; + printf("\n pointer before addition = %d",ptr1); + + ptr1 = ptr1 + 3; + printf("\n pointer after addition = %d\n",ptr1); + + return 0; +} + +int ptr_substraction () +{ + int m = 4 ; + int *ptr2; + ptr2=&m; + printf("\n pointer before substractio = %d",ptr2); + + ptr2 = ptr2 - 3; + printf("\n pointer after substractio = %d\n",ptr2); + + return 0; +} + +int ptr_increment () +{ + int var[] = {10,100,200}; + int i,*ptr3; + ptr3=var; + + for(i=0;i<3;i++) + { + printf("\n address of var[%d] = %d",i,ptr3); + printf("\n value of var[%d] = %d",i,*ptr3); + ptr3++; + } + printf("\n"); +} + + +int ptr_decrement () +{ + int var[] = {10,100,200}; + int i,*ptr4; + ptr4=&var[2]; + + for(i=3;i>0;i--) + { + printf("\n address of var[%d] = %d",i,ptr4); + printf("\n value of var[%d] = %d",i,*ptr4); + ptr4--; + } + printf("\n"); +} + + + + + + + + + + + + diff --git a/C/c codes/pointers pr.c b/C/c codes/pointers pr.c new file mode 100644 index 0000000..e96a175 --- /dev/null +++ b/C/c codes/pointers pr.c @@ -0,0 +1,325 @@ +#include +#include + +/*void main () +{ + int a=10; + int* ptr=&a; + + printf("\n%d",&a); + printf("\n%d",ptr); + printf("\n%d",*ptr); + printf("\n%d",&ptr); +}*/ + + +/*void main () // by 2 variables +{ + int a=5, b=10,c,d; + + printf("\n value of a = %d",a); + printf("\n value of b %d",b); + + c=a; d=b; a=b; b=c; + + printf("\n value of a %d",a); + printf("\n value of b %d",b); + +}*/ + +/* +void main () // by no variables +{ + int a=5, b=10; + + printf("\n value of a = %d",a); + printf("\n value of b %d",b); + a=a+b; + b=a-b; + a=a-b; + printf("\n value of a %d",a); + printf("\n value of b %d",b); + +} +*/ + + +/* +void swap(int a,int b); +void main () // by no variables +{ + int a=0, b=0; + + scanf("%d",&a); + printf("\n value of a = %d\n",a); + scanf("%d",&b); + printf("\n value of b %d",b); + + swap(a,b); + +} +void swap(int a,int b) +{ + a=a+b; + b=a-b; + a=a-b; + + printf("\n value of a %d",a); + printf("\n value of b %d",b); + +}*/ + + +/* +// call by value +void swap(int a,int b); +void main () // by no variables +{ + int a=0, b=0; + + scanf("%d",&a); + printf("\n value of a = %d\n",a); + scanf("%d",&b); + printf("\n value of b %d",b); + + swap(a,b); //will print same values as main fun drawback of call by value will not swap in main function + + + printf("\n value of a %d",a); + printf("\n value of b %d",b); + +} +void swap(int a,int b) +{ + a=a+b; + b=a-b; + a=a-b; + +}*/ + +/* +// call by reference with one variable +void swap(int* a,int* b); +void main () +{ + int a=0, b=0; + + scanf("%d",&a); + printf(" a before swap outside fun = %d\n",a); + scanf("%d",&b); + printf(" b before swap outside fun = %d\n",b); + + swap(&a,&b); + + + printf("\n a after swap outside fun %d\n",a); + printf("\n b after swap outside fun %d\n",b); + +} +void swap(int* a,int* b) +{ + printf(" a before swap in fun = %d\n",*a); + printf(" b before swap in fun = %d\n",*b); + int c; + c=*a; + *a=*b; + *b=c; + printf("\n a after swap in fun %d\n",*a); + printf("\n b after swap in fun %d\n",*b); +} +*/ + + + +/* +void swap(int* a,int* b); ///by no variable +void main () +{ + int a=0, b=0; + + scanf("%d",&a); + printf(" a before swap outside fun = %d\n",a); + scanf("%d",&b); + printf(" b before swap outside fun = %d\n",b); + + swap(&a,&b); + + + printf("\n a after swap outside fun %d\n",a); + printf("\n b after swap outside fun %d\n",b); + +} +void swap(int* a,int* b) +{ + printf(" a before swap in fun = %d\n",*a); + printf(" b before swap in fun = %d\n",*b); + *a=*a+*b; + *b=*a-*b; + *a=*a-*b; + printf("\n a after swap in fun %d\n",*a); + printf("\n b after swap in fun %d\n",*b); +} + + +void main () + { + +int a[5]={1,2,3,4,5}; +int i; + +for(i=0;i<5;i++) +{ + printf("%d",a[i]); +} + +}*/ + + +/* +void main () + { + +int a[5]={1,2,3,4,5}; +int i, *ptr=a; + +for(i=0;i<5;i++) +{ + printf("%d\n",*ptr); + *ptr++; +} + +}*/ + + + /* //code for forward n reverse printing of array by pointers. +void main () + { + +int a[5]={1,2,3,4,5}; +int i, *ptr=a; + +for(i=0;i<5;i++) +{ + printf("%d\t",*ptr); + ptr++; +} + printf("\n\n"); + ptr = &a[4]; +for(i=0;i<5;i++) +{ + printf("%d\t",*ptr); + ptr--; +} + +}*/ + + + + + + // code for forward n reverse printing of my name by pointers +void main () +{ +char a[5000]; +printf("enter your name "); +gets(a); + +int l=strlen(a),i; +char *ptr=&a[0]; + +for(i=0;i +void add(int *a,int *b); +void sub(int *a,int *b); +void mul(int *a,int *b); +void div(int *a,int *b); +void main() +{ + int a,b; + printf("enter values of a and b "); + scanf("%d %d",&a,&b); + + add (&a,&b); + sub (&a,&b); + mul (&a,&b); + div (&a,&b); + +} +void add(int *a,int *b) +{ + int c; + c=*a+*b; + printf("addition is %d\n",c); +} +void sub(int *a,int *b) +{ + int c; + c=*a-*b; + printf("substraction is %d\n",c); +} +void mul(int *a,int *b) +{ + int c; + c=*a * *b; + printf("multiplition is %d\n",c); +} +void div(int *a,int *b) +{ + int c; + c=*a / *b; + printf("division is %d\n",c); +} diff --git a/C/c codes/recursion.c b/C/c codes/recursion.c new file mode 100644 index 0000000..b5c72ae --- /dev/null +++ b/C/c codes/recursion.c @@ -0,0 +1,60 @@ +#include + +//void display( int a); +//// recursion = calling by own goes infinite imp = termiation +//void main() +//{ int a=0; +// display(a); +//} +//void display( int a) +//{ +// while(a<2) //termination +// { a++; +// printf("hello\t"); +// display(a); //recursive +// +// } +// +//} + + +int main() +{ + int a = 0,result = 0; + printf("enter values of a "); + scanf("%d",&a); + result = fact (a); + printf("%d",result); + return 0; +} +int fact(int a) +{ + if(a==0) + return 1; + return a*fact(a-1); //recursive call +} + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/C/c codes/revise fun para.c b/C/c codes/revise fun para.c new file mode 100644 index 0000000..73d6de1 --- /dev/null +++ b/C/c codes/revise fun para.c @@ -0,0 +1,44 @@ +#include"stdio.h" +float sub(); +void add(); +void mul(); +void main() +{ +int a=100; +int b=200; +scanf("%d",&a); +scanf("%d",&b); +float c; +c=sub(a,b); //1 + + printf("\n%f",c); +add(a,b);//2 +mul(); //3 +} + +//1.function with other (int , float) return type and two parameter +float sub(int ab, int ba) +{ +int d; +float k; +k=ab-ba; +return k; +} + +//2.function with void return type and two parameter +void add(int a, int b) +{ +int c; +c=a+b; +printf("\n%d",c); //300 +} + +//3.function with void return type and no parameter +void mul() +{ +int a=100; +int b=200; +int c; +c=a*b; +printf("\n%d",c); +} diff --git a/C/c codes/str cmp.c b/C/c codes/str cmp.c new file mode 100644 index 0000000..a570a8a --- /dev/null +++ b/C/c codes/str cmp.c @@ -0,0 +1,36 @@ +#include +#include + +void main() +{ + char n1[100] ; + char n2[100]; + + printf("\n enter your first name "); + scanf("%s",n1); + printf("\n%s",n1); + + printf("\n enter your last name "); + scanf("%s",n2); + printf("\n%s",n2); + + int res; + res = strcmp (n1,n2); //alphabates are considered by lexicographic order (dictionary order) + + if(res==0) + { + printf("\n both are equal "); + } + else if(res>0) + { + printf("\n first is greater "); + } + else if(res<0) + { + printf("\n first is smaller "); + } + + + + +} diff --git a/C/c codes/str conversion.c b/C/c codes/str conversion.c new file mode 100644 index 0000000..9ae3038 --- /dev/null +++ b/C/c codes/str conversion.c @@ -0,0 +1,62 @@ +#include +#include + +void main() +{ +// int i; +// char n1[5]="harsh"; +// printf("\n \t original name is %s",n1); +// printf("\n"); +// +// for(i=0;i<5;i++) +// { +// printf("\n%d",n1[i]); +// } +// printf("\n"); +// for(i=0;i<5;i++) +// { +// n1[i]=n1[i]+32; +// printf("\n%d",n1[i]); +// +// } +// printf("\n"); +// printf("\n \t converted name is %s",n1); + + + + + + // lower to upper + int i; + char n1[20]; + + printf("\n enter your string "); + scanf("%s",n1); + int l=strlen(n1); + +// puts(n); + + printf("\n \t original string is %s",n1); + printf("\n"); + + for(i=0;i +#include +// //stringcopy without strcpy +//void main() +// +//{ +// int i,l=0; +// char n1[20]; +// +// +// printf("\n enter your string "); +// scanf("%s",n1); +// +// for(i=0;n1[i]!='\0';i++) +// { +// l++; +// } +// printf("\n\t %d",l); +//} + + + + + + + + + + + + + + + +//own function call in void baki all own fun madhe + +//void stringlength(); +//void main() +// +//{ +// stringlength(); +//} +//void stringlength() +//{ +// int i,l=0; +// char n1[20]; +// printf("\n enter your string "); +// scanf("%s",n1); +// +// for(i=0;n1[i]!='\0';i++) +// { +// l++; +// } +// printf("\n\t %d",l); +//} + + + + + + + +//// parameter with return type + +//int stringlength(char n1[]); +//void main() +// +//{ +// int i,l=0; +// char n1[20]; +// printf("\n enter your string "); +// scanf("%s",n1); +// l=stringlength(n1); +// printf("\n\t string length is %d",l); +//} +//int stringlength(char n1[]) +//{ +// int i,l=0; +// +// +// for(i=0;n1[i]!='\0';i++) +// { +// l++; +// } +// return l; +//} + + + + +// its by str function we want it without using strcpy = by own function + +// void main() +// { +// char name[10] ; +// char name1[10]; +// +// scanf("%s",name); +// printf("\n%s",name); +// +// strcpy(name1,name) ; //to copy name from one string to another (destination , source) +// printf("\n name1 is %s",name1); +// printf("\n name is %s",name); +//} + + + +/* own function=to copy name from one string to another +void main() +{ + int i; + char n1[20],n2[20]; + + printf("\n enter your string "); + scanf("%s",n1); + printf("\n entered string is = %s",n1); + + for(i=0;n1[i]!='\0';i++) + { + n2[i]=n1[i]; + + } + printf("\n copied string is = %s",n2); + +}*/ + + + + +/* // by parameter +void stringcopy(char n2[20],char n1[20]); +void main() +{ + int i; + char n1[20],n2[20]; + + printf("\n enter your string "); + scanf("%s",n1); + printf("\n entered string is = %s",n1); + stringcopy(n2,n1); + printf("\n copied string is = %s",n2); + +} +void stringcopy(char n2[],char n1[]) +{ int i; + for(i=0;n1[i]!='\0';i++) + { + n2[i]=n1[i]; + } +} +*/ + + + + + +/// own function=to put one str after other +/* +void stringconcatination(char n2[],char n1[]); +void main() +{ + char f[20],c[20]; + + printf("\n enter first string "); + scanf("%s",f); + printf("\n entered string is = %s",f); + + printf("\n enter second string "); + scanf("%s",c); + printf("\n entered string is = %s",c); + + stringconcatination(f,c); + printf("\n new string is = %s",f); + +} +void stringconcatination(char f[],char c[]) +{ int i,j; + for(i=0;i +#include + +void main() +{ + char name[1024]="mitaoe hii"; //string array always end with \o + +// char n1='A'; + printf("%d",name); //%d = will print ascii value + printf("\n%c",name); //%c character value + +// printf("%c",name[4]); //to print single character +// +// scanf("%s",name); +// printf("\n%s",name); + + + +/* char name[15]; + char n1='q',n2='Q'; + printf("\n enter your name "); + scanf("%s",name); + printf("\n name is %s",name); + printf("\nascii value q is %d\nascii value Q is %d",n1,n2); +*/ + + + + +// 1) string length +/* char name[6]; + scanf("%s",name); + int l = strlen(name); //to calcuate length of string + printf("\n string length is %d",l); +*/ + + + +// 2) string copy +/* char name[10] ; + char name1[10]; + + scanf("%s",name); + printf("\n%s",name); + + strcpy(name1,name) ; //to copy name from one string to another (destination , source) + printf("\n name1 is %s",name1); + printf("\n name is %s",name); + + + + + +// 3) string compare + +/* char n1[10] ; + char n2[10]; + + printf("\n enter your first name "); + scanf("%s",n1); + printf("\n%s",n1); + printf("\n enter your last name "); + scanf("%s",n2); + printf("\n%s",n2); + + //alphabates are considered by lexicographic order (dictionary order) + int res = strcmp(n1,n2); // name character array //to compare values all equal = 1 , first smaller -1 , first larger +1 + + // int res = strcmp("mit","mit"); // string // can give directly also + //printf("%d",res); //%d as 0,-1,+1 + + if(res==0) + { + printf("\n both are equal "); + } + else if(res>0) + { + printf("\n first is greater "); + } + else if(res<0) + { + printf("\n first is smaller "); + } +*/ + + + + + + +// 4) string concatination + +/* char n1[10] ; + char n2[10]; + + printf("\n enter your first name "); + scanf("%s",n1); + printf("\n%s\n",n1); + printf("\n enter your last name "); + scanf("%s",n2); + printf("\n%s\n",n2); + + strcat(n1,n2); //strng concatination = attatch one strng to other + printf("\n output concatination is %s",n1); + + int l=strlen(n1); + printf("\n\n length of output concatination is %d",l); +*/ + + + +// 5) string reverse +/* char n1[10] ; + printf("\n enter your first name "); + scanf("%s",n1); + printf("\n%s\n",n1); + strrev(n1); + printf("\n output reverse is %s",n1); +*/ + + + +// 6) sub string + /*char n1[10]; + char n2[10]; + + printf("\n enter your first name "); + scanf("%s",n1); + printf("\n%s\n",n1); + printf("\n enter your last name "); + scanf("%s",n2); + printf("\n%s\n",n2); + +// strstr(n1,n2) // (n1 = to where ,n2 = to whom) + if(strstr(n1,n2)==NULL) // 0 CHALEGA KYA ?????????????????????????????????????? + { + printf("\n SUBSTRING NOT AVAILABLE"); + } + else + { + printf("\n SUBSTRING AVAILABLE"); + }*/ + + + + + + + + + + + +} diff --git a/C/c codes/struct by sir.c b/C/c codes/struct by sir.c new file mode 100644 index 0000000..b474050 --- /dev/null +++ b/C/c codes/struct by sir.c @@ -0,0 +1,51 @@ +#include +//struct stu +//{ +// int rno; //4 +// int prn; //4 +//}; +//int main() +//{ +// struct stu s1; +// struct stu s2; +// +// printf("enter roll no and prn no for student 1 \n"); +// scanf("%d\t %d",&s1.rno,&s1.prn); +// printf("enter roll no and prn no for student 2 \n"); +// scanf("%d\t %d",&s2.rno,&s2.prn); +// +// printf("roll no = %d\t prn no = %d\n ",s1.rno,s1.prn); +// +// printf("roll no = %d\t prn no = %d\n",s2.rno,s2.prn); +// +// printf("size of s1 is %d",sizeof(s1)); +// +// return 0; +//} + + + +struct stu +{ + int rno; //4 + int prn; //4 +}; +int main() +{ + struct stu s[3]; //array of objects + int i; + + for(i=0;i<3;i++) + { + printf("enter roll no and prn no for student %d \n",i+1); + scanf("%d",&s[i].rno); + scanf("%d",&s[i].prn); + } + for(i=0;i<3;i++) + { + printf(" roll no and prn no for student %d \n",i+1); + printf("\t%d\n",s[i].rno); + printf("\t%d\n",s[i].prn); + } + return 0; +} diff --git a/C/c codes/switch fun all.c b/C/c codes/switch fun all.c new file mode 100644 index 0000000..d68f6d7 --- /dev/null +++ b/C/c codes/switch fun all.c @@ -0,0 +1,182 @@ +/* name = harshwardhan prakash tilekar + division = A + batch = A1 + roll no = 108 + practical 10 = Write a program in C using functions to display addition, subtraction, multiplication, division of two numbers. +*/ + +#include"stdio.h" //standard library or header file +void add(); // function prototye +int sub(); // function prototye +void div(int a,int b); // function prototye +int mul(int a,int b); // function prototye + +void main() // system defined main function + +{ int a,b,c,choice,sub(); //declaration of variable + + printf("MENU"); // menu + printf("\n 1) ADDITION "); // option for ADDITION + printf("\n 2) SUBSTRACITION "); // option for SUBSTRACITION + printf("\n 3) DIVISION "); // option for DIVISION + printf("\n 4) MULTIPLICATION "); // option for MULTIPLICATION + do{ + + printf("\n ENTER YOUR CHOICE "); // printf statement for asking user's choice + scanf("%d",&choice); // scanf statement take and store value from user + + switch (choice) // switch cases for choice + { case 1 : + add(); //calling of function + break; // end of case + + case 2 : + + c=sub(); //calling of function + printf("\n substraction is %d",c); //printf function for printing results + break; // end of case + + case 3 : + printf("\n enter first no "); + scanf("%d",&a); + printf("\n enter second no "); + scanf("%d",&b); + div(a,b); //calling of function + break; // end of case + + case 4 : + printf("\n enter first no "); + scanf("%d",&a); + printf("\n enter second no "); + scanf("%d",&b); + c=mul(a,b); //calling of function + printf("\n multiplication is %d",c); //printf function for printing results + break; // end of case + + default: + printf(" invalid choice !!! "); // printf statement for printing invalid choice + break; + }}while(choice!=4);} + + +void add() //function definition and functon body +{ int a,b,c; + printf("\n enter first no "); + scanf("%d",&a); + printf("\n enter second no "); + scanf("%d",&b); + c=a+b; //mathematical expression for addition + printf("\n addition is %d",c); //printf function for printing results +} +//function with int return type +int sub() //function definition and functon body +{ int a,b,c; + printf("\n enter first no "); + scanf("%d",&a); + printf("\n enter second no "); + scanf("%d",&b); + c=a-b; //mathematical expression for substraction + return c; //return type +} +//function with two parameter +void div(int a,int b) //function definition and functon body +{ + int c; + c=a/b; //mathematical expression for division + printf("\n division is %d",c); //printf function for printing results + +} +//function with int return type and two parameter +int mul(int a,int b) //function definition and functon body +{ + int c; + c=a*b; //mathematical expression for multiplication + return c; //return type + +} + + + +/* +case 1 = +MENU + 1) ADDITION + 2) SUBSTRACITION + 3) DIVISION + 4) MULTIPLICATION + ENTER YOUR CHOICE 1 + + enter first no 10 + + enter second no 20 + + addition is 30 +-------------------------------- +Process exited after 6.085 seconds with return value 16 +Press any key to continue . . . + +case 2 = +MENU + 1) ADDITION + 2) SUBSTRACITION + 3) DIVISION + 4) MULTIPLICATION + ENTER YOUR CHOICE 2 + + enter first no 10 + + enter second no 5 + + substraction is 5 +-------------------------------- +Process exited after 4.903 seconds with return value 19 +Press any key to continue . . . + +case 3 = +MENU + 1) ADDITION + 2) SUBSTRACITION + 3) DIVISION + 4) MULTIPLICATION + ENTER YOUR CHOICE 3 + + enter first no 200 + + enter second no 5 + + division is 40 +-------------------------------- +Process exited after 5.113 seconds with return value 16 +Press any key to continue . . . + +case 4 = +MENU + 1) ADDITION + 2) SUBSTRACITION + 3) DIVISION + 4) MULTIPLICATION + ENTER YOUR CHOICE 4 + + enter first no 200 + + enter second no 5 + + multiplication is 1000 +-------------------------------- +Process exited after 5.673 seconds with return value 24 +Press any key to continue . . . + +case 5 = +MENU + 1) ADDITION + 2) SUBSTRACITION + 3) DIVISION + 4) MULTIPLICATION + ENTER YOUR CHOICE 5 + invalid choice !!! +-------------------------------- +Process exited after 1.677 seconds with return value 21 +Press any key to continue . . . + +*/ + diff --git a/C/c codes/trans matrix.c b/C/c codes/trans matrix.c new file mode 100644 index 0000000..01375e6 --- /dev/null +++ b/C/c codes/trans matrix.c @@ -0,0 +1,41 @@ +#include +void main() +{ +int row,col; + int a[3][3],addition; //2d dimensional array + + for (row=0;row<3;row++) + { + for (col=0;col<3;col++) + { + scanf("%d",&a[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<3;row++) + { + for (col=0;col<3;col++) + { + printf("%d\t",a[row][col]); + } + printf("\n"); + + } + + printf("transpose of matrix is"); + + printf("\n\n\n\n"); + + for (row=0;row<3;row++) + { + for (col=0;col<3;col++) + { + printf("%d\t",a[col][row]); + } + printf("\n"); + + } + +} From c58402095c0b67533fe8dda949a0c9d6190ed382 Mon Sep 17 00:00:00 2001 From: Harsh Rawat <112020551+Rawharsh@users.noreply.github.com> Date: Mon, 3 Oct 2022 03:37:56 +0530 Subject: [PATCH 264/278] Create CODE FOR FINDING THE TOTAL NO. OF OCCURENCE OF ANY NO. IN SORTED ARRAY USING BINARY SEARCH --- ...NY NO. IN SORTED ARRAY USING BINARY SEARCH | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 CPP/CODE FOR FINDING THE TOTAL NO. OF OCCURENCE OF ANY NO. IN SORTED ARRAY USING BINARY SEARCH diff --git a/CPP/CODE FOR FINDING THE TOTAL NO. OF OCCURENCE OF ANY NO. IN SORTED ARRAY USING BINARY SEARCH b/CPP/CODE FOR FINDING THE TOTAL NO. OF OCCURENCE OF ANY NO. IN SORTED ARRAY USING BINARY SEARCH new file mode 100644 index 0000000..1ed586b --- /dev/null +++ b/CPP/CODE FOR FINDING THE TOTAL NO. OF OCCURENCE OF ANY NO. IN SORTED ARRAY USING BINARY SEARCH @@ -0,0 +1,102 @@ + + //CODE FOR FINDING THE TOTAL NO. OF OCCURENCES OF ANY NO. IN SORTED ARRAY USING BINARY SEARCH + + +#include +using namespace std; + + //FUNTION FOR FINDING THE FIRST MOST OCCURANCE OF A NUMBER + int first_occurence(int arr[],int n,int key) + { + int start=0,end=n-1,mid,first_index; + mid=start + (end-start)/2; + + + while(start<=end) + { + if(arr[mid]==key) + { + first_index=mid; + end=mid-1 ; + } + if(arr[mid]key) + { + end=mid-1; + } + + mid=start + (end-start)/2; + + } + + return first_index; + + + } + + + //FUNTION FOR FINDING THE LAST MOST OCCURANCE OF A NUMBER + int last_occurence(int arr[],int n,int key) + { + int start=0,end=n-1,mid,last_index; + mid=start + (end-start)/2; + + + while(start<=end) + { + if(arr[mid]==key) + { + last_index=mid; + start=mid+1 ; + } + if(arr[mid]key) + { + end=mid-1; + } + + mid=start + (end-start)/2; + + } + + return last_index; + + + } + + +int main() { + int n; + cout<<"ENTER THE LENGTH OF THE ARRAY"<>n; + + int arr[n],key,first_index,last_index; + + + cout<<"ENTER THE ELEMENTS OF SORTED ARRAY"<>arr[i]; + } + + cout<<"ENTER THE ELEMENT/KEY WHOSE OCCURANCE YOU WANT TO FIND"<>key; + + first_index=first_occurence(arr,n,key); //CALLING OF first_occurence FUNCTION + + last_index=last_occurence(arr,n,key); //CALLING OF last_occurence FUNCTION + + cout<<"NO. OF OCCURENCE OF "< Date: Mon, 3 Oct 2022 05:46:07 +0530 Subject: [PATCH 265/278] Create m --- go/m | 1 + 1 file changed, 1 insertion(+) create mode 100644 go/m diff --git a/go/m b/go/m new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/go/m @@ -0,0 +1 @@ + From 93319187cc39b53cf4b45c0ea35007653dfbd5a1 Mon Sep 17 00:00:00 2001 From: Astra5155j <80286220+Astra5155j@users.noreply.github.com> Date: Mon, 3 Oct 2022 05:47:30 +0530 Subject: [PATCH 266/278] Add files via upload --- go/doc.go | 2 + go/generator.go | 46 +++++++++++++++++++ go/hashing_test.go | 3 ++ go/sha256.go | 112 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 163 insertions(+) create mode 100644 go/doc.go create mode 100644 go/generator.go create mode 100644 go/hashing_test.go create mode 100644 go/sha256.go diff --git a/go/doc.go b/go/doc.go new file mode 100644 index 0000000..1e44253 --- /dev/null +++ b/go/doc.go @@ -0,0 +1,2 @@ +// Package hashing containing different implementation of certain hashing +package hashing diff --git a/go/generator.go b/go/generator.go new file mode 100644 index 0000000..4623736 --- /dev/null +++ b/go/generator.go @@ -0,0 +1,46 @@ +// This program generates a password from a list of possible chars +// You must provide a minimum length and a maximum length +// This length is not fixed if you generate multiple passwords for the same range + +// Package password contains functions to help generate random passwords +package password + +import ( + "crypto/rand" + "io" + "math/big" +) + +// Generate returns a newly generated password +func Generate(minLength int, maxLength int) string { + var chars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,.?/:;{}[]`~") + + length, err := rand.Int(rand.Reader, big.NewInt(int64(maxLength-minLength))) + if err != nil { + panic(err) // handle this gracefully + } + length.Add(length, big.NewInt(int64(minLength))) + + intLength := int(length.Int64()) + + newPassword := make([]byte, intLength) + randomData := make([]byte, intLength+intLength/4) + charLen := byte(len(chars)) + maxrb := byte(256 - (256 % len(chars))) + i := 0 + for { + if _, err := io.ReadFull(rand.Reader, randomData); err != nil { + panic(err) + } + for _, c := range randomData { + if c >= maxrb { + continue + } + newPassword[i] = chars[c%charLen] + i++ + if i == intLength { + return string(newPassword) + } + } + } +} diff --git a/go/hashing_test.go b/go/hashing_test.go new file mode 100644 index 0000000..9067f84 --- /dev/null +++ b/go/hashing_test.go @@ -0,0 +1,3 @@ +// Empty test file to keep track of all the tests for the algorithms. + +package hashing diff --git a/go/sha256.go b/go/sha256.go new file mode 100644 index 0000000..9061f38 --- /dev/null +++ b/go/sha256.go @@ -0,0 +1,112 @@ +// sha256.go +// description: The sha256 cryptographic hash function as defined in the RFC6234 standard. +// author: [Paul Leydier] (https://github.com/paul-leydier) +// ref: https://datatracker.ietf.org/doc/html/rfc6234 +// ref: https://en.wikipedia.org/wiki/SHA-2 +// see sha256_test.go + +package sha256 + +import ( + "encoding/binary" // Used for interacting with uint at the byte level + "math/bits" // Used for bits rotation operations +) + +var K = [64]uint32{ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +} + +const chunkSize = 64 + +// pad returns a padded version of the input message, such as the padded message's length is a multiple +// of 512 bits. +// The padding methodology is as follows: +// A "1" bit is appended at the end of the input message, followed by m "0" bits such as the length is +// 64 bits short of a 512 bits multiple. The remaining 64 bits are filled with the initial length of the +// message, represented as a 64-bits unsigned integer. +// For more details, see: https://datatracker.ietf.org/doc/html/rfc6234#section-4.1 +func pad(message []byte) []byte { + L := make([]byte, 8) + binary.BigEndian.PutUint64(L, uint64(len(message)*8)) + message = append(message, 0x80) // "1" bit followed by 7 "0" bits + for (len(message)+8)%64 != 0 { + message = append(message, 0x00) // 8 "0" bits + } + message = append(message, L...) + + return message +} + +// Hash hashes the input message using the sha256 hashing function, and return a 32 byte array. +// The implementation follows the RGC6234 standard, which is documented +// at https://datatracker.ietf.org/doc/html/rfc6234 +func Hash(message []byte) [32]byte { + message = pad(message) + + // Initialize round constants + h0, h1, h2, h3, h4, h5, h6, h7 := uint32(0x6a09e667), uint32(0xbb67ae85), uint32(0x3c6ef372), uint32(0xa54ff53a), + uint32(0x510e527f), uint32(0x9b05688c), uint32(0x1f83d9ab), uint32(0x5be0cd19) + + // Iterate through 512-bit chunks + for chunkStart := 0; chunkStart < len(message); chunkStart += chunkSize { + // Message schedule + var w [64]uint32 + for i := 0; i*4 < chunkSize; i++ { + w[i] = binary.BigEndian.Uint32(message[chunkStart+i*4 : chunkStart+(i+1)*4]) + } + + // Extend the 16 bytes chunk to the whole 64 bytes message schedule + for i := 16; i < 64; i++ { + s0 := bits.RotateLeft32(w[i-15], -7) ^ bits.RotateLeft32(w[i-15], -18) ^ (w[i-15] >> 3) + s1 := bits.RotateLeft32(w[i-2], -17) ^ bits.RotateLeft32(w[i-2], -19) ^ (w[i-2] >> 10) + w[i] = w[i-16] + s0 + w[i-7] + s1 + } + + // Actual hashing loop + a, b, c, d, e, f, g, h := h0, h1, h2, h3, h4, h5, h6, h7 + for i := 0; i < 64; i++ { + S1 := bits.RotateLeft32(e, -6) ^ bits.RotateLeft32(e, -11) ^ bits.RotateLeft32(e, -25) + ch := (e & f) ^ ((^e) & g) + tmp1 := h + S1 + ch + K[i] + w[i] + S0 := bits.RotateLeft32(a, -2) ^ bits.RotateLeft32(a, -13) ^ bits.RotateLeft32(a, -22) + maj := (a & b) ^ (a & c) ^ (b & c) + tmp2 := S0 + maj + h = g + g = f + f = e + e = d + tmp1 + d = c + c = b + b = a + a = tmp1 + tmp2 + } + h0 += a + h1 += b + h2 += c + h3 += d + h4 += e + h5 += f + h6 += g + h7 += h + } + + // Export digest + digest := [32]byte{} + binary.BigEndian.PutUint32(digest[:4], h0) + binary.BigEndian.PutUint32(digest[4:8], h1) + binary.BigEndian.PutUint32(digest[8:12], h2) + binary.BigEndian.PutUint32(digest[12:16], h3) + binary.BigEndian.PutUint32(digest[16:20], h4) + binary.BigEndian.PutUint32(digest[20:24], h5) + binary.BigEndian.PutUint32(digest[24:28], h6) + binary.BigEndian.PutUint32(digest[28:], h7) + + return digest +} From adc607e3569c9f9dd1fb3a45bf837938504a0140 Mon Sep 17 00:00:00 2001 From: kumaratul2002 <91847042+kumaratul2002@users.noreply.github.com> Date: Mon, 3 Oct 2022 06:37:28 +0530 Subject: [PATCH 267/278] quickSort_First_Pivot Quick sort algorithm using first element as pivot. --- quickSort_First_Pivot.cpp | 65 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 quickSort_First_Pivot.cpp diff --git a/quickSort_First_Pivot.cpp b/quickSort_First_Pivot.cpp new file mode 100644 index 0000000..7a1ea9e --- /dev/null +++ b/quickSort_First_Pivot.cpp @@ -0,0 +1,65 @@ +#include +using namespace std; + +void swap(int *a, int *b) +{ + int temp = *a; + *a = *b; + *b = temp; + return; +} +int partition(int arr[], int start, int end) +{ + int pivot = arr[start]; + int i = start; + int j = end; + while (i <= j) + { + + while (arr[i] <= pivot) + { + i++; + } + while (arr[j] > pivot) + { + j--; + } + if (i <= j) + swap(arr[i], arr[j]); + else + break; + } + swap(arr[start], arr[j]); + return j; +} +void quickSort(int arr[], int start, int end) +{ + if (start < end) + { + int part = partition(arr, start, end); + quickSort(arr, start, part - 1); + quickSort(arr, part + 1, end); + } +} + +int main() +{ + int size; + cout << "Enter size: "; + cin >> size; + int arr[size]; + cout << "Enter array: "; + for (int i = 0; i < size; i++) + { + cin >> arr[i]; + } + + quickSort(arr, 0, size); + + cout << "Sorted array is: "; + for (int i = 0; i < size; i++) + { + cout << arr[i] << " "; + } + cout << endl; +} \ No newline at end of file From b75305ae24e2d229c4057620f6a9fa4118a69d91 Mon Sep 17 00:00:00 2001 From: kumaratul2002 <91847042+kumaratul2002@users.noreply.github.com> Date: Mon, 3 Oct 2022 07:01:03 +0530 Subject: [PATCH 268/278] countingsort --- countingsort.cpp | 56 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 countingsort.cpp diff --git a/countingsort.cpp b/countingsort.cpp new file mode 100644 index 0000000..5ac531e --- /dev/null +++ b/countingsort.cpp @@ -0,0 +1,56 @@ +#include +using namespace std; +void countsort(int a[],int n) +{ + int b[n];int max=a[0],min=a[0]; + for(int i=0;ia[i]) + min=a[i]; + } + int range=max-min+1; + int f[range]; + for(int i=0;i=0;i--) + { + int pos=f[a[i]-min]-1; + b[pos]=a[i]; + f[a[i]-min]--; + } + for(int i=0;i>n; + int a[n]; + for(int i=0;i>a[i]; + } + countsort(a,n); + + return 0; +} \ No newline at end of file From 461eab369b3fd139b2debf0c9dbef626b6b3719a Mon Sep 17 00:00:00 2001 From: kumaratul2002 <91847042+kumaratul2002@users.noreply.github.com> Date: Mon, 3 Oct 2022 07:08:36 +0530 Subject: [PATCH 269/278] radixsort --- radixsort.cpp | 145 ++++++++++++++++++++++++-------------------------- 1 file changed, 70 insertions(+), 75 deletions(-) diff --git a/radixsort.cpp b/radixsort.cpp index 36b69a8..86383d2 100644 --- a/radixsort.cpp +++ b/radixsort.cpp @@ -1,75 +1,70 @@ -// C++ implementation of Radix Sort - -#include -using namespace std; - -// A utility function to get maximum value in arr[] -int getMax(int arr[], int n) -{ - int mx = arr[0]; - for (int i = 1; i < n; i++) - if (arr[i] > mx) - mx = arr[i]; - return mx; -} - -// A function to do counting sort of arr[] according to -// the digit represented by exp. -void countSort(int arr[], int n, int exp) -{ - int output[n]; // output array - int i, count[10] = { 0 }; - - // Store count of occurrences in count[] - for (i = 0; i < n; i++) - count[(arr[i] / exp) % 10]++; - - // Change count[i] so that count[i] now contains actual - // position of this digit in output[] - for (i = 1; i < 10; i++) - count[i] += count[i - 1]; - - // Build the output array - for (i = n - 1; i >= 0; i--) { - output[count[(arr[i] / exp) % 10] - 1] = arr[i]; - count[(arr[i] / exp) % 10]--; - } - - // Copy the output array to arr[], so that arr[] now - // contains sorted numbers according to current digit - for (i = 0; i < n; i++) - arr[i] = output[i]; -} - -// The main function to that sorts arr[] of size n using -// Radix Sort -void radixsort(int arr[], int n) -{ - // Find the maximum number to know number of digits - int m = getMax(arr, n); - - // 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 - for (int exp = 1; m / exp > 0; exp *= 10) - countSort(arr, n, exp); -} - -// A utility function to print an array -void print(int arr[], int n) -{ - for (int i = 0; i < n; i++) - cout << arr[i] << " "; -} - -// Driver Code -int main() -{ - int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; - int n = sizeof(arr) / sizeof(arr[0]); - - // Function Call - radixsort(arr, n); - print(arr, n); - return 0; -} +#include +using namespace std; +void countsort(int a[],int n,int exp) +{ + int b[n];int max=a[0],min=a[0]; + for(int i=0;ia[i]) + min=a[i]; + } + int range=10; + int f[range]; + for(int i=0;i<10;i++) + { + f[i]=0; + } + for(int i=0;i=0;i--) + { + int pos=f[a[i]/exp%10]-1; + b[pos]=a[i]; + f[a[i]/exp%10]--; + } + for(int i=0;imax) + max=a[i]; + } + int exp=1; + while(max>=exp) + { + countsort(a,n,exp); + exp=exp*10; + } +} +int main() +{ + int n; + cout<<"ENETR NUMBER OF VALUES : "; + cin>>n; + int a[n]; + for(int i=0;i>a[i]; + } + + radixsort(a,n); + for(int i=0;i Date: Mon, 3 Oct 2022 07:12:36 +0530 Subject: [PATCH 270/278] Update 4_Sum.cpp --- 4_Sum.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/4_Sum.cpp b/4_Sum.cpp index 792ffaa..ef2c579 100644 --- a/4_Sum.cpp +++ b/4_Sum.cpp @@ -37,8 +37,8 @@ class Solution { temp[0] = arr[left]; temp[1] = arr[right]; res.push_back(temp); - while(left < right && arr[left] == arr[left + 1])left++; - while(left < right && arr[right] == arr[right - 1])right--; + while(left < right && arr[left] == arr[left + 1]){left++;} + while(left < right && arr[right] == arr[right - 1]){right--;} left++; right--; } From 8683becf89081dddb9f64cea1685ef657d679ab9 Mon Sep 17 00:00:00 2001 From: Himanshu Mohanty <94133298+HimanshuMohanty-Git24@users.noreply.github.com> Date: Mon, 3 Oct 2022 08:20:40 +0530 Subject: [PATCH 271/278] Add files via upload Greatest Common Divisor of a number algorithm --- GCD_of_Number.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 GCD_of_Number.cpp diff --git a/GCD_of_Number.cpp b/GCD_of_Number.cpp new file mode 100644 index 0000000..1653781 --- /dev/null +++ b/GCD_of_Number.cpp @@ -0,0 +1,32 @@ +/****************************************************************************** + + Online C++ Compiler. + Code, Compile, Run and Debug C++ program online. +Write your code in this editor and press "Run" button to compile and execute it. + +*******************************************************************************/ + +#include + +using namespace std; + +int main() +{ + int m,n,i; + cout<<"Enter 2 number to find GCD:"; + cin>>m>>n; + while(m != n) + { + if(m>n) + { + m=m-n; + } + else + { + n=n-m; + } + } + cout< Date: Mon, 3 Oct 2022 08:28:35 +0530 Subject: [PATCH 272/278] Create invertBinaryTree.cpp --- CPP/invertBinaryTree.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 CPP/invertBinaryTree.cpp diff --git a/CPP/invertBinaryTree.cpp b/CPP/invertBinaryTree.cpp new file mode 100644 index 0000000..b5bd92d --- /dev/null +++ b/CPP/invertBinaryTree.cpp @@ -0,0 +1,28 @@ +/** +Input: root = [4,2,7,1,3,6,9] +Output: [4,7,2,9,6,3,1] + + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ + +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + if(!root) return NULL; + + TreeNode* rTree = invertTree(root->right); + TreeNode* lTree = invertTree(root->left); + + root->left = rTree; + root->right = lTree; + return root; + } +}; From 72454bdc00a476c7ea83bc3b604a186e80bdac77 Mon Sep 17 00:00:00 2001 From: Saurav Sutaria Date: Mon, 3 Oct 2022 09:03:32 +0530 Subject: [PATCH 273/278] added a program to find largest binary search tree --- CPP/largestBST.cpp | 65 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 CPP/largestBST.cpp diff --git a/CPP/largestBST.cpp b/CPP/largestBST.cpp new file mode 100644 index 0000000..c895ca9 --- /dev/null +++ b/CPP/largestBST.cpp @@ -0,0 +1,65 @@ +#include +#include +using namespace std; +struct node{ + int data; + node *left,*right; + node(int val){ + data = val; + left = NULL; + right = NULL; + + } +}; +struct info{ + int size; + int max; + int min; + int ans; + bool isBST; +}; +info largestBST(node* root){ + if(root == NULL){ + return {0,INT_MIN,INT_MAX,0,true}; //directly typecasting the value in structure info + } + if(root->left == NULL && root->right == NULL){ + return {1,root->data,root->data,1,true}; //for leaf node + } + + info leftInfo = largestBST(root->left); //calling for left subtree + info rightInfo = largestBST(root->right); //calling for right subtree + + info curr; + curr.size = (1+leftInfo.size+rightInfo.size); + //if left and right subtree are bst then only check for current node, otherwise it's meaningless + + if(leftInfo.isBST && rightInfo.isBST && leftInfo.max < root->data && rightInfo.min > root->data){ + curr.min = min(leftInfo.min,min(rightInfo.min,root->data)); + curr.max = max(rightInfo.max,max(leftInfo.max,root->data)); + curr.ans = curr.size; + curr.isBST = true; + return curr; + } + curr.ans = max(leftInfo.ans,rightInfo.ans); + curr.isBST = false; + return curr; + + +} + +int main(){ + /* + 5 + / \ + 3 6 + / \ + 2 4 + */ + node* root = new node(5); + root->left =new node(3); + //root->left->left =new node(2); + root->left->right =new node(4); + root->right = new node(6); + cout<<"largest bst size : "< Date: Mon, 3 Oct 2022 11:20:03 +0530 Subject: [PATCH 274/278] Shell Sort --- Java/MergeSortInPlace.java | 66 ++++++++++++++++++++++++++++++++++++++ Java/ShellSort.java | 42 ++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 Java/MergeSortInPlace.java create mode 100644 Java/ShellSort.java diff --git a/Java/MergeSortInPlace.java b/Java/MergeSortInPlace.java new file mode 100644 index 0000000..4b4833c --- /dev/null +++ b/Java/MergeSortInPlace.java @@ -0,0 +1,66 @@ + +import java.util.Arrays; + +public class MergeSortInPlace { + + public static void main(String[] args) { + + int[]arr={4,6,7,4,3,1,1}; + MergeSortInPla(arr,0,arr.length); + System.out.println(Arrays.toString(arr)); + } + + private static void MergeSortInPla(int[] arr, int s, int e) { + if (e-s==1) + return; + + int m=s+(e-s)/2; + MergeSortInPla(arr,s,m); + MergeSortInPla(arr,m,e); + + Merge(arr, s,m,e); + } + + private static void Merge(int[] arr, int s, int m, int e) { + + int [] ans=new int[e-s]; + int i=s; + int j=m; + int index=0; + + while (i0; gap/=2) + { + for (int i=gap; i=gap && arr[j-gap]>t ; j-=gap) + { + arr[j]=arr[j-gap]; + } + arr[j]=t; + } + } + } +} From e112e7cba00fe70371260dde80b2b4979f55f40b Mon Sep 17 00:00:00 2001 From: Sumit Kumar Jha <88476958+sumit-kumar-jha1709@users.noreply.github.com> Date: Mon, 3 Oct 2022 23:19:48 +0530 Subject: [PATCH 275/278] TripletSumUsingHashing --- Java/TripletSumProgramUsingHashing.java | 42 +++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Java/TripletSumProgramUsingHashing.java diff --git a/Java/TripletSumProgramUsingHashing.java b/Java/TripletSumProgramUsingHashing.java new file mode 100644 index 0000000..1c50c01 --- /dev/null +++ b/Java/TripletSumProgramUsingHashing.java @@ -0,0 +1,42 @@ +import java.util.*; + +class GFG { + + static boolean find3Numbers(int A[],int arr_size, int sum) + { + + for (int i = 0; i < arr_size - 2; i++) { + + // Find pair in subarray A[i+1..n-1] + // with sum equal to sum - A[i] + HashSet s = new HashSet(); + int curr_sum = sum - A[i]; + for (int j = i + 1; j < arr_size; j++) + { + if (s.contains(curr_sum - A[j])) + { + System.out.printf("Triplet is %d, + %d, %d", A[i], + A[j], curr_sum - A[j]); + return true; + } + s.add(A[j]); + } + } + + + return false; + } + + /* Driver code */ + public static void main(String[] args) + { + int A[] = { 1, 4, 45, 6, 10, 8 }; + int sum = 22; + int arr_size = A.length; + + find3Numbers(A, arr_size, sum); + } +} + + From 7ac2f697282205ac18650a5f1e39a697b441a218 Mon Sep 17 00:00:00 2001 From: Sumit Kumar Jha <88476958+sumit-kumar-jha1709@users.noreply.github.com> Date: Tue, 11 Oct 2022 16:01:41 +0530 Subject: [PATCH 276/278] RadixSort --- CPP/RadixSort | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 CPP/RadixSort diff --git a/CPP/RadixSort b/CPP/RadixSort new file mode 100644 index 0000000..36b69a8 --- /dev/null +++ b/CPP/RadixSort @@ -0,0 +1,75 @@ +// C++ implementation of Radix Sort + +#include +using namespace std; + +// A utility function to get maximum value in arr[] +int getMax(int arr[], int n) +{ + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; +} + +// A function to do counting sort of arr[] according to +// the digit represented by exp. +void countSort(int arr[], int n, int exp) +{ + int output[n]; // output array + int i, count[10] = { 0 }; + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains actual + // position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current digit + for (i = 0; i < n; i++) + arr[i] = output[i]; +} + +// The main function to that sorts arr[] of size n using +// Radix Sort +void radixsort(int arr[], int n) +{ + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // 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 + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); +} + +// A utility function to print an array +void print(int arr[], int n) +{ + for (int i = 0; i < n; i++) + cout << arr[i] << " "; +} + +// Driver Code +int main() +{ + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = sizeof(arr) / sizeof(arr[0]); + + // Function Call + radixsort(arr, n); + print(arr, n); + return 0; +} From ad8c7a1996a93ef4df53855af655bd9824448568 Mon Sep 17 00:00:00 2001 From: Sumit Kumar Jha <88476958+sumit-kumar-jha1709@users.noreply.github.com> Date: Tue, 11 Oct 2022 16:02:31 +0530 Subject: [PATCH 277/278] Delete RadixSort --- CPP/RadixSort | 75 --------------------------------------------------- 1 file changed, 75 deletions(-) delete mode 100644 CPP/RadixSort diff --git a/CPP/RadixSort b/CPP/RadixSort deleted file mode 100644 index 36b69a8..0000000 --- a/CPP/RadixSort +++ /dev/null @@ -1,75 +0,0 @@ -// C++ implementation of Radix Sort - -#include -using namespace std; - -// A utility function to get maximum value in arr[] -int getMax(int arr[], int n) -{ - int mx = arr[0]; - for (int i = 1; i < n; i++) - if (arr[i] > mx) - mx = arr[i]; - return mx; -} - -// A function to do counting sort of arr[] according to -// the digit represented by exp. -void countSort(int arr[], int n, int exp) -{ - int output[n]; // output array - int i, count[10] = { 0 }; - - // Store count of occurrences in count[] - for (i = 0; i < n; i++) - count[(arr[i] / exp) % 10]++; - - // Change count[i] so that count[i] now contains actual - // position of this digit in output[] - for (i = 1; i < 10; i++) - count[i] += count[i - 1]; - - // Build the output array - for (i = n - 1; i >= 0; i--) { - output[count[(arr[i] / exp) % 10] - 1] = arr[i]; - count[(arr[i] / exp) % 10]--; - } - - // Copy the output array to arr[], so that arr[] now - // contains sorted numbers according to current digit - for (i = 0; i < n; i++) - arr[i] = output[i]; -} - -// The main function to that sorts arr[] of size n using -// Radix Sort -void radixsort(int arr[], int n) -{ - // Find the maximum number to know number of digits - int m = getMax(arr, n); - - // 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 - for (int exp = 1; m / exp > 0; exp *= 10) - countSort(arr, n, exp); -} - -// A utility function to print an array -void print(int arr[], int n) -{ - for (int i = 0; i < n; i++) - cout << arr[i] << " "; -} - -// Driver Code -int main() -{ - int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; - int n = sizeof(arr) / sizeof(arr[0]); - - // Function Call - radixsort(arr, n); - print(arr, n); - return 0; -} From 69ecf72b958d169c590327e3b9fba51523b7f3a1 Mon Sep 17 00:00:00 2001 From: Sumit Kumar Jha <88476958+sumit-kumar-jha1709@users.noreply.github.com> Date: Tue, 11 Oct 2022 03:33:18 -0700 Subject: [PATCH 278/278] radixSort --- CPP/radixSort.cpp | 75 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 CPP/radixSort.cpp diff --git a/CPP/radixSort.cpp b/CPP/radixSort.cpp new file mode 100644 index 0000000..432ae3b --- /dev/null +++ b/CPP/radixSort.cpp @@ -0,0 +1,75 @@ +// C++ implementation of Radix Sort + +#include +using namespace std; + +// A utility function to get maximum value in arr[] +int getMax(int arr[], int n) +{ + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; +} + +// A function to do counting sort of arr[] according to +// the digit represented by exp. +void countSort(int arr[], int n, int exp) +{ + int output[n]; // output array + int i, count[10] = { 0 }; + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains actual + // position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current digit + for (i = 0; i < n; i++) + arr[i] = output[i]; +} + +// The main function to that sorts arr[] of size n using +// Radix Sort +void radixsort(int arr[], int n) +{ + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // 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 + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); +} + +// A utility function to print an array +void print(int arr[], int n) +{ + for (int i = 0; i < n; i++) + cout << arr[i] << " "; +} + +// Driver Code +int main() +{ + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = sizeof(arr) / sizeof(arr[0]); + + // Function Call + radixsort(arr, n); + print(arr, n); + return 0; +}