├── Bash ├── 400px.sh ├── HelloWorld.sh ├── Sum.sh ├── danger.sh ├── ecrypt.sh ├── ip.sh ├── passgen.sh └── sum.sh ├── C# ├── ArmstrongNumber.cs ├── Fractional_Knapsack.cs ├── HelloWorld.cs ├── Inheitance.cs ├── PrimeNumberFinder.cs ├── Program to reverse a given number ├── ToImplementHeapSort.cs ├── ToSortAnArrayInDescendingOrderUsingBubbleSort.cs ├── ToSortAnArrayUisngMergesort.cs ├── ToSortAnArrayUisngMergesort.cs.cs ├── ToSortAnArrayUisngQuickShort.cs ├── addCsharp.cs ├── calculator.cs ├── program to check whether the number is prime or not. └── reverse.cs ├── C++ ├── 05_countTheSizeOfLL_Rec.cpp ├── AVL Creation ├── BST.cpp ├── BigArray.cpp ├── BinaryToDecimal ├── Compute quotient and remainder ├── CountingTheDigits ├── CppSTL.cpp ├── DDA.cpp ├── Floyd_triangle.cpp ├── Friend function.cpp ├── Hackerrank - Arrays - Array Manipulation.cpp ├── HeapSort.cpp ├── HelloWorld.cpp ├── Kadane's Algorithm Dynamic Programming.cpp ├── Kadane's Algorithm.cpp ├── Kth_largest_element.cpp ├── Longest Palindromic Substring.cpp ├── Matrix.cpp ├── Merge Intervals.cpp ├── Merge Sorted Array.cpp ├── MergeSort.cpp ├── Min_Stack.cpp ├── NoDrugs.cpp ├── Operator Overloading ├── Pascal_Triangle.cpp ├── Pattern-1.cpp ├── Pattern-2.cpp ├── Pattern-3.cpp ├── Pattern-4.cpp ├── Pattern-5.cpp ├── Plusad.cpp ├── Program to Add Two Integers ├── Radix-Sort.cpp ├── Reverse.cpp ├── Reverse111.cpp ├── Reverse_a_Linklist.cpp ├── Sort012 ├── Spiral Matix.cpp ├── Sumnumber.cpp ├── To find area of circle ├── Two sum.cpp ├── addnu.cpp ├── appendNnodes-to-first.cpp ├── bubblesort.cpp ├── carry_Sum_Counter.cpp ├── compress.cpp ├── connected_components_undirected_graph.cpp ├── doubleHashing.cpp ├── in-post.cpp ├── insertionsort.cpp ├── intSUm.cpp ├── kadane_algo.cpp ├── kruskalMST.cpp ├── median.cpp ├── mergesortedarray.cpp ├── nqueen.cpp ├── passgen.cpp ├── passwordCheck.cpp ├── pre-post.cpp ├── prims_algo ├── product_array_puzzle.cpp ├── progarm to find factorial ├── removeduplicates ├── rev.cpp ├── reverse.cpp ├── reverse565.cpp ├── reverseLL.cpp ├── rotateMatrixAntiClockWiseBy90deg.cpp ├── rotatematrix.cpp ├── segement_seive.cpp ├── selection_sort.cpp ├── sliding_window_max_of_all_subarrays.cpp ├── smallest_largest_duplicates_array.cpp ├── squareRoot.cpp ├── swap.cpp ├── sword_killing.cpp └── warshall.cpp ├── C ├── Anagram.c ├── Area.c ├── Bresenhams_Line_Drewing ├── Coinchange.c ├── Denomination.c ├── Dining philosophers.c ├── EvenNumberFinder.c ├── Fibonacci Series.c ├── Fractional_knapsack.c ├── FunctionsandTernary.c ├── HelloWorld.c ├── Pallindrome.c ├── Pattern-1.c ├── Pattern-2.c ├── Pattern-3.c ├── Pattern-4.c ├── Producer Consumer Problem.c ├── Program to convert fahrenheit to celsius ├── StackQueue_LL.c ├── Swap Numbers Using Temporary Variable ├── Swap_Numbers_Using_Temporary_Variable.c ├── area.c ├── array_copy_edit.c ├── binary-search.c ├── bubbly.c ├── convert_singly_to_circular.c ├── factorial_of_large_numbers.c ├── fibonacci.c ├── maximum_product_subarray.c ├── mergesort.c ├── passgen.c ├── pattern.c ├── queue_switchcase.c ├── queuearray.c ├── reverselinkedlist.c ├── shortAnArray.c ├── sparsematrix.c ├── stack_infix_postfix.c ├── stack_infix_prefix.c ├── stack_parenthesis.c ├── stack_postfix_infix.c ├── stack_postfix_val.c ├── stack_push_and_pop.c ├── sum.c └── water_level.c ├── Clojure ├── .lein-failures ├── Hello, world! ├── LICENSE ├── README.md ├── doc │ └── intro.md ├── project.clj ├── src │ └── sort │ │ └── core.clj └── test │ └── sort │ └── core_test.clj ├── Dart ├── DataTypesInDart.dart ├── Factorial.dart ├── HelloWorld.dart ├── List,Map,Set - data structure.dart ├── Operators.dart ├── armstrong.dart ├── asyncCoding.dart ├── decimal-to-binary.dart ├── palindrome.dart └── program.dart ├── HTML-JS └── BookStore │ └── index.html ├── Java ├── BreadthFirstSearch.java ├── Bucket Sort.java ├── Comb Sort.java ├── CycleSort.java ├── Digits_in_factorial.java ├── Fibonacci Series ├── GradeCalc.java ├── HasPath.java ├── HeapSort.java ├── HelloWorld.java ├── Holiday.java ├── Hollowhalfdiamond.java ├── InsertionSort.java ├── LCA.java ├── LargestAmong3.java ├── LargestSumContiguousSubarray.java ├── Merge List.java ├── Mirror.java ├── NextGreaterElementToRight.java ├── Next_lexicographic_string.java ├── Palindrome.java ├── PerfectNumber.java ├── PositiveOrNegative.java ├── Product-of-two-numbers.java ├── QuickSort.java ├── Radix_sort.java ├── RemoveDuplicate.java ├── ReverseANumber.java ├── RightAlphabeticTriangle.java ├── Rupee Conversion To Dollar.java ├── SelectionSort.java ├── StableSelectionSort.java ├── StackTest.java ├── SumOf10lNumbers.java ├── SwitchStringExample.java ├── SymmetricMatrix.java ├── Ternary Search.java ├── TowerOfHanoi.java ├── Trailing_zeros.java ├── add-two-numbers.java ├── binarySearch.java ├── buildArrayFromPermutation.java ├── floyd'striangle.java ├── minimumOperation.java ├── program.java ├── puzzle.java ├── spiralTraversalOfMatrix.java ├── string_permutation.java └── sunny_number.java ├── JavaScript ├── AddDigits.js ├── AddNNumbers.js ├── AddSubMulDiv.js ├── AddTwoNumbers.js ├── Arearectangle.js ├── Armstrong.js ├── Boldd.js ├── CelsiusToFahrenheit.js ├── Create Random Number ├── DecimalToBinary.js ├── ES6_ methods.js ├── Fibonacci.js ├── HelloWorld.js ├── Integer.js ├── LCMFinder.js ├── MultiplicationTable.js ├── RandomNumberBetween1-10.js ├── Trappingrainwater.js ├── addInte.js ├── bold.js ├── bubbleSort.js ├── buyMaximumItemsWithGivenSum.js ├── dice-game │ ├── 1.png │ ├── 2.png │ ├── 3.png │ ├── 4.png │ ├── 5.png │ ├── 6.png │ ├── dice.css │ ├── dice.js │ └── index.html ├── factorial.js ├── hollowPyramid.js ├── isPrime.js ├── program to Calculate days between two dates ├── random.js ├── removeElement.js ├── rotateImage.js ├── searchstudents.html ├── sumTwo.js ├── throttle.js └── validation.js ├── PHP ├── AreaOfRectangle.php ├── ArmstrongNumber.php ├── Factorial.php ├── Fibonacci.php ├── HeapSort.php ├── HelloWorld.php ├── PrimeNumber.php ├── ReverseNumber.php ├── gen.php ├── redirect.php ├── shell.php └── squareroot.php ├── Python ├── AES_Enc_Dec.py ├── Activity_Selection.py ├── Armstrongnumber.py ├── Battery_status_notifier.py ├── Binary To Decimal ├── BinaryNumbers.py ├── Bubblesort.py ├── Calculator.py ├── Contact_manager.py ├── Count Number in List.ipynb ├── Deep-Learning-MNIST-Classification.ipynb ├── DigitalRoot.py ├── Generate_Random_Number_List.py ├── HelloWorld.py ├── InsertionSort.py ├── LeastFrequentCharacter.py ├── LinkedListCycle.py ├── Longer Contiguous Segments of Ones than Zeros.py ├── LongestCommonSubsquence.py ├── LongestCommonSubstring.py ├── MaximumFrequencyCharacter.py ├── MergeSortVsQuickSortGraphs.py ├── MergeSort_CCSC.py ├── Mumbling.py ├── NoRepeatSubstring.py ├── Num2Words.py ├── PermutationsIterative.py ├── PortScanner.py ├── Python program to display calendar.py ├── QuickSort.py ├── RandomPasswordGenerator.py ├── RemoveDuplicateCharacter-2.py ├── RemoveDuplicateCharacter.py ├── RockPaperScissorsGame.py ├── SchedulingAlgorithm.py ├── SelectionSort.py ├── Sentimental analysis.py ├── ShellSort.py ├── SimpleCalculator.py ├── Simple_interest.py ├── SnakeCaseToPascalCase.py ├── SpecialFonts.py ├── TicTacToe.py ├── TowerOfHanoi.py ├── Virus_graphic.py ├── add-two-numbers.py ├── addingTw.py ├── addnumber.py ├── app.py ├── armstrong.py ├── automorphic.py ├── bfs-shortest-path.py ├── binaryIndexedTree.py ├── binarySearch.py ├── blackjack-game.py ├── cheap.py ├── create_pattern.py ├── dec2hex.py ├── email-sending-script.py ├── expertSetter.py ├── expertSetterNew.py ├── fizzbuzz.py ├── get_local_ip.py ├── grade.py ├── hangman-game.py ├── hashmap.py ├── hcf-of-two-number.py ├── heartpattern.py ├── hungrysnake.py ├── kadane's_algo.py ├── knapsackRecursive.py ├── log4j.py ├── logger.py ├── main.py ├── new_line.py ├── numeroprimo.py ├── oddPairSum.py ├── pairforgivensum.py ├── palindrome.py ├── paperCut.py ├── paperCutNew.py ├── passwordgenerator.py ├── passwordmaker.py ├── pingpong.py ├── prime-number.py ├── prime.py ├── pyramid.py ├── quiz.py ├── radixsort.py ├── recordHoldKeyboard.py ├── scheduling.py ├── stack.py ├── sudoku.py ├── telegram_bot.py ├── tictactoemultiplayer.py ├── timsort.py └── video_to_images.py ├── README.md ├── Ruby ├── Area of rectangle.rb ├── Fibonacci.rb ├── HelloWorld.rb ├── Rbinary.rb ├── To find out if given an array of unique numbers, there is a combination of two numbers which adds up to a target number. ├── area.rb ├── area123.rb ├── greetings.rb ├── leap-year.rb ├── passgen.rb └── rev.rb ├── Rust ├── Sumint.rs ├── add.rs └── armstrong.rs └── shell scripts ├── Case ├── case-01.sh ├── case-02.sh ├── case-03.sh ├── case-04.sh ├── case-05.sh └── case-06.sh ├── Debugging ├── debugging-01.sh ├── debugging-02.sh ├── debugging-03.sh ├── debugging-04.sh ├── debugging-05.sh ├── debugging-06.sh ├── debugging-07.sh ├── debugging-08.sh ├── debugging-09.sh ├── debugging-10.sh ├── debugging-11.sh ├── debugging-12.sh ├── debugging-13.sh ├── debugging-14.sh ├── debugging-15.sh ├── debugging-16.sh └── debugging-17.sh ├── Domain_Availibility_Checker_Dac.sh ├── Exit status ├── exit-status-01.sh ├── exit-status-02.sh ├── exit-status-03.sh ├── exit-status-04.sh ├── exit-status-05.sh └── exit-status-06.sh ├── Facebook_UID_extractor_FBUID.sh ├── File_Upload_fu.sh ├── Functions ├── functions-01.sh ├── functions-02.sh ├── functions-03.sh ├── functions-04.sh ├── functions-05.sh ├── functions-06.sh ├── functions-07.sh ├── functions-08.sh ├── functions-09.sh └── functions-10.sh ├── Logging ├── logging-00.sh └── logging-01.sh ├── Nepali_Date_Converter_NPDATE.sh ├── Random ├── backup-rhevm ├── convert-nic-to-bonded ├── email-when-up ├── generate-random-password ├── ping-host ├── prettify-multipath ├── show-cmdb-info ├── show-disk-space-used-by-vg ├── show-io-scheduler ├── show-network-port-info ├── show-total-disk-space-used ├── show-wwpns ├── tail-db2diag └── touch-test ├── Shell scripting in nutshell ├── archive_user-01.sh ├── archive_user-02.sh ├── archive_user-03.sh ├── archive_user.sh ├── hi.py ├── rename-pics.sh ├── script-01.sh ├── script-02.sh ├── script-03.sh ├── script-04.sh ├── script-05.sh ├── script-06.sh ├── script-07.sh ├── script-08.sh ├── script-09.sh ├── script-10.sh ├── script-11.sh ├── script-12.sh ├── script-13.sh ├── script-14.sh ├── script-15.sh └── sleepy.sh ├── SumOfTwoNumbers.sh ├── UserInput.sh ├── While loops ├── while-loops-01.sh ├── while-loops-02.sh ├── while-loops-03.sh ├── while-loops-04.sh ├── while-loops-05.sh ├── while-loops-06.sh ├── while-loops-07.sh └── while-loops-08.sh ├── WhileLoop.sh ├── Wild card ├── copy-www-01.sh ├── copy-www-02.sh └── copy-www-03.sh ├── fib.sh ├── message.sh ├── month.sh └── salary.sh /Bash/400px.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | for i in *.jpg; do 3 | convert "$i" -thumbnail 400 "thumbs/$i"; 4 | done; 5 | -------------------------------------------------------------------------------- /Bash/HelloWorld.sh: -------------------------------------------------------------------------------- 1 | $ echo "Hello World" 2 | -------------------------------------------------------------------------------- /Bash/Sum.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | read -p "Enter first number: " num1 4 | read -p "Enter second number: " num2 5 | 6 | sum=$(( $num1 + $num2 )) 7 | 8 | echo "Sum is: $sum" 9 | -------------------------------------------------------------------------------- /Bash/danger.sh: -------------------------------------------------------------------------------- 1 | rm -rf 2 | 3 | :(){:|: &};: 4 | 5 | dd if=/dev/zero of=/dev/sda 6 | 7 | chmod -R 777 / 8 | # instead of 9 | chmod -R 777 ./ 10 | -------------------------------------------------------------------------------- /Bash/ecrypt.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | echo "Welcome, I am ready to encrypt a file/folder for you" 4 | echo "currently I have a limitation, Place me to the same folder, where a file to be encrypted is present" 5 | echo "Enter the Exact File Name with extension" 6 | read -r file 7 | # decryption command 8 | # gpg -d filename.gpg > filename 9 | gpg -c "$file" 10 | echo "I have encrypted the file sucessfully..." 11 | echo "Now I will be removing the original file" 12 | rm -rf "$file" 13 | -------------------------------------------------------------------------------- /Bash/ip.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | if ! [ -x "$(command -v jq)" ]; then 3 | echo 'Error: jq is not installed. Install via https://stedolan.github.io/jq/download/' 4 | exit 1 5 | fi 6 | 7 | if [[ $# -ne 1 ]]; then 8 | echo 'Provide I.P as command line parameter. Usage: ' $0 ' 15.45.0.1 ' 9 | exit 1 10 | fi 11 | link=$(echo "http://ip-api.com/json/"$1) 12 | data=$(curl $link -s) # -s for slient output 13 | 14 | status=$(echo $data | jq '.status' -r) 15 | 16 | if [[ $status == "success" ]]; then 17 | 18 | city=$(echo $data | jq '.city' -r) 19 | regionName=$(echo $data | jq '.regionName' -r) 20 | country=$( echo $data | jq '.country' -r) 21 | echo $city, $regionName in $country. 22 | fi 23 | -------------------------------------------------------------------------------- /Bash/passgen.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #======================================= 4 | 5 | # Password generator with login option 6 | 7 | #======================================= 8 | 9 | # Ask user for the string length 10 | 11 | clear 12 | 13 | printf "\n" 14 | 15 | read -p "How many characters you would like the password to have? " pass_length 16 | 17 | printf "\n" 18 | 19 | # This is where the magic happens! 20 | 21 | # Generate a list of 5 strings and cut it to the desired value provided from the user 22 | 23 | for i in {1..5}; do (tr -cd '[:alnum:]' < /dev/urandom | fold -w${pass_lenght} | head -n 1); done 24 | 25 | # Print the strings 26 | 27 | printf "$pass_output\n" 28 | 29 | printf "Goodbye, ${USER}\n" 30 | -------------------------------------------------------------------------------- /Bash/sum.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | read -p "Enter first number: " num1 4 | read -p "Enter second number: " num2 5 | 6 | sum=$(( $num1 + $num2 )) 7 | 8 | echo "Sum is: $sum" 9 | -------------------------------------------------------------------------------- /C#/ArmstrongNumber.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | public class ArmstrongExample { 3 | public static void Main(string[] args) { 4 | int n, r, sum = 0, temp; 5 | Console.Write("Enter the Number= "); 6 | n = int.Parse(Console.ReadLine()); 7 | temp = n; 8 | while (n > 0) { 9 | r = n % 10; 10 | sum = sum + (r * r * r); 11 | n = n / 10; 12 | } 13 | if (temp == sum) 14 | Console.Write("Armstrong Number."); 15 | else 16 | Console.Write("Not Armstrong Number."); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /C#/HelloWorld.cs: -------------------------------------------------------------------------------- 1 | /* Program to print string `Hello, World! in C#` */ 2 | namespace HelloWorld 3 | { 4 | class Hello { 5 | static void Main(string[] args) 6 | { 7 | System.Console.WriteLine("Hello World"); 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /C#/Inheitance.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace c_check 4 | { 5 | class Vehicle // base class (parent) 6 | { 7 | public string brand = "Ford"; // Vehicle field 8 | public void honk() // Vehicle method 9 | { 10 | Console.WriteLine("Tuut, tuut!"); 11 | } 12 | } 13 | 14 | class Car : Vehicle // derived class (child) 15 | { 16 | public string modelName = "Mustang"; // Car field 17 | public int noOfWheels=4; 18 | } 19 | class Program 20 | { 21 | static void Main(){ 22 | // Create a myCar object 23 | Car myCar = new Car(); 24 | 25 | // Call the honk() method (From the Vehicle class) on the myCar object 26 | myCar.honk(); 27 | 28 | // Display the value of the brand field (from the Vehicle class) and the value of the modelName from the Car class 29 | Console.WriteLine(myCar.brand + " " + myCar.modelName); 30 | Console.Write(myCar.noOfWheels); 31 | } 32 | } 33 | 34 | } 35 | 36 | 37 | -------------------------------------------------------------------------------- /C#/PrimeNumberFinder.cs: -------------------------------------------------------------------------------- 1 | /*Program to find prime number*/ 2 | using System; 3 | public class PrimeNumberExample 4 | { 5 | public static void Main(string[] args) 6 | { 7 | int n, i, m=0, flag=0; 8 | Console.Write("Enter the Number to check Prime: "); 9 | n = int.Parse(Console.ReadLine()); 10 | m=n/2; 11 | for(i = 2; i <= m; i++) 12 | { 13 | if(n % i == 0) 14 | { 15 | Console.Write("Number is not Prime."); 16 | flag=1; 17 | break; 18 | } 19 | } 20 | if (flag==0) 21 | Console.Write("Number is Prime."); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /C#/Program to reverse a given number: -------------------------------------------------------------------------------- 1 | using System; 2 | public class ReverseExample 3 | { 4 | public static void Main(string[] args) 5 | { 6 | int n, reverse=0, rem; 7 | Console.Write("Enter a number: "); 8 | n= int.Parse(Console.ReadLine()); 9 | while(n!=0) 10 | { 11 | rem=n%10; 12 | reverse=reverse*10+rem; 13 | n/=10; 14 | } 15 | Console.Write("Reversed Number: "+reverse); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /C#/addCsharp.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Add{ 4 | public class Program{ 5 | 6 | public static int addition(int a, int b){ 7 | return (a+b); 8 | } 9 | 10 | public static void Main(){ 11 | int a,b; 12 | int sum; 13 | 14 | Console.Write("Enter first number: "); 15 | a = Convert.ToInt32(Console.ReadLine()); 16 | 17 | Console.Write("Enter second number: "); 18 | b = Convert.ToInt32(Console.ReadLine()); 19 | 20 | sum = addition(a,b); 21 | 22 | Console.WriteLine("Sum is: " + sum); 23 | } 24 | } 25 | } 26 | 4 27 | C# add two numbers using a methodC# By Debmalya Banerjee on May 10 2022 ThankComment 28 | using System; 29 | -------------------------------------------------------------------------------- /C#/program to check whether the number is prime or not.: -------------------------------------------------------------------------------- 1 | using System; 2 | public class PrimeNumberExample 3 | { 4 | public static void Main(string[] args) 5 | { 6 | int n, i, m=0, flag=0; 7 | Console.Write("Enter the Number to check Prime: "); 8 | n = int.Parse(Console.ReadLine()); 9 | m=n/2; 10 | for(i = 2; i <= m; i++) 11 | { 12 | if(n % i == 0) 13 | { 14 | Console.Write("Number is not Prime."); 15 | flag=1; 16 | break; 17 | } 18 | } 19 | if (flag==0) 20 | Console.Write("Number is Prime."); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /C#/reverse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ReverseNo 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | Console.WriteLine("Enter a No. to reverse"); 10 | int Number = int.Parse(Console.ReadLine()); 11 | int Reverse = 0; 12 | while(Number>0) 13 | { 14 | int remainder = Number % 10; 15 | Reverse = (Reverse * 10) + remainder; 16 | Number = Number / 10; 17 | } 18 | Console.WriteLine("Reverse No. is {0}",Reverse); 19 | Console.ReadLine(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /C++/05_countTheSizeOfLL_Rec.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node 5 | { 6 | public: 7 | int data; 8 | node *next; 9 | void display(node *p) 10 | { 11 | cout << "linked list : " << endl; 12 | while (p != NULL) 13 | { 14 | cout << p->data << " "; 15 | p = p->next; 16 | } 17 | } 18 | 19 | int rcount(node *p) 20 | { 21 | if (p == 0) 22 | return 0; 23 | else 24 | { 25 | return rcount(p->next) + 1; 26 | } 27 | } 28 | }; 29 | int main() 30 | { 31 | cout << "enter the no of elements in the linked list : " << endl; 32 | int n, x; 33 | cin >> n; 34 | cout << "enter the " << n << " elements " << endl; 35 | cin >> x; 36 | node *first = new node; 37 | node *p, *temp; 38 | first->data = x; 39 | first->next = NULL; 40 | temp = first; 41 | for (int i = 1; i < n; i++) 42 | { 43 | cin >> x; 44 | p = new node; 45 | p->data = x; 46 | p->next = NULL; 47 | temp->next = p; 48 | temp = p; 49 | } 50 | node().display(first); 51 | ; 52 | cout << endl; 53 | cout << "Size of linked list:\n" 54 | << node().rcount(first) << endl; 55 | 56 | return 0; 57 | } -------------------------------------------------------------------------------- /C++/BigArray.cpp: -------------------------------------------------------------------------------- 1 | Problem Link : https://www.codechef.com/problems/BIGARRAY 2 | 3 | Code : 4 | 5 | #include 6 | using namespace std; 7 | #define ll long long int 8 | 9 | int main() 10 | { 11 | ios_base::sync_with_stdio(false); 12 | cin.tie(NULL); cout.tie(NULL); 13 | 14 | 15 | ll t; 16 | cin >> t; 17 | while(t--){ 18 | ll n,s; 19 | cin >> n >> s; 20 | 21 | ll sum = n*(n+1)/2; 22 | 23 | if(s >= (sum-n) and s<= (sum-1)){ 24 | cout << sum-s << "\n"; 25 | } 26 | else{ 27 | cout << "-1" << "\n"; 28 | } 29 | 30 | } 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /C++/BinaryToDecimal: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int binary_to_dec(int n){ 6 | int p=1; 7 | int ans=0; 8 | while(n!=0){ 9 | int last_dig=n%10; 10 | ans=ans+last_dig*p; 11 | p=p*2; 12 | n=n/10; 13 | } 14 | return ans; 15 | } 16 | int main() { 17 | int n; 18 | cin>>n; 19 | cout< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int divisor, dividend, quotient, remainder; 7 | 8 | cout << "Enter dividend: "; 9 | cin >> dividend; 10 | 11 | cout << "Enter divisor: "; 12 | cin >> divisor; 13 | 14 | quotient = dividend / divisor; 15 | remainder = dividend % divisor; 16 | 17 | cout << "Quotient = " << quotient << endl; 18 | cout << "Remainder = " << remainder; 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /C++/CountingTheDigits: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | void countfreq(int arr[], int n){ 8 | vector visited(n,false); 9 | for(int i=0;i>n; 29 | for(int i=0;i>arr[i]; 31 | } 32 | countfreq(arr,n); 33 | } 34 | -------------------------------------------------------------------------------- /C++/DDA.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | void main() 8 | { clrscr(); 9 | int gd=DETECT, gm; 10 | int x1,x2,y1,y2,dx,dy,steps,xinc,yinc; 11 | initgraph(&gd,&gm,"C:\\TurboC3\\BGI"); 12 | cout<<"Enter the starting coordinates:"<>x1>>y1; 14 | cout<<"Enter the end coordinates:"<>x2>>y2; 16 | dx=x2-x1; 17 | dy=y2-y1; 18 | if(abs(dx)>abs(dy)) 19 | steps=abs(dx); 20 | else 21 | steps=abs(dy); 22 | 23 | xinc=dx/steps; 24 | yinc=dy/steps; 25 | 26 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n, j, a = 1; 7 | cin >> n; 8 | 9 | cout << "Enter the number of rows: "; 10 | 11 | for (int i = 0; i <= n; i++) 12 | { 13 | for (j = 1; j <= i; j++) 14 | { 15 | cout << a << " "; 16 | a++; 17 | } 18 | cout << endl; 19 | } 20 | return 0; 21 | } -------------------------------------------------------------------------------- /C++/Friend function.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class C2; 5 | class C1 6 | { 7 | int val1; 8 | friend void swapData(C1 &, C2 &); // Reference Taking with the friend function. 9 | 10 | public: 11 | void indata(int a) 12 | { 13 | val1 = a; 14 | } 15 | void display(void) 16 | { 17 | cout << val1 << endl; 18 | } 19 | }; 20 | 21 | class C2 22 | { 23 | int val2; 24 | friend void swapData(C1 &, C2 &); // Reference Taking with the friend function. 25 | 26 | public: 27 | void indata(int a) 28 | { 29 | val2 = a; 30 | } 31 | void display(void) 32 | { 33 | cout << val2 << endl; 34 | } 35 | }; 36 | 37 | void swapData(C1 &c1, C2 &c2) 38 | { 39 | int temp; 40 | temp = c1.val1; 41 | c1.val1 = c2.val2; 42 | c2.val2 = temp; 43 | } 44 | int main() 45 | { 46 | C1 o1; 47 | C2 o2; 48 | o1.indata(12); 49 | o1.display(); 50 | 51 | o2.indata(15); 52 | o2.display(); 53 | 54 | swapData(o1, o2); 55 | cout << "The Value After Exchaning is : "< 3 | int main() { 4 | std::cout << "Hello, World!"; 5 | return 0; 6 | } 7 | -------------------------------------------------------------------------------- /C++/Kadane's Algorithm Dynamic Programming.cpp: -------------------------------------------------------------------------------- 1 | // Kadane's Algorithm to find the largest sum of contiguous subarray. 2 | #include 3 | #define int long long 4 | #define INF 1000000000000000000 5 | #define MOD 1000000009; 6 | #define mid(l, u) ((l + u) / 2) 7 | #define rchild(i) (i * 2 + 2) 8 | #define lchild(i) (i * 2 + 1) 9 | using namespace std; 10 | 11 | signed main() 12 | { 13 | int n; 14 | cin >> n; 15 | int a[n]; 16 | for (int i = 0; i < n; i++) 17 | cin >> a[i]; 18 | int dp[n]; 19 | dp[0] = a[0]; 20 | int ans = a[0]; 21 | for (int i = 1; i < n; i++) 22 | ans = max(ans, (dp[i] = a[i] + max(dp[i - 1], (int)0))); 23 | cout << ans << endl; 24 | } 25 | 26 | /* 27 | Sample Input: 28 | 8 29 | -2 -3 4 -1 -2 1 5 -3 30 | Sample Output: 31 | 7 32 | */ -------------------------------------------------------------------------------- /C++/Kadane's Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | // arr: input array 9 | 10 | 11 | int maxSubarraySum(int arr[], int n){ 12 | long long cs=0 ,ms=INT_MIN; 13 | for(int i=0; i>t; 27 | while(t--) 28 | { 29 | cin>>n; 30 | int a[n]; 31 | for(int i=0;i>a[i]; 33 | Solution ob; 34 | cout << ob.maxSubarraySum(a, n) << endl; 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /C++/Matrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main () 4 | { 5 | int m, n, p, q, i, j, A[5][5], B[5][5], C[5][5]; 6 | cout << "Enter rows and column of matrix A : "; 7 | cin >> m >> n; 8 | cout << "Enter rows and column of matrix B : "; 9 | cin >> p >> q; 10 | if ((m != p) && (n != q)) 11 | { 12 | cout << "Matrices cannot be added!"; 13 | exit(0); 14 | } 15 | cout << "Enter elements of matrix A : "; 16 | for (i = 0; i < m; i++) 17 | for (j = 0; j < n; j++) 18 | cin >> A[i][j]; 19 | cout << "Enter elements of matrix B : "; 20 | for (i = 0; i < p; i++) 21 | for (j = 0; j < q; j++) 22 | cin >> B[i][j]; 23 | for (i = 0; i < m; i++) 24 | for (j = 0; j < n; j++) 25 | C[i][j] = A[i][j] + B[i][j]; 26 | cout << "Sum of matrices\n"; 27 | for (i = 0; i < m; i++) 28 | { for (j = 0; j < n; j++) 29 | cout << C[i][j] << " "; 30 | cout << "\n"; 31 | } 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /C++/Merge Intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> merge(vector>& intervals) { 4 | sort(intervals.begin(), intervals.end()); 5 | 6 | vector> merged; 7 | for (auto interval : intervals) { 8 | // if the list of merged intervals is empty or if the current 9 | // interval does not overlap with the previous, simply append it. 10 | if (merged.empty() || merged.back()[1] < interval[0]) { 11 | merged.push_back(interval); 12 | } 13 | // otherwise, there is overlap, so we merge the current and previous 14 | // intervals. 15 | else { 16 | merged.back()[1] = max(merged.back()[1], interval[1]); 17 | } 18 | } 19 | return merged; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/NoDrugs.cpp: -------------------------------------------------------------------------------- 1 | Problem Link : https://www.codechef.com/CDMN21B/problems/NODRUGS 2 | 3 | Code : 4 | 5 | #include 6 | using namespace std; 7 | #define ll long long int 8 | 9 | int main() 10 | { 11 | ios_base::sync_with_stdio(false); 12 | cin.tie(NULL); cout.tie(NULL); 13 | 14 | 15 | ll t; 16 | cin >> t; 17 | while(t--){ 18 | ll n,k,l; 19 | cin >> n >> k >> l; 20 | int a[n]; 21 | int max = INT_MIN; 22 | int i=0; 23 | int t=n; 24 | while(n--){ 25 | int x; 26 | cin >> x; 27 | a[i]=x; 28 | if(x>max){ 29 | max = x; 30 | } 31 | i++; 32 | } 33 | 34 | int f; 35 | f = a[t-1] + (k*(l-1)); 36 | if(k<=0 and a[t-1]>=max){ 37 | cout << "Yes" << "\n"; 38 | } 39 | else if(f>max){ 40 | cout << "Yes" << "\n"; 41 | } 42 | else{ 43 | cout << "No" << "\n"; 44 | } 45 | } 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /C++/Operator Overloading: -------------------------------------------------------------------------------- 1 | //Binary operator overloading 2 | 3 | #include 4 | using namespace std; 5 | class bioverload{ 6 | public: 7 | int a,b,d; 8 | bioverload(int x,int y) 9 | { 10 | a=x; 11 | b=y; 12 | 13 | } 14 | 15 | bioverload() 16 | { 17 | 18 | } 19 | 20 | bioverload operator +(bioverload c) 21 | { 22 | bioverload b3; 23 | b3.a=a+c.a; //10+20=30 24 | b3.b=b+c.b; //20+30=50 25 | return b3; 26 | // 27 | 28 | } 29 | }; 30 | 31 | int main(){ 32 | bioverload b1(10,20); 33 | bioverload b2(20,30); 34 | bioverload b3; 35 | b3=b1+b2; 36 | // cout<<"Value of b3.a :"< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int r, c = 1; 7 | 8 | cout << "Number of rows: "; 9 | cin >> r; 10 | 11 | for(int i = 0; i < r; i++) 12 | { 13 | for(int space = 1; space <= r-i; space++) 14 | cout <<" "; 15 | 16 | for(int j = 0; j <= i; j++) 17 | { 18 | if (j == 0 || i == 0) 19 | c = 1; 20 | else 21 | c = c*(i-j+1)/j; 22 | 23 | cout << c << " "; 24 | } 25 | cout << endl; 26 | } 27 | 28 | return 0; 29 | } 30 | 31 | /* Output: 32 | 33 | Number of rows: 5 34 | 35 | 1 36 | 1 1 37 | 1 2 1 38 | 1 3 3 1 39 | 1 4 6 4 1 40 | 41 | */ 42 | -------------------------------------------------------------------------------- /C++/Pattern-1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int rows; 7 | 8 | cout << "Enter number of rows: "; 9 | cin >> rows; 10 | 11 | for(int i = 1; i <= rows; ++i) 12 | { 13 | for(int j = 1; j <= i; ++j) 14 | { 15 | cout << "* "; 16 | } 17 | cout << endl; 18 | } 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /C++/Pattern-2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int rows; 7 | 8 | cout << "Enter number of rows: "; 9 | cin >> rows; 10 | 11 | for(int i = 1; i <= rows; ++i) 12 | { 13 | for(int j = 1; j <= i; ++j) 14 | { 15 | cout << j << " "; 16 | } 17 | cout << "\n"; 18 | } 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /C++/Pattern-3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | char input, alphabet = 'A'; 7 | 8 | cout << "Enter the uppercase character you want to print in the last row: "; 9 | cin >> input; 10 | 11 | for(int i = 1; i <= (input-'A'+1); ++i) 12 | { 13 | for(int j = 1; j <= i; ++j) 14 | { 15 | cout << alphabet << " "; 16 | } 17 | ++alphabet; 18 | 19 | cout << endl; 20 | } 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /C++/Pattern-4.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int rows; 7 | 8 | cout << "Enter number of rows: "; 9 | cin >> rows; 10 | 11 | for(int i = rows; i >= 1; --i) 12 | { 13 | for(int j = 1; j <= i; ++j) 14 | { 15 | cout << "* "; 16 | } 17 | cout << endl; 18 | } 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /C++/Pattern-5.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | Program to print the following pattern 6 | 7 | * 8 | * * 9 | * * * 10 | * * * * 11 | * * * * * 12 | 13 | */ 14 | 15 | int main(){ 16 | int n; 17 | cout<<"Number of rows: "; 18 | cin>> n; 19 | for(int i = 1; i <= n; i++){ 20 | for(int j = 0; j < n; j++){ 21 | (j < n-i)? cout<< " " : cout<< "* "; 22 | } 23 | cout<< endl; 24 | } 25 | return 0; 26 | } -------------------------------------------------------------------------------- /C++/Plusad.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | int first_number, second_number, sum; 8 | 9 | 10 | 11 | cout << "Enter two integers: "; 12 | 13 | cin >> first_number >> second_number; 14 | 15 | // sum of two numbers in stored in variable sumOfTwoNumbers 16 | 17 | sum = first_number + second_number; 18 | 19 | // prints sum 20 | 21 | cout << first_number << " + " << second_number << " = " << sum; 22 | 23 | return 0; 24 | 25 | } 26 | -------------------------------------------------------------------------------- /C++/Program to Add Two Integers: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int firstNumber, secondNumber, sumOfTwoNumbers; 7 | 8 | cout << "Enter two integers: "; 9 | cin >> firstNumber >> secondNumber; 10 | 11 | // sum of two numbers in stored in variable sumOfTwoNumbers 12 | sumOfTwoNumbers = firstNumber + secondNumber; 13 | 14 | // Prints sum 15 | cout << firstNumber << " + " << secondNumber << " = " << sumOfTwoNumbers; 16 | 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /C++/Reverse.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main () 5 | { 6 | char str[50], temp; 7 | int i, j; 8 | cout << "Enter a string : "; 9 | gets(str); 10 | j = strlen(str) - 1; 11 | for (i = 0; i < j; i++,j--) 12 | { 13 | temp = str[i]; 14 | str[i] = str[j]; 15 | str[j] = temp; 16 | } 17 | cout << "\nReverse string : " << str; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /C++/Reverse111.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | string str = "Hello world!"; 7 | reverse(str.begin(), str.end()); 8 | cout << str; 9 | return 0; 10 | } 11 | -------------------------------------------------------------------------------- /C++/Sort012: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() { 4 | int n; 5 | cin>>n; 6 | int a[1000]; 7 | for(int i=0;i>a[i]; 9 | } 10 | int cnt1=0; 11 | int cnt0=0; 12 | int cnt2=0; 13 | for(int i=0;i 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | int first_number, second_number, sum; 8 | 9 | 10 | 11 | cout << "Enter two integers: "; 12 | 13 | cin >> first_number >> second_number; 14 | 15 | // sum of two numbers in stored in variable sumOfTwoNumbers 16 | 17 | sum = first_number + second_number; 18 | 19 | // prints sum 20 | 21 | cout << first_number << " + " << second_number << " = " << sum; 22 | 23 | return 0; 24 | 25 | } 26 | -------------------------------------------------------------------------------- /C++/To find area of circle: -------------------------------------------------------------------------------- 1 | #include < stdio.h > 2 | #include < conio.h > #define PI 3.141 3 | int main() 4 | { 5 | float radius, area; 6 | printf("Enter radius of circle\n"); 7 | scanf("%f", & radius); 8 | area = PI * radius * radius; 9 | printf("Area of circle : %0.4f\n", area); 10 | getch(); 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /C++/Two sum.cpp: -------------------------------------------------------------------------------- 1 | //Question------ 2 | 3 | // Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 4 | 5 | // You may assume that each input would have exactly one solution, and you may not use the same element twice. 6 | 7 | // You can return the answer in any order. 8 | 9 | 10 | // Example 1: 11 | 12 | // Input: nums = [2,7,11,15], target = 9 13 | // Output: [0,1] 14 | // Output: Because nums[0] + nums[1] == 9, we return [0, 1]. 15 | // Example 2: 16 | 17 | // Input: nums = [3,2,4], target = 6 18 | // Output: [1,2] 19 | // Example 3: 20 | 21 | // Input: nums = [3,3], target = 6 22 | // Output: [0,1] 23 | 24 | // Solution----- 25 | 26 | 27 | class Solution { 28 | public: 29 | vector twoSum(vector& nums, int target) { 30 | vector s; 31 | unordered_map a; 32 | for(int i=0;i 2 | 3 | int main() { 4 | std::cout << "Hello & Welcome to Adding Calculator Application.\n"; 5 | 6 | // Create the Variables (FirstNumber & SecondNumber) 7 | int FirstNumber = 0, SecondNumber = 0; 8 | 9 | // Get the First Number 10 | std::cout << "Please enter your first number: "; 11 | std::cin >> FirstNumber; 12 | 13 | // Get the Second Number 14 | std::cout << "Please enter your second number: "; 15 | std::cin >> SecondNumber; 16 | 17 | // Add the two numbers 18 | int Sum = FirstNumber + SecondNumber; 19 | std::cout << "The Sum of the two numbers is: "<< Sum; 20 | } 21 | -------------------------------------------------------------------------------- /C++/bubblesort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void bubbleSort(std::vector &arr) { 5 | int n = static_cast(arr.size()); 6 | while (n > 0) { 7 | int lastModifiedIndex = 0; 8 | for (int currentIndex = 1; currentIndex < n; currentIndex++) { 9 | // if the item at the previous index is greater than the item at the `currentIndex`, swap them 10 | if (arr[currentIndex - 1] > arr[currentIndex]) { 11 | // swap 12 | int temp = arr[currentIndex - 1]; 13 | arr[currentIndex - 1] = arr[currentIndex]; 14 | arr[currentIndex] = temp; 15 | // save the index that was modified 16 | lastModifiedIndex = currentIndex; 17 | } 18 | } 19 | // save the last modified index so we know not to iterate past it since all proceeding values are sorted 20 | n = lastModifiedIndex; 21 | } 22 | } 23 | 24 | int main() { 25 | std::vector arr = {12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8}; 26 | bubbleSort(arr); 27 | for (int i; i < arr.size(); i++) { 28 | std::cout << arr[i]; 29 | if (i < arr.size() - 1) std::cout << ", "; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /C++/carry_Sum_Counter.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | int fun(int m,int n){ 11 | int carry = 0; 12 | int countCarr = 0; 13 | int diff = 0; 14 | 15 | for(int i=0; i<3;i++){ 16 | 17 | int lastM = m%10; 18 | m = m/10; 19 | int lastN = n%10; 20 | n = n/10; 21 | 22 | if( (lastM + lastN + diff) >= 10 ){ 23 | countCarr++; 24 | diff = 1; 25 | } 26 | } 27 | 28 | return countCarr; 29 | } 30 | 31 | 32 | 33 | int main(){ 34 | 35 | int m ; 36 | cout << "Enter first number" << endl; 37 | cin >> m; 38 | int n ; 39 | cout << "Enter Second Number" << endl; 40 | cin >> n; 41 | 42 | cout << "Carry happened in the addition : "; 43 | cout << fun(m,n); 44 | 45 | return 0; 46 | 47 | 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /C++/compress.cpp: -------------------------------------------------------------------------------- 1 | void stringCompression(char input[]) { 2 | // Write your code here 3 | int k; 4 | for (int i=0; i 18 | #include 19 | #include 20 | using namespace std; 21 | 22 | //#include "solution.h" 23 | 24 | int main() { 25 | int size = 1e6; 26 | string str; 27 | cin >> str; 28 | str = getCompressedString(str); 29 | cout << str << endl; 30 | } 31 | -------------------------------------------------------------------------------- /C++/connected_components_undirected_graph.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | const int N = 1e5 + 10; 4 | vector g[N]; 5 | bool vis[N]; 6 | void dfs(int vertex){ 7 | vis[vertex] = true; 8 | for(int child:g[vertex]){ 9 | if(vis[child]) continue; 10 | dfs(child); 11 | } 12 | } 13 | int main() { 14 | int n,e; 15 | cin>>n>>e; 16 | for(int i=0;i>x>>y;-g[x].push_back(y); 19 | g[y].push_back(x); 20 | 21 | } 22 | int ct =0; 23 | for(int i=1;i<=n;i++){ 24 | if(vis[i]) continue; 25 | dfs(i); 26 | ct++; 27 | } 28 | cout< 3 | using namespace std; 4 | 5 | /* Function to sort an array using insertion sort*/ 6 | void insertionSort(int arr[], int n) 7 | { 8 | int i, key, j; 9 | for (i = 1; i < n; i++) 10 | { 11 | key = arr[i]; 12 | j = i - 1; 13 | 14 | /* Move elements of arr[0..i-1], that are 15 | greater than key, to one position ahead 16 | of their current position */ 17 | while (j >= 0 && arr[j] > key) 18 | { 19 | arr[j + 1] = arr[j]; 20 | j = j - 1; 21 | } 22 | arr[j + 1] = key; 23 | } 24 | } 25 | 26 | // A utility function to print an array of size n 27 | void printArray(int arr[], int n) 28 | { 29 | int i; 30 | for (i = 0; i < n; i++) 31 | cout << arr[i] << " "; 32 | cout << endl; 33 | } 34 | 35 | /* Driver code */ 36 | int main() 37 | { 38 | int arr[] = { 12, 11, 13, 5, 6 }; 39 | int n = sizeof(arr) / sizeof(arr[0]); 40 | 41 | insertionSort(arr, n); 42 | printArray(arr, n); 43 | 44 | return 0; 45 | } 46 | 47 | // This is code is contributed by rathbhupendra 48 | -------------------------------------------------------------------------------- /C++/intSUm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | std::cout << "Hello & Welcome to Adding Calculator Application.\n"; 5 | 6 | // Create the Variables (FirstNumber & SecondNumber) 7 | int FirstNumber = 0, SecondNumber = 0; 8 | 9 | // Get the First Number 10 | std::cout << "Please enter your first number: "; 11 | std::cin >> FirstNumber; 12 | 13 | // Get the Second Number 14 | std::cout << "Please enter your second number: "; 15 | std::cin >> SecondNumber; 16 | 17 | // Add the two numbers 18 | int Sum = FirstNumber + SecondNumber; 19 | std::cout << "The Sum of the two numbers is: "<< Sum; 20 | } 21 | -------------------------------------------------------------------------------- /C++/kadane_algo.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print largest contiguous array sum using KADANE ALGORITHM 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int maxSubArraySum(int a[], int size) 7 | { 8 | int max_so_far = INT_MIN, max_ending_here = 0, 9 | start =0, end = 0, s=0; 10 | 11 | for (int i=0; i< size; i++ ) 12 | { 13 | max_ending_here += a[i]; 14 | 15 | if (max_so_far < max_ending_here) 16 | { 17 | max_so_far = max_ending_here; 18 | start = s; 19 | end = i; 20 | } 21 | 22 | if (max_ending_here < 0) 23 | { 24 | max_ending_here = 0; 25 | s = i + 1; 26 | } 27 | } 28 | cout << "Maximum contiguous sum is " 29 | << max_so_far << endl; 30 | cout << "Starting index "<< start 31 | << endl << "Ending index "<< end << endl; 32 | } 33 | 34 | /*Driver program to test maxSubArraySum*/ 35 | int main() 36 | { 37 | int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; 38 | int n = sizeof(a)/sizeof(a[0]); 39 | int max_sum = maxSubArraySum(a, n); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /C++/mergesortedarray.cpp: -------------------------------------------------------------------------------- 1 | void merge(int *arr1, int size1, int *arr2, int size2, int *ans) 2 | { 3 | //Write your code here 4 | int i=0, j=0, k=0; 5 | while (i 24 | using namespace std; 25 | 26 | 27 | 28 | int main() 29 | { 30 | int t; 31 | cin >> t; 32 | 33 | while (t--) 34 | { 35 | int size1; 36 | cin >> size1; 37 | 38 | int *arr1 = new int[size1]; 39 | 40 | for (int i = 0; i < size1; i++) 41 | { 42 | cin >> arr1[i]; 43 | } 44 | 45 | int size2; 46 | cin >> size2; 47 | 48 | int *arr2 = new int[size2]; 49 | 50 | for (int i = 0; i < size2; i++) 51 | { 52 | cin >> arr2[i]; 53 | } 54 | 55 | int *ans = new int[size1 + size2]; 56 | 57 | merge(arr1, size1, arr2, size2, ans); 58 | 59 | for (int i = 0; i < size1 + size2; i++) 60 | { 61 | cout << ans[i] << " "; 62 | } 63 | 64 | cout << endl; 65 | delete[] arr1; 66 | delete[] arr2; 67 | delete[] ans; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /C++/passwordCheck.cpp: -------------------------------------------------------------------------------- 1 | Problem Link : https://www.codechef.com/problems/PASSWD 2 | 3 | code : 4 | 5 | #include 6 | using namespace std; 7 | #define ll long long int 8 | 9 | int main() 10 | { 11 | ios_base::sync_with_stdio(false); 12 | cin.tie(NULL); cout.tie(NULL); 13 | 14 | 15 | ll t; 16 | cin >> t; 17 | while(t--){ 18 | string s; 19 | cin >> s; 20 | int l = s.length(); 21 | int lc=0,uc=0,dc=0,sc=0; 22 | for(int i=0;i='a' and s[i]<='z'){ 24 | lc++; 25 | } 26 | else if((s[i]>='A' and s[i]<='Z') and (i!=0 and i!=(l-1))){ 27 | uc++; 28 | } 29 | else if(s[i]>='0' and s[i]<='9' and (i!=0 and i!=(l-1))){ 30 | dc++; 31 | } 32 | else if((s[i]=='@' or s[i]=='#' or s[i]=='%' or s[i]=='&' or s[i]=='?') and (i!=0 and i!=l-1) ){ 33 | sc++; 34 | } 35 | } 36 | 37 | if(l>=10 and (lc>=1 and uc>=1 and dc>=1 and sc>=1)){ 38 | cout << "YES" << "\n"; 39 | } 40 | else{ 41 | cout << "NO" << "\n"; 42 | } 43 | } 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /C++/pre-post.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | bool isOperator(char x) { 5 | switch (x) { 6 | case '+': 7 | case '-': 8 | case '/': 9 | case '*': 10 | return true; 11 | } 12 | return false; 13 | } 14 | string preToPost(string pre_exp) { 15 | 16 | stack s; 17 | int length = pre_exp.size(); 18 | for (int i = length - 1; i >= 0; i--) { 19 | if (isOperator(pre_exp[i])) { 20 | string op1 = s.top(); s.pop(); 21 | string op2 = s.top(); s.pop(); 22 | string temp = op1 + op2 + pre_exp[i]; 23 | s.push(temp); 24 | } 25 | else { 26 | s.push(string(1, pre_exp[i])); 27 | } 28 | } 29 | return s.top(); 30 | } 31 | int main() { 32 | string pre_exp; 33 | cout<<"Enter Prefix string : \n"; 34 | cin>>pre_exp; 35 | cout << "Postfix : " << preToPost(pre_exp); 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /C++/progarm to find factorial: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int n; 6 | long factorial = 1.0; 7 | 8 | cout << "Enter a positive integer: "; 9 | cin >> n; 10 | 11 | if (n < 0) 12 | cout << "Error! Factorial of a negative number doesn't exist."; 13 | else { 14 | for(int i = 1; i <= n; ++i) { 15 | factorial *= i; 16 | } 17 | cout << "Factorial of " << n << " = " << factorial; 18 | } 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /C++/removeduplicates: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | int removdup(int arr[],int n){ 7 | int i=0; 8 | for(int j=1;j>n; 24 | for(int i=0;i>arr[i]; 26 | 27 | } 28 | 29 | int k= removdup(arr,n); 30 | for(int i=0;i 3 | 4 | using namespace std; 5 | 6 | void reverseStr(string& str) 7 | { 8 | 9 | int n = str.length(); 10 | 11 | for (int i = 0; i < n / 2; i++) 12 | 13 | swap(str[i], str[n - i - 1]); 14 | } 15 | 16 | // Driver program 17 | 18 | int main() 19 | { 20 | 21 | string str = "geeksforgeeks"; 22 | 23 | reverseStr(str); 24 | 25 | cout << str; 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /C++/reverse.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main () 5 | { 6 | char str[50], temp; 7 | int i, j; 8 | cout << "Enter a string : "; 9 | gets(str); 10 | j = strlen(str) - 1; 11 | for (i = 0; i < j; i++,j--) 12 | { 13 | temp = str[i]; 14 | str[i] = str[j]; 15 | str[j] = temp; 16 | } 17 | cout << "\nReverse string : " << str; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /C++/reverse565.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main () 5 | { 6 | char str[50], temp; 7 | int i, j; 8 | cout << "Enter a string : "; 9 | gets(str); 10 | j = strlen(str) - 1; 11 | for (i = 0; i < j; i++,j--) 12 | { 13 | temp = str[i]; 14 | str[i] = str[j]; 15 | str[j] = temp; 16 | } 17 | cout << "\nReverse string : " << str; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /C++/rotateMatrixAntiClockWiseBy90deg.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void rotate90(int **mat, int n ) 4 | { 5 | for(int i=0;i>mat[i][j]; 38 | } 39 | } 40 | rotate90(mat,n); 41 | return 0; 42 | } -------------------------------------------------------------------------------- /C++/rotatematrix.cpp: -------------------------------------------------------------------------------- 1 | void rotate(int **input, int n){ 2 | /* Don't write main(). 3 | * Don't read input, it is passed as function argument. 4 | * Taking input and printing output is handled automatically. 5 | */ 6 | int k; 7 | for (int i=0; i 21 | using namespace std; 22 | 23 | 24 | int main() { 25 | int n; 26 | cin >> n; 27 | 28 | int **input = new int*[n]; 29 | 30 | for(int i = 0; i < n; i++) { 31 | input[i] = new int[n]; 32 | for(int j = 0; j < n; j++) { 33 | cin >> input[i][j]; 34 | } 35 | } 36 | 37 | rotate(input, n); 38 | 39 | for(int i = 0; i < n; i++) { 40 | for(int j = 0; j < n; j++) { 41 | cout << input[i][j] << " "; 42 | } 43 | cout << endl; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /C++/selection_sort.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | using namespace std; 5 | 6 | void swap(int *xp, int *yp) 7 | { 8 | int temp = *xp; 9 | *xp = *yp; 10 | *yp = temp; 11 | } 12 | 13 | void selectionSort(int arr[], int n) 14 | { 15 | int i, j, min_idx; 16 | 17 | for (i = 0; i < n-1; i++) 18 | { 19 | min_idx = i; 20 | for (j = i+1; j < n; j++) 21 | if (arr[j] < arr[min_idx]) 22 | min_idx = j; 23 | 24 | swap(&arr[min_idx], &arr[i]); 25 | } 26 | } 27 | 28 | void printArray(int arr[], int size) 29 | { 30 | int i; 31 | for (i=0; i < size; i++) 32 | cout << arr[i] << " "; 33 | cout << endl; 34 | } 35 | 36 | int main() 37 | { 38 | int arr[] = {64, 25, 12, 22, 11}; 39 | int n = sizeof(arr)/sizeof(arr[0]); 40 | selectionSort(arr, n); 41 | cout << "Sorted array: \n"; 42 | printArray(arr, n); 43 | return 0; 44 | } 45 | 46 | -------------------------------------------------------------------------------- /C++/sliding_window_max_of_all_subarrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | //Main Function Block 6 | void printKMax(int arr[], int n, int k) 7 | { 8 | deque dq(k); 9 | for (int i = 0; i < k; ++i) 10 | { 11 | while ((!dq.empty()) && arr[i] >= arr[dq.back()]) 12 | dq.pop_back(); 13 | 14 | dq.push_back(i); 15 | } 16 | 17 | for (; i < n; ++i) 18 | { 19 | cout << arr[dq.front()] << " "; 20 | 21 | while ((!dq.empty()) && dq.front() <= i - k) 22 | 23 | dq.pop_front(); 24 | 25 | while ((!dq.empty()) && arr[i] >= arr[dq.back()]) 26 | dq.pop_back(); 27 | 28 | dq.push_back(i); 29 | } 30 | 31 | cout << arr[dq.front()]; 32 | } 33 | 34 | //Testing code 35 | int main() 36 | { 37 | int arr[] = { 12, 156, 73, 93, 59, 83, 51, 73, 101, 456}; 38 | int n = sizeof(arr) / sizeof(arr[0]); 39 | int k = 3; 40 | printKMax(arr, n, k); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /C++/squareRoot.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | float number, root; 7 | cout << "Enter number whose root is to be found: "; 8 | cin >> number; 9 | root = sqrt(number); 10 | cout << "Square root of " << number << " is " << root; 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /C++/swap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class SwapNumbers 4 | { 5 | private: 6 | int x,y; 7 | public: 8 | void getdata() 9 | { 10 | cin>>x>>y; 11 | } 12 | void showdata() 13 | { 14 | cout<<"X="< 2 | using namespace std; 3 | int main() 4 | { 5 | int person = 100; 6 | vector a(person); 7 | for (int i = 0; i < person; i++) { 8 | a[i] = i + 1; 9 | } 10 | int pos = 0; 11 | while (a.size() > 1) { 12 | pos++; 13 | pos %= a.size(); 14 | a.erase(a.begin() + pos); 15 | } 16 | cout << a[0]; 17 | return 0; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /C/Anagram.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main () { 5 | char s1[45], s2[45]; 6 | scanf("%s %s", s1, s2); 7 | 8 | char temp; 9 | int i, j; 10 | int n = strlen(s1); 11 | int n1 = strlen(s2); 12 | 13 | if( n != n1) { 14 | printf("Strings are not anagrams! \n", s1, s2); 15 | return 0; 16 | } 17 | 18 | for (i = 0; i < n-1; i++) { 19 | for (j = i+1; j < n; j++) { 20 | if (s1[i] > s1[j]) { 21 | temp = s1[i]; 22 | s1[i] = s1[j]; 23 | s1[j] = temp; 24 | } 25 | if (s2[i] > s2[j]) { 26 | temp = s2[i]; 27 | s2[i] = s2[j]; 28 | s2[j] = temp; 29 | } 30 | } 31 | } 32 | 33 | for(i = 0; i 2 | void main() 3 | { float a,b,h; 4 | printf("Enter the base : "); 5 | scanf("%f",&b); 6 | printf("Enter the height : "); 7 | scanf("%f",&h); 8 | a=0.5*b*h; 9 | printf("Area is %f",a); 10 | } 11 | -------------------------------------------------------------------------------- /C/Bresenhams_Line_Drewing: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void drawline(int x0, int y0, int x1, int y1) 5 | { 6 | int dx, dy, p, x, y; 7 | 8 | dx=x1-x0; 9 | dy=y1-y0; 10 | 11 | x=x0; 12 | y=y0; 13 | 14 | p=2*dy-dx; 15 | 16 | while(x=0) 19 | { 20 | putpixel(x,y,7); 21 | y=y+1; 22 | p=p+2*dy-2*dx; 23 | } 24 | else 25 | { 26 | putpixel(x,y,7); 27 | p=p+2*dy; 28 | } 29 | x=x+1; 30 | } 31 | } 32 | 33 | int main() 34 | { 35 | int gdriver=DETECT, gmode, error, x0, y0, x1, y1; 36 | initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi"); 37 | 38 | printf("Enter co-ordinates of first point: "); 39 | scanf("%d %d", &x0 ,&y0); 40 | 41 | printf("Enter co-ordinates of second point: "); 42 | scanf("%d %d", &x1 ,&y1); 43 | drawline(x0, y0, x1, y1); 44 | delay(5000); 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /C/Coinchange.c: -------------------------------------------------------------------------------- 1 | // Dynamic Programming 2 | #include 3 | int count( int check[], int m, int n ) 4 | { 5 | if (n == 0) 6 | return 1; 7 | if (n < 0) 8 | return 0; 9 | if (m <=0 && n >= 1) 10 | return 0; 11 | return count(check, m - 1, n ) + count(check, m, n-check[m-1] ); 12 | } 13 | 14 | int main() 15 | { 16 | int i, j; 17 | int arr[] = {1, 2, 3}; 18 | int m = sizeof(arr)/sizeof(arr[0]); 19 | printf("%d ", count(arr, m, 4)); 20 | getchar(); 21 | return 0; 22 | } 23 | 24 | -------------------------------------------------------------------------------- /C/Denomination.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main() 4 | { 5 | long long int amount; 6 | printf("Enter the amount: "); 7 | scanf("%lld", &amount); 8 | int count2000 = 0, count500 = 0, count100 = 0, count50 = 0, count20 = 0; 9 | 10 | if (amount >= 2000) 11 | { 12 | count2000 = amount / 2000; 13 | printf("required no of 2000 notes %d\n", count2000); 14 | } 15 | count2000 = count2000 * 2000; 16 | amount -= count2000; 17 | 18 | if (amount >= 500) 19 | { 20 | count500 = amount / 500; 21 | } 22 | printf("required no of 500 notes %d\n", count500); 23 | 24 | count500 *= 500; 25 | amount -= count500; 26 | 27 | if (amount >= 100) 28 | { 29 | count100 = amount / 100; 30 | } 31 | printf("required no of 100 notes %d\n", count100); 32 | count100 *= 100; 33 | amount -= count100; 34 | 35 | if (amount >= 50) 36 | { 37 | count50 = amount / 50; 38 | } 39 | printf("required no of 50 notes %d\n", count50); 40 | count50 *= 50; 41 | amount -= count50; 42 | 43 | if (amount >= 20) 44 | { 45 | count20 = amount / 20; 46 | } 47 | printf("required no of 20 notes %d\n", count20); 48 | count20 *= 20; 49 | amount -= count20; 50 | } -------------------------------------------------------------------------------- /C/EvenNumberFinder.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int num; 4 | printf("Enter an integer: "); 5 | scanf("%d", &num); 6 | 7 | // true if num is perfectly divisible by 2 8 | if(num % 2 == 0) 9 | printf("%d is even.", num); 10 | else 11 | printf("%d is odd.", num); 12 | 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /C/Fibonacci Series.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int num1, num2, num3, count; 5 | printf("Enter the Starting two Numbers: "); 6 | scanf("%d%d", &num1, &num2); 7 | printf("Enter the Number upto Till you want the series: "); 8 | scanf("%d", &count); 9 | printf("The fabonacci series is : %d,%d,", num1, num2); 10 | if (count > 2) 11 | { 12 | int i = 0; 13 | for (i = 3; i <= count; i++) 14 | { 15 | num3 = num1 + num2; 16 | num1 = num2; 17 | num2 = num3; 18 | printf("%d", num3); 19 | if (i == count) 20 | { 21 | printf(" "); 22 | } 23 | else 24 | { 25 | printf(","); 26 | } 27 | } 28 | } 29 | return 0; 30 | } -------------------------------------------------------------------------------- /C/Fractional_knapsack.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define max 5 3 | char ob[5]={'D','P','G','S','B'}; 4 | int p[]={5000,4000,4500,6250,5000}; 5 | int w[]={10,10,15,25,50}; 6 | int p_w[max];int c=15; 7 | void swap(int*p,int*q) 8 | { 9 | int t=*p; 10 | *p=*q; 11 | *q=t; 12 | } 13 | void main() 14 | { 15 | int i=0; 16 | for(i;i0;i++) 36 | { 37 | if(w[i]<=c) 38 | { 39 | printf("\n 1 of %c",ob[i]); 40 | o_p=o_p+p[i]; 41 | c=c-w[i]; 42 | } 43 | else 44 | { 45 | o_p=o_p+(c)*p_w[i]; 46 | printf("\n %d/%d of %c",c,w[i],ob[i]); 47 | c=0; 48 | } 49 | } 50 | printf("\n Optimized Profit= %d",o_p); 51 | } 52 | -------------------------------------------------------------------------------- /C/FunctionsandTernary.c: -------------------------------------------------------------------------------- 1 | //A basic program of Finding the maximum of the entered numbers 2 | 3 | //1)Using Functions- using funchions always reduces the execution time( max_of_four) is the function used here 4 | //2)Using ternary Operator- where three( so why it is called as ternary) operands will be present 5 | //syntax of Ternary operator is - variable = Expression1 ? Expression2 : Expression3 6 | 7 | 8 | 9 | #include 10 | int max_of_four(int num1,int num2 , int num3 , int num4) 11 | {//using ternary operator 12 | int max1=(num1>num2)?num1:num2; 13 | int max2 = (num3>num4)?num3:num4; 14 | return (max1>max2)?max1:max2; 15 | } 16 | int main() { 17 | int num1,num2,num3,num4; 18 | printf("Enter number1: "); 19 | scanf("%d", &num1); 20 | printf("Enter number2: "); 21 | scanf("%d", &num2); 22 | printf("Enter number3: "); 23 | scanf("%d", &num3); 24 | printf("Enter number4: "); 25 | scanf("%d", &num4); 26 | 27 | int ans = max_of_four(num1,num2,num3,num4); 28 | printf("The maximum of all the entered num is :%d", ans); 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /C/HelloWorld.c: -------------------------------------------------------------------------------- 1 | // Program to print string `Hello, World! in C` 2 | #include 3 | main(){ 4 | printf("Hello, World!"); 5 | } 6 | -------------------------------------------------------------------------------- /C/Pallindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int n,r,sum=0,temp; 5 | printf("enter the number="); 6 | scanf("%d",&n); 7 | temp=n; 8 | while(n>0) 9 | { 10 | r=n%10; 11 | sum=(sum*10)+r; 12 | n=n/10; 13 | } 14 | if(temp==sum) 15 | printf("palindrome number "); 16 | else 17 | printf("not palindrome"); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /C/Pattern-1.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int i, j, rows; 4 | printf("Enter the number of rows: "); 5 | scanf("%d", &rows); 6 | for (i = 1; i <= rows; ++i) { 7 | for (j = 1; j <= i; ++j) { 8 | printf("* "); 9 | } 10 | printf("\n"); 11 | } 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /C/Pattern-2.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int i, j, rows; 4 | printf("Enter the number of rows: "); 5 | scanf("%d", &rows); 6 | for (i = 1; i <= rows; ++i) { 7 | for (j = 1; j <= i; ++j) { 8 | printf("%d ", j); 9 | } 10 | printf("\n"); 11 | } 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /C/Pattern-3.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int i, j; 4 | char input, alphabet = 'A'; 5 | printf("Enter an uppercase character you want to print in the last row: "); 6 | scanf("%c", &input); 7 | for (i = 1; i <= (input - 'A' + 1); ++i) { 8 | for (j = 1; j <= i; ++j) { 9 | printf("%c ", alphabet); 10 | } 11 | ++alphabet; 12 | printf("\n"); 13 | } 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /C/Pattern-4.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int i, j, rows; 4 | printf("Enter the number of rows: "); 5 | scanf("%d", &rows); 6 | for (i = rows; i >= 1; --i) { 7 | for (j = 1; j <= i; ++j) { 8 | printf("* "); 9 | } 10 | printf("\n"); 11 | } 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /C/Producer Consumer Problem.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int mutex=1,full=0,empty,x=0; 5 | 6 | int main() 7 | { 8 | int n,ch; 9 | void producer(); 10 | void consumer(); 11 | int wait(int); 12 | int signal(int); 13 | printf("Enter the size of buffer: "); 14 | scanf("%d",&n); 15 | empty=n; 16 | printf("\n1.Producer\n2.Consumer\n3.Exit\n"); 17 | while(1) 18 | { 19 | printf("Enter your choice: "); 20 | scanf("%d",&ch); 21 | switch(ch) 22 | { 23 | case 1: if((mutex==1)&&(empty!=0)) 24 | producer(); 25 | else 26 | printf("Buffer is full!\n"); 27 | break; 28 | case 2: if((mutex==1)&&(full!=0)) 29 | consumer(); 30 | else 31 | printf("Buffer is empty!!\n"); 32 | break; 33 | case 3: 34 | exit(0); 35 | break; 36 | } 37 | } 38 | 39 | return 0; 40 | } 41 | 42 | int wait(int s) 43 | { 44 | s--; 45 | return (s); 46 | } 47 | 48 | int signal(int s) 49 | { 50 | s++; 51 | return(s); 52 | } 53 | 54 | void producer() 55 | { 56 | mutex=wait(mutex); 57 | full=signal(full); 58 | empty=wait(empty); 59 | x++; 60 | printf("Producer produces the item %d\n",x); 61 | mutex=signal(mutex); 62 | } 63 | 64 | void consumer() 65 | { 66 | mutex=wait(mutex); 67 | full=wait(full); 68 | empty=signal(empty); 69 | printf("Consumer consumes item %d\n",x); 70 | x--; 71 | mutex=signal(mutex); 72 | } 73 | 74 | 75 | -------------------------------------------------------------------------------- /C/Program to convert fahrenheit to celsius: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | float celsius, fahrenheit; 6 | 7 | /* Input temperature in fahrenheit */ 8 | printf("Enter temperature in Fahrenheit: "); 9 | scanf("%f", &fahrenheit); 10 | 11 | /* Fahrenheit to celsius conversion formula */ 12 | celsius = (fahrenheit - 32) * 5 / 9; 13 | 14 | /* Print the value of celsius */ 15 | printf("%.2f Fahrenheit = %.2f Celsius", fahrenheit, celsius); 16 | 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /C/Swap Numbers Using Temporary Variable: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | double first, second, temp; 4 | printf("Enter first number: "); 5 | scanf("%lf", &first); 6 | printf("Enter second number: "); 7 | scanf("%lf", &second); 8 | 9 | // value of first is assigned to temp 10 | temp = first; 11 | 12 | // value of second is assigned to first 13 | first = second; 14 | 15 | // value of temp (initial value of first) is assigned to second 16 | second = temp; 17 | 18 | // %.2lf displays number up to 2 decimal points 19 | printf("\nAfter swapping, first number = %.2lf\n", first); 20 | printf("After swapping, second number = %.2lf", second); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /C/Swap_Numbers_Using_Temporary_Variable.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | double first, second, temp; 4 | printf("Enter first number: "); 5 | scanf("%lf", &first); 6 | printf("Enter second number: "); 7 | scanf("%lf", &second); 8 | 9 | // value of first is assigned to temp 10 | temp = first; 11 | 12 | // value of second is assigned to first 13 | first = second; 14 | 15 | // value of temp (initial value of first) is assigned to second 16 | second = temp; 17 | 18 | // %.2lf displays number up to 2 decimal points 19 | printf("\nAfter swapping, first number = %.2lf\n", first); 20 | printf("After swapping, second number = %.2lf", second); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /C/area.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main() 4 | { 5 | float radius, area; 6 | 7 | printf("Enter the radius of a circle\n"); 8 | 9 | scanf("%f", &radius); 10 | 11 | area = 3.14159*radius*radius; 12 | 13 | printf("Area of the circle = %.2f\n", area); // printing upto two decimal places 14 | 15 | return 0; 16 | -------------------------------------------------------------------------------- /C/array_copy_edit.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | void main() 5 | { 6 | clrscr(); 7 | int i,n,a[100],b[100],c[100],p=0,q=0,Y; 8 | char m; 9 | printf("Enter number of elements : "); 10 | scanf("%d",&n); 11 | printf("\nEnter %d elements = \n",n); 12 | for(i=0;i 2 | #include 3 | 4 | int main(){ 5 | int arr[10], i, j , temp; 6 | 7 | for ( i = 0 ; i < 10 ; i++ ){ 8 | scanf( "%d" , arr + i ); 9 | } 10 | 11 | for ( i=0 ; i < 9 ; i++ ){ 12 | for ( j = i + 1 ; j < 10 ; j++ ){ 13 | if ( *(arr+i) > *(arr+j) ){ 14 | temp = *(arr+i); 15 | *(arr+i) = *(arr+j); 16 | *(arr+j) = temp; 17 | } 18 | } 19 | } 20 | 21 | for ( i=0 ; i<10; i++) { 22 | printf("%d " , *(arr+i) ); 23 | } 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /C/factorial_of_large_numbers.c: -------------------------------------------------------------------------------- 1 | # include 2 | void main() 3 | { 4 | int a[10000];\ 5 | a[0]=1; 6 | printf("ENTER NUMBER\n"); 7 | int n,i=1,c,x=0,size=1; 8 | scanf("%d",&n); 9 | { 10 | for(i;i<=n;i++) 11 | { 12 | c=0; 13 | x=0; 14 | while(x=0;j--) 32 | { 33 | printf("%d",a[j]); 34 | } 35 | } 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /C/fibonacci.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | 4 | int i, n; 5 | 6 | // initialize first and second terms 7 | int t1 = 0, t2 = 1; 8 | 9 | // initialize the next term (3rd term) 10 | int nextTerm = t1 + t2; 11 | 12 | // get no. of terms from user 13 | printf("Enter the number of terms: "); 14 | scanf("%d", &n); 15 | 16 | // print the first two terms t1 and t2 17 | printf("Fibonacci Series: %d, %d, ", t1, t2); 18 | 19 | // print 3rd to nth terms 20 | for (i = 3; i <= n; ++i) { 21 | printf("%d, ", nextTerm); 22 | t1 = t2; 23 | t2 = nextTerm; 24 | nextTerm = t1 + t2; 25 | } 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /C/passgen.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | #include 6 | 7 | int password(int password_length) { 8 | 9 | char list[] = "1234567890qwertyuiopasdfghjklzxcvbnm!@#$%^&*()_- +=QWERTYUIOPASDFGHJKLZXCVBNM[]{};':\"<>,.?/\|"; 10 | 11 | printf("\t"); 12 | 13 | for(int i = 0; i < password_length; i++) { 14 | 15 | printf("*"); 16 | 17 | } 18 | 19 | printf("\n"); 20 | 21 | printf("\t"); 22 | 23 | srand(time(NULL)); 24 | 25 | for(int i = 0; i < password_length; i++) { 26 | 27 | printf("%c", list[rand() % (sizeof list - 1)]); 28 | 29 | } 30 | 31 | printf("\n"); 32 | 33 | printf("\t"); 34 | 35 | for(int i = 0; i < password_length; i++) { 36 | 37 | printf("*"); 38 | 39 | } 40 | 41 | printf("\n"); 42 | 43 | } 44 | 45 | int main() { 46 | 47 | int password_length; 48 | 49 | printf("\n\t*********************************\n\n"); 50 | 51 | printf("\tWelcome to the password generator\n\n"); 52 | 53 | printf("\t*********************************\n"); 54 | 55 | printf("\n\tEnter length of the password = "); 56 | 57 | scanf("%d", &password_length); 58 | 59 | printf("\n"); 60 | 61 | printf("\n"); 62 | 63 | password(password_length); 64 | 65 | return 0; 66 | 67 | } 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /C/pattern.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int i, j, rows; 4 | printf("Enter the number of rows: "); 5 | scanf("%d", &rows); 6 | for (i = 1; i <= rows; ++i) { 7 | for (j = 1; j <= i; ++j) { 8 | printf("* "); 9 | } 10 | printf("\n"); 11 | } 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /C/shortAnArray.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | int arr[] = {1,7,10,13,16,19}; 6 | int arr_size = sizeof(arr)/sizeof(int)-1; 7 | int temp; 8 | 9 | 10 | for (int i = 0; i <= arr_size; i++) 11 | { 12 | for (int j = i + 1; j < arr_size; j++) 13 | { 14 | if (arr[i] > arr[j]) 15 | { 16 | temp = arr[i]; 17 | arr[i] = arr[j]; 18 | arr[j] = temp; 19 | } 20 | } 21 | } 22 | for (int i = 0; i <= arr_size; i++) 23 | printf("%5d", arr[i]); 24 | 25 | 26 | return 0; 27 | } -------------------------------------------------------------------------------- /C/sum.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | 4 | int number1, number2, sum; 5 | 6 | printf("Enter two integers: "); 7 | scanf("%d %d", &number1, &number2); 8 | 9 | // calculating sum 10 | sum = number1 + number2; 11 | 12 | printf("%d + %d = %d", number1, number2, sum); 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /C/water_level.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int a,i,b,d; 5 | printf("The rate of water flow is 1 litre per second"); 6 | printf("\nNow ,enter the water level of the tank"); 7 | scanf("%d", &a); 8 | for(i=0;i<=a;i++) 9 | { 10 | printf("\n%d", i); 11 | } 12 | printf("\nThe choices are \nTo stop the flow \nTo release water"); 13 | scanf("%d", &b); 14 | switch(b) 15 | { 16 | case 1: printf("\nThe flow of water is stopped"); 17 | break; 18 | case 2: for(i=a;i>=0;i--) 19 | { 20 | d=i; 21 | printf("\n%d", d); 22 | } 23 | } 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Clojure/.lein-failures: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------------------------------- /Clojure/Hello, world!: -------------------------------------------------------------------------------- 1 | user=> (println "Hello, world!") 2 | Hello, world! 3 | nil 4 | 5 | 6 | 7 | 8 | user> "h" 9 | "h" 10 | 11 | user> 100 12 | 100 13 | 14 | user> true 15 | true 16 | -------------------------------------------------------------------------------- /Clojure/doc/intro.md: -------------------------------------------------------------------------------- 1 | # Introduction to sort 2 | 3 | TODO: write [great documentation](http://jacobian.org/writing/what-to-write/) 4 | -------------------------------------------------------------------------------- /Clojure/project.clj: -------------------------------------------------------------------------------- 1 | (defproject sort "0.1.0-SNAPSHOT" 2 | :description "FIXME: write description" 3 | :url "http://example.com/FIXME" 4 | :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0" 5 | :url "https://www.eclipse.org/legal/epl-2.0/"} 6 | :dependencies [[org.clojure/clojure "1.10.3"]] 7 | :main sort.core 8 | :target-path "target/%s" 9 | :profiles {:uberjar {:aot :all 10 | :jvm-opts ["-Dclojure.compiler.direct-linking=true"]}}) 11 | -------------------------------------------------------------------------------- /Clojure/src/sort/core.clj: -------------------------------------------------------------------------------- 1 | (ns sort.core 2 | (:gen-class)) 3 | 4 | (defn quick-sort [[pivot & coll]] 5 | (when pivot 6 | (concat (quick-sort (filter #(< % pivot) coll)) 7 | [pivot] 8 | (quick-sort (filter #(>= % pivot) coll))))) 9 | 10 | (defn -main 11 | "I will call quick-sort" 12 | [& args] 13 | (let [unsorted [3 2 1 4 7]] 14 | (println "Hello, Quick-Sort:") 15 | (println "Input: " unsorted) 16 | (println "Output: " (quick-sort unsorted)))) 17 | -------------------------------------------------------------------------------- /Clojure/test/sort/core_test.clj: -------------------------------------------------------------------------------- 1 | (ns sort.core-test 2 | (:require [clojure.test :refer [deftest testing is]] 3 | [sort.core :refer [quick-sort]])) 4 | 5 | (deftest a-test 6 | (testing "Woohooo" 7 | (is (= nil (quick-sort []))) 8 | (is (= nil (quick-sort []))) 9 | (is (= [0] (quick-sort [0]))) 10 | (is (= [0 1 2] (quick-sort [0 1 2]))) 11 | (is (= [0 1 2] (quick-sort [2 1 0]))) 12 | (is (= [1 2 8] (quick-sort [2 8 1]))) 13 | (is (= [-5 0 9] (quick-sort [0 -5 9]))))) 14 | -------------------------------------------------------------------------------- /Dart/DataTypesInDart.dart: -------------------------------------------------------------------------------- 1 | main() { 2 | // Strings can be appended using + 3 | print("dart" + "lang"); 4 | 5 | // Integers and Floats 6 | print("1+1=${1+1}"); 7 | print("7.0/3.0 =${7.0/3.0}"); 8 | 9 | // Booleans 10 | print(true && false); 11 | print(false || true); 12 | print(!true); 13 | } 14 | -------------------------------------------------------------------------------- /Dart/Factorial.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | stdout.write("Enter a number :"); 5 | int? n = int.parse(stdin.readLineSync()!); 6 | print(factorial(n)); 7 | } 8 | 9 | int factorial(int n) { 10 | int res = 1, i; 11 | for (i = 2; i <= n; i++) res *= i; 12 | return res; 13 | } 14 | -------------------------------------------------------------------------------- /Dart/HelloWorld.dart: -------------------------------------------------------------------------------- 1 | // Program to print string `Hello, World! in Dart` 2 | main(){ 3 | print('Hello, World!'); 4 | } 5 | -------------------------------------------------------------------------------- /Dart/armstrong.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | void main(){ 4 | 5 | int? num; 6 | print('Enter A Number to check ARMSTRONG or NOT ARMSTRONG NUMBER'); 7 | // user will enter a number to check 8 | num = int.parse(stdin.readLineSync()!); 9 | 10 | // user entered number is passed to function 11 | isArmString(num); 12 | 13 | } 14 | 15 | //a function to check arm strong 16 | void isArmString(int number){ 17 | //initial some variable 18 | int temp,digits =0, last = 0, sum = 0; 19 | 20 | //assign user entered number to temp variable 21 | temp = number; 22 | 23 | // loop execute until temp is 0 and increment digits by 1 each loop 24 | while(temp>0){ 25 | temp = temp~/10; 26 | digits++; 27 | } 28 | 29 | //reset temp to user entered number 30 | temp = number; 31 | 32 | //another loop for getting sum 33 | while(temp>0){ 34 | last = temp % 10; 35 | sum = sum + pow(last, digits) as int; 36 | temp = temp~/10; 37 | } 38 | 39 | // now if number and sum are equal its a arm strong number 40 | if(number == sum){ 41 | print("IT'S A ARMSTRONG NUMBER"); 42 | }else{ 43 | print("IT'S NOT ARMSTRONG NUMBER"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Dart/asyncCoding.dart: -------------------------------------------------------------------------------- 1 | Future fetchUserOrder() { 2 | return Future.delayed(const Duration(seconds: 2), () => print('Large Latte')); 3 | } 4 | 5 | void main() { 6 | fetchUserOrder(); 7 | print('Fetching user order...'); 8 | } -------------------------------------------------------------------------------- /Dart/decimal-to-binary.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | 3 | 4 | int decimal_value=10; //decimal value 5 | 6 | 7 | int binary_value = 0; 8 | 9 | 10 | int i = 1; 11 | 12 | 13 | 14 | 15 | 16 | while(decimal_value > 0) 17 | 18 | 19 | { 20 | 21 | 22 | binary_value = binary_value + (decimal_value % 2)*i; 23 | 24 | 25 | decimal_value = (decimal_value/2).floor(); 26 | 27 | 28 | i = i * 10; 29 | 30 | 31 | } 32 | 33 | 34 | 35 | print("the binary value is $binary_value"); 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Dart/palindrome.dart: -------------------------------------------------------------------------------- 1 | void main(){ 2 | int reminder, sum =0, temp; 3 | int number = 54545; 4 | 5 | temp = number; 6 | 7 | // a loop to reverse a number 8 | while(number>0) 9 | { 10 | reminder = number % 10; //get remainder 11 | sum = (sum*10)+reminder; 12 | number = number~/10; 13 | } 14 | 15 | if(sum == temp) 16 | { 17 | print('Its A Palindrome number'); 18 | 19 | }else{ 20 | print('Its A Not Palindrome number'); 21 | } 22 | 23 | 24 | // StringNumber(); 25 | } 26 | -------------------------------------------------------------------------------- /Dart/program.dart: -------------------------------------------------------------------------------- 1 | void main(){ 2 | int a = 2, b = 3, result; 3 | result =product(a, b); 4 | print('$result'); 5 | } 6 | 7 | // calculate multiplication and return the result 8 | int product(int a,int b){ 9 | int temp =0; 10 | while(b != 0){ 11 | temp += a; 12 | b--; 13 | } 14 | return temp; 15 | } 16 | -------------------------------------------------------------------------------- /Java/CycleSort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class MissingNumber { 3 | public static void main(String[] args) 4 | { 5 | int[] arr = { 3, 2, 4, 5, 1 }; 6 | int n = arr.length; 7 | System.out.println("Before sort :"); 8 | System.out.println(Arrays.toString(arr)); 9 | CycleSort(arr, n); 10 | 11 | } 12 | 13 | static void CycleSort(int[] arr, int n) 14 | { 15 | int i = 0; 16 | while (i < n) { 17 | 18 | int correctpos = arr[i] - 1; 19 | if (arr[i] < n && arr[i] != arr[correctpos]) { 20 | 21 | swap(arr, i, correctpos); 22 | } 23 | else { 24 | i++; 25 | } 26 | } 27 | System.out.println("After sort : "); 28 | System.out.print(Arrays.toString(arr)); 29 | 30 | 31 | } 32 | 33 | static void swap(int[] arr, int i, int correctpos) 34 | { 35 | 36 | int temp = arr[i]; 37 | arr[i] = arr[correctpos]; 38 | arr[correctpos] = temp; 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /Java/Digits_in_factorial.java: -------------------------------------------------------------------------------- 1 | // Java program to find the number 2 | // of digits in a factorial 3 | 4 | import java.io.*; 5 | import java.util.*; 6 | 7 | class Digits_in_factorial 8 | { 9 | // returns the number of digits 10 | // present in n! 11 | static int findDigits(int n) 12 | { 13 | // factorial exists only for n>=0 14 | if (n < 0) 15 | return 0; 16 | 17 | // base case 18 | if (n <= 1) 19 | return 1; 20 | 21 | // else iterate through n and calculate the 22 | // value 23 | double digits = 0; 24 | for (int i=2; i<=n; i++) 25 | digits += Math.log10(i); 26 | 27 | return (int)(Math.floor(digits)) + 1; 28 | } 29 | 30 | 31 | public static void main (String[] args) 32 | { 33 | System.out.println(findDigits(1)); 34 | System.out.println(findDigits(5)); 35 | System.out.println(findDigits(10)); 36 | System.out.println(findDigits(120)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Java/Fibonacci Series: -------------------------------------------------------------------------------- 1 | class FibonacciExample1{ 2 | public static void main(String args[]) 3 | { 4 | int n1=0,n2=1,n3,i,count=10; 5 | System.out.print(n1+" "+n2);//printing 0 and 1 6 | 7 | for(i=2;i= 90) 6 | return 'S'; 7 | 8 | else if (Mark >= 80 && Mark<90) 9 | return 'A'; 10 | 11 | else if (Mark >= 70 && Mark<80) 12 | return 'B'; 13 | 14 | else if (Mark >= 60 && Mark<70) 15 | return 'C'; 16 | 17 | else if (Mark >= 50 && Mark<60) 18 | return 'D'; 19 | 20 | else 21 | return 'F'; 22 | 23 | } 24 | 25 | public static void main(String args[]) { 26 | 27 | Scanner s = new Scanner(System.in); 28 | 29 | String registernum[] = new String[5]; 30 | 31 | int Mark[] = new int[5]; 32 | 33 | char grade[] = new char[5]; 34 | 35 | int Total = 0; 36 | 37 | System.out.println("Please enter the register numbers and marks"); 38 | 39 | for (int m = 0; m < 5; m++) { 40 | registernum[m] = s.next(); 41 | Mark[m] = s.nextInt(); 42 | s.nextLine(); 43 | 44 | grade[m] = grader(Mark[m]); 45 | 46 | Total = Total + Mark[m]; 47 | 48 | } 49 | 50 | for (int j = 0; j < 5; j++) { 51 | System.out.println("Grade for student - " + registernum[j] + " is " + grade[j]); 52 | } 53 | 54 | System.out.println("Class Average = " + (double) (Total / 5)); 55 | 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Java/HeapSort.java: -------------------------------------------------------------------------------- 1 | # Python program for implementation of heap Sort 2 | 3 | # To heapify subtree rooted at index i. 4 | # n is size of heap 5 | 6 | 7 | def heapify(arr, n, i): 8 | largest = i # Initialize largest as root 9 | l = 2 * i + 1 # left = 2*i + 1 10 | r = 2 * i + 2 # right = 2*i + 2 11 | 12 | # See if left child of root exists and is 13 | # greater than root 14 | if l < n and arr[largest] < arr[l]: 15 | largest = l 16 | 17 | # See if right child of root exists and is 18 | # greater than root 19 | if r < n and arr[largest] < arr[r]: 20 | largest = r 21 | 22 | # Change root, if needed 23 | if largest != i: 24 | arr[i], arr[largest] = arr[largest], arr[i] # swap 25 | 26 | # Heapify the root. 27 | heapify(arr, n, largest) 28 | 29 | # The main function to sort an array of given size 30 | 31 | 32 | def heapSort(arr): 33 | n = len(arr) 34 | 35 | # Build a maxheap. 36 | for i in range(n//2 - 1, -1, -1): 37 | heapify(arr, n, i) 38 | 39 | # One by one extract elements 40 | for i in range(n-1, 0, -1): 41 | arr[i], arr[0] = arr[0], arr[i] # swap 42 | heapify(arr, i, 0) 43 | 44 | 45 | # Driver code 46 | arr = [12, 11, 13, 5, 6, 7] 47 | heapSort(arr) 48 | n = len(arr) 49 | print("Sorted array is") 50 | for i in range(n): 51 | print("%d" % arr[i]), 52 | -------------------------------------------------------------------------------- /Java/HelloWorld.java: -------------------------------------------------------------------------------- 1 | // Program to print string `Hello, World! in Java 2 | import java.io.*; 3 | 4 | class HelloWorld { 5 | public static void main (String[] args) { 6 | System.out.println("Hello, World!"); 7 | } 8 | } -------------------------------------------------------------------------------- /Java/Hollowhalfdiamond.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | import java.util.*; 4 | 5 | public class Hollowhalfdiamond{ 6 | 7 | public static void main(String[] args) { 8 | 9 | Scanner sc = new Scanner(System.in); 10 | int n = sc.nextInt(); 11 | 12 | int sp = n+1; 13 | 14 | for(int i = 1; i <=n; i++){ 15 | 16 | for(int j = 1;j <=1; j++){ 17 | 18 | System.out.println("*\t"); 19 | } 20 | 21 | for(int k = 1; k <=sp; k++){ 22 | System.out.print("\t"); 23 | } 24 | sp-=2; 25 | 26 | for(int l = 1; l <=i; l++){ 27 | System.out.print("*\t"); 28 | } 29 | 30 | System.out.println(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Java/InsertionSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class InsertionSort { 4 | 5 | public static void insertionSort(int[] arr) { 6 | int n = arr.length; 7 | 8 | for (int i = 1; i < n; i++) { 9 | int max = arr[i]; 10 | int j = i - 1; 11 | 12 | while ((j > -1) && (arr[j] > max)) { 13 | arr[j + 1] = arr[j]; 14 | j--; 15 | } 16 | arr[j + 1] = max; 17 | 18 | } 19 | } 20 | 21 | public static void main(String[] args) { 22 | int[] ar = {56, 12, 32, 87, 65, 54, 43, 32, 31, 2}; 23 | System.out.println(Arrays.toString(ar)); 24 | insertionSort(ar); 25 | System.out.println(Arrays.toString(ar)); 26 | } 27 | } -------------------------------------------------------------------------------- /Java/LargestAmong3.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class LargestNumberExample1 3 | { 4 | public static void main(String[] args) 5 | { 6 | int a, b, c, largest, temp; 7 | //object of the Scanner class 8 | Scanner sc = new Scanner(System.in); 9 | //reading input from the user 10 | System.out.println("Enter the first number:"); 11 | a = sc.nextInt(); 12 | System.out.println("Enter the second number:"); 13 | b = sc.nextInt(); 14 | System.out.println("Enter the third number:"); 15 | c = sc.nextInt(); 16 | //comparing a and b and storing the largest number in a temp variable 17 | temp=a>b?a:b; 18 | //comparing the temp variable with c and storing the result in the variable 19 | largest=c>temp?c:temp; 20 | //prints the largest number 21 | System.out.println("The largest number is: "+largest); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/LargestSumContiguousSubarray.java: -------------------------------------------------------------------------------- 1 | class Main{ 2 | static int maxSumSubArray(int a[]){ 3 | int maxSum=0; 4 | int currSum=0; 5 | for(int i=1;imaxSum){ 8 | maxSum=currSum; 9 | } 10 | if(currSum<0){ 11 | currSum=0; 12 | } 13 | } 14 | return maxSum; 15 | } 16 | public static void main (String[] args) { 17 | int []a={-2,-3,4,-1,-2,1,5,-3}; 18 | System.out.println("Maximum contiguous sum is "+maxSumSubArray(a)); 19 | } 20 | } -------------------------------------------------------------------------------- /Java/NextGreaterElementToRight.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class NextGreaterElementToRight{ 3 | 4 | static int[] solve(int a[]){ 5 | 6 | Stack st = new Stack<>(); 7 | int nge[] = new int[a.length]; 8 | 9 | nge[a.length-1] = -1; 10 | st.push(a[a.length-1]); 11 | 12 | 13 | for(int i = a.length-2; i >=0; i--){ 14 | 15 | while(st.size() > 0 && a[i] >= st.peek()){ 16 | st.pop(); 17 | } 18 | if(st.size()> 0){ 19 | nge[i] = st.peek(); 20 | } 21 | else{ 22 | nge[i] = -1; 23 | } 24 | st.push(a[i]); 25 | } 26 | return nge; 27 | 28 | } 29 | 30 | public static void main(String[] args) { 31 | 32 | int a[] = {4,3}; 33 | 34 | int b[] = solve(a); 35 | for(int i =0; i = 0) 18 | i--; 19 | 20 | // If all characters are 'z', 21 | // append an 'a' at the end. 22 | if (i == -1) 23 | str = str + 'a'; 24 | 25 | // If there are some 26 | // non-z characters 27 | else 28 | str = str.substring(0, i) + 29 | (char)((int)(str.charAt(i)) + 1) + 30 | str.substring(i + 1); 31 | return str; 32 | } 33 | 34 | // Driver Code 35 | public static void main (String[] args) 36 | { 37 | String str = "samez"; 38 | System.out.print(nextWord(str)); 39 | } 40 | } 41 | 42 | // This code is contributed 43 | // by Kirti_Mangal 44 | -------------------------------------------------------------------------------- /Java/Palindrome.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Scanner; 3 | public class Palindrome { 4 | static void checkPalindrome(String input) { 5 | //Assuming result to be true 6 | boolean res = true; 7 | int length = input.length(); 8 | //dividing the length of the string by 2 and comparing it. 9 | for(int i=0; i<= length/2; i++) { 10 | if(input.charAt(i) != input.charAt(length-i-1)) { 11 | res = false; 12 | break; 13 | } 14 | } 15 | System.out.println(input + " is palindrome = "+res); 16 | } 17 | public static void main(String[] args) { 18 | Scanner sc = new Scanner(System.in); 19 | System.out.print("Enter your Statement: "); 20 | String str = sc.nextLine(); 21 | //function call 22 | checkPalindrome(str); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Java/PerfectNumber.java: -------------------------------------------------------------------------------- 1 | public class PerfectNumber { 2 | // Java program to check if a number is perfect or not 3 | static boolean isPerfect(int n) { 4 | // To store sum of divisors 5 | int sum = 1; 6 | 7 | // Find all divisors and add them 8 | for (int i = 2; i * i <= n; i++) { 9 | if (n % i == 0) { 10 | if (i * i != n) 11 | sum = sum + i + n / i; 12 | else 13 | sum = sum + i; 14 | } 15 | } 16 | // If sum of divisors is equal to 17 | // n, then n is a perfect number 18 | return sum == n && n != 1; 19 | } 20 | 21 | // Driver program 22 | public static void main(String[] args) { 23 | System.out.println("Below are all perfect" + "numbers till 10000"); 24 | for (int n = 2; n < 10000; n++) 25 | if (isPerfect(n)) 26 | System.out.println(n + " is a perfect number"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Java/PositiveOrNegative.java: -------------------------------------------------------------------------------- 1 | public class CheckPositiveOrNegativeExample1 { 2 | public static void main(String[] args) { 3 | //number to be check 4 | int num = 912; 5 | //checks the number is greater than 0 or not 6 | if (num > 0) { 7 | System.out.println("The number is positive."); 8 | } 9 | //checks the number is less than 0 or not 10 | else if (num < 0) { 11 | System.out.println("The number is negative."); 12 | } 13 | //executes when the above two conditions return false 14 | else { 15 | System.out.println("The number is zero."); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Java/Product-of-two-numbers.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class MultiplyExample3 { 4 | 5 | public static void main(String[] args) { 6 | 7 | Scanner scanner = new Scanner(System.in); 8 | System.out.print("Enter first number = "); 9 | double myDouble1 = scanner.nextDouble(); 10 | System.out.print("Enter second number = "); 11 | double myDouble2 = scanner.nextDouble(); 12 | scanner.close(); 13 | 14 | double result = myDouble1*myDouble2; 15 | 16 | // Displaying the multiplication result 17 | System.out.println(myDouble1 + "*" + myDouble2 + " = " + result); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Java/QuickSort.java: -------------------------------------------------------------------------------- 1 | class QuickSort { 2 | 3 | static void swap(int[] arr, int i, int j) { 4 | int temp = arr[i]; 5 | arr[i] = arr[j]; 6 | arr[j] = temp; 7 | } 8 | 9 | static int partition(int[] arr, int low, int high) { 10 | 11 | int pivot = arr[high]; 12 | int i = (low - 1); 13 | 14 | for (int j = low; j <= high - 1; j++) { 15 | if (arr[j] < pivot) { 16 | i++; 17 | swap(arr, i, j); 18 | } 19 | } 20 | swap(arr, i + 1, high); 21 | return (i + 1); 22 | } 23 | 24 | static void quickSort(int[] arr, int low, int high) { 25 | if (low < high) { 26 | int pi = partition(arr, low, high); 27 | quickSort(arr, low, pi - 1); 28 | quickSort(arr, pi + 1, high); 29 | } 30 | } 31 | 32 | static void printArray(int[] arr) { 33 | System.out.print("["); 34 | for (int j : arr) { 35 | System.out.print(j + ", "); 36 | } 37 | System.out.print("\b\b]"); 38 | } 39 | 40 | public static void main(String[] args) { 41 | int[] arr = {99, 1, 77, 66, 55, 44, 7, 22, 11, 3}; 42 | quickSort(arr, 0, arr.length - 1); 43 | printArray(arr); 44 | } 45 | } -------------------------------------------------------------------------------- /Java/RemoveDuplicate.java: -------------------------------------------------------------------------------- 1 | import java.util.regex.Matcher; 2 | import java.util.regex.Pattern; 3 | 4 | public class RegexMatches { 5 | public static void main(String args[]) { 6 | 7 | // String to be scanned to find the pattern. 8 | String line = "This order was placed for QT3000! OK?"; 9 | String pattern = "(.*)(\\d+)(.*)"; 10 | 11 | // Create a Pattern object 12 | Pattern r = Pattern.compile(pattern); 13 | 14 | // Now create matcher object. 15 | Matcher m = r.matcher(line); 16 | if (m.find()) { 17 | System.out.println("Found value: " + m.group(0)); 18 | System.out.println("Found value: " + m.group(1)); 19 | System.out.println("Found value: " + m.group(2)); 20 | } else { 21 | System.out.println("NO MATCH"); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Java/ReverseANumber.java: -------------------------------------------------------------------------------- 1 | public class ReverseNumberExample1 { 2 | public static void main(String[] args) { 3 | int number = 987654, reverse = 0; 4 | while (number != 0) { 5 | int remainder = number % 10; 6 | reverse = reverse * 10 + remainder; 7 | number = number / 10; 8 | } 9 | System.out.println("The reverse of the given number is: " + reverse); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Java/RightAlphabeticTriangle.java: -------------------------------------------------------------------------------- 1 | public class Pattern { 2 | public static void main(String[] args) 3 | { 4 | int alphabet = 65; 5 | for (int i = 0; i <= 5; i++) 6 | { 7 | for (int j = 0; j <= i; j++) 8 | { 9 | System.out.print((char) (alphabet + j) + " "); 10 | } 11 | System.out.println(); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Java/Rupee Conversion To Dollar.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class RupeeConvertionToDollar{ 4 | public static void main(String[] arr){ 5 | Scanner scan = new Scanner(System.in); 6 | System.out.println("Enter a Rupee value to convert it in Dollar value"); 7 | int rupee = scan.nextInt(); 8 | 9 | System.out.println("corresponding Doller value :"+rupee*0.0136824549); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Java/SelectionSort.java: -------------------------------------------------------------------------------- 1 | public class SelectionSort { 2 | //main function 3 | public static void main(String args[]){ 4 | int[] arr={10,35,-15,7,55,1,-22}; 5 | for(int i= arr.length-1;i>0;i--){ 6 | int a=0; 7 | for(int j=1;j<=i;j++){ 8 | if(arr[j]>arr[a]){ 9 | a=j; 10 | } 11 | } 12 | swap(arr,a,i); 13 | } 14 | print(arr); 15 | } 16 | //function for swapping the values 17 | public static void swap(int[] arr,int i,int j){ 18 | if(i==j){ 19 | return; 20 | } 21 | int temp = arr[i]; 22 | arr[i] = arr[j]; 23 | arr[j] = temp; 24 | } 25 | //print function 26 | public static void print(int[] arr){ 27 | for(int i=0;i arr[j]) 9 | min = j; 10 | int key = arr[min]; 11 | while (min > i) { 12 | arr[min] = arr[min - 1]; 13 | min--; 14 | } 15 | 16 | arr[i] = key; 17 | } 18 | print(arr); 19 | } 20 | //function to print the array 21 | public static void print(int[] arr){ 22 | for(int i=0;i= l) 15 | { 16 | int mid1 = l + (r - l) / 3; 17 | int mid2 = mid1 + (r - l) / 3; 18 | 19 | // If x is present at the mid1 20 | if (arr[mid1] == x) return mid1; 21 | 22 | // If x is present at the mid2 23 | if (arr[mid2] == x) return mid2; 24 | 25 | // If x is present in left one-third 26 | if (arr[mid1] > x) 27 | return ternarySearch(arr, l, mid1 - 1, x); 28 | 29 | // If x is present in right one-third 30 | if (arr[mid2] < x) 31 | return ternarySearch(arr, mid2 + 1, r, x); 32 | 33 | // If x is present in middle one-third 34 | return ternarySearch(arr, mid1 + 1, 35 | mid2 - 1, x); 36 | } 37 | 38 | // We reach here when element is 39 | // not present in array 40 | return -1; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Java/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | /*Tower of Hanoi is a mathematical puzzle where we have three rods (A, B, and C) and N disks. 2 | Initially, all the disks are stacked in decreasing value of diameter i.e., the smallest disk is placed on the top and they are on rod A. 3 | The objective of the puzzle is to move the entire stack to another rod (here considered C), obeying the following simple rules: 4 | -Only one disk can be moved at a time. 5 | -Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 6 | -No disk may be placed on top of a smaller disk.*/ 7 | 8 | 9 | public class TowerOfHanoi{ 10 | 11 | public static void towerHanoi(int n,char s,char h,char d) { 12 | if(n==1) { 13 | System.out.println("Move 1st disk from "+s+" to "+d); 14 | return; 15 | } 16 | 17 | towerHanoi(n-1, s, d, h); 18 | System.out.println("Move "+n+"th disk from "+s+" to "+d); 19 | towerHanoi(n-1, h, s, d); 20 | } 21 | 22 | public static void main(String[] args) { 23 | //s-start tower 24 | //h-helper tower 25 | //d-destination tower 26 | towerHanoi(4, 's','h','d'); 27 | 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Java/Trailing_zeros.java: -------------------------------------------------------------------------------- 1 | // Java program to count 2 | // trailing 0s in n! 3 | import java.io.*; 4 | 5 | class Trailing_zeros { 6 | // Function to return trailing 7 | // 0s in factorial of n 8 | static int findTrailingZeros(int n) 9 | { 10 | if (n < 0) // Negative Number Edge Case 11 | return -1; 12 | 13 | // Initialize result 14 | int count = 0; 15 | 16 | // Keep dividing n by powers 17 | // of 5 and update count 18 | for (int i = 5; n / i >= 1; i *= 5) 19 | count += n / i; 20 | 21 | return count; 22 | } 23 | 24 | 25 | public static void main(String[] args) 26 | { 27 | int n = 100; 28 | System.out.println("Count of trailing 0s in " + n 29 | + "! is " 30 | + findTrailingZeros(n)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Java/add-two-numbers.java: -------------------------------------------------------------------------------- 1 | class Main { 2 | 3 | public static void main(String[] args) { 4 | 5 | System.out.println("Enter two numbers"); 6 | int first = 10; 7 | int second = 20; 8 | 9 | System.out.println(first + " " + second); 10 | 11 | // add two numbers 12 | int sum = first + second; 13 | System.out.println("The sum is: " + sum); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Java/buildArrayFromPermutation.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] buildArray(int[] nums) { 3 | int n = nums.length; 4 | int[] ans = new int[n]; 5 | for (int i=0; i= left; i--) 29 | System.out.print(mat[bottom][i] + " "); 30 | 31 | bottom--; 32 | } 33 | 34 | if(left <= right){ 35 | for(int i = bottom; i >= top; i--) 36 | System.out.print(mat[i][left] + " "); 37 | 38 | left++; 39 | } 40 | } 41 | } 42 | 43 | public static void main(String args[]) 44 | { 45 | int arr[][] = {{1, 2, 3, 4}, 46 | {5, 6, 7, 8}, 47 | {9, 10, 11, 12}, 48 | {13, 14, 15, 16}}; 49 | 50 | printSpiral(arr, 4, 4); 51 | 52 | 53 | } 54 | 55 | } -------------------------------------------------------------------------------- /Java/sunny_number.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class SunnyNumberExample1 3 | { 4 | //driver code 5 | public static void main(String args[]) 6 | { 7 | Scanner sc = new Scanner(System.in); 8 | System.out.print("Enter a number to check: "); 9 | //reading a number from the user 10 | int N=sc.nextInt(); 11 | //calling user-defined function 12 | isSunnyNumber(N); 13 | } 14 | //function checks whether the given is a perfect square or not 15 | static boolean findPerfectSquare(double num) 16 | { 17 | //finds the square root of the ggiven number 18 | double square_root = Math.sqrt(num); 19 | //if square root is an integer 20 | return((square_root - Math.floor(square_root)) == 0); 21 | } 22 | //function that checks whether the given number is Sunny or not 23 | static void isSunnyNumber(int N) 24 | { 25 | //checks N+1 is perfect square or not 26 | if (findPerfectSquare(N + 1)) 27 | { 28 | System.out.println("The given number is a sunny number."); 29 | } 30 | //executes if N+1 is not a perfect square 31 | else 32 | { 33 | System.out.println("The given number is not a sunny number."); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /JavaScript/AddDigits.js: -------------------------------------------------------------------------------- 1 | var num=1234, rem, sum=0; 2 | while(num) 3 | { 4 | rem = num%10; 5 | sum = sum+rem; 6 | num = Math.floor(num/10); 7 | } 8 | console.log(sum); 9 | -------------------------------------------------------------------------------- /JavaScript/AddNNumbers.js: -------------------------------------------------------------------------------- 1 | const i, n=5, sum=0; 2 | arr = new Array(10, 12, 13, 15, 19); 3 | for(i=0; i<5; i++) 4 | sum = sum + arr[i]; 5 | console.log(sum); 6 | -------------------------------------------------------------------------------- /JavaScript/AddSubMulDiv.js: -------------------------------------------------------------------------------- 1 | const numOne=12, numTwo=10, res; 2 | res = numOne + numTwo; 3 | console.log("Add = " + res); 4 | res = numOne - numTwo; 5 | console.log("Subtract = " + res); 6 | res = numOne * numTwo; 7 | console.log("Multiply = " + res); 8 | res = numOne/numTwo; 9 | console.log("Divide = " + res); 10 | -------------------------------------------------------------------------------- /JavaScript/AddTwoNumbers.js: -------------------------------------------------------------------------------- 1 | cosnt numOne = 10; 2 | const numTwo = 20; 3 | const sum = numOne+numTwo; 4 | console.log(sum) 5 | -------------------------------------------------------------------------------- /JavaScript/Arearectangle.js: -------------------------------------------------------------------------------- 1 | var rectangleLength = parseInt(prompt("Enter length of rectangle:")); 2 | 3 | var rectangleWidth = parseInt(prompt("Enter width of rectangle:")); 4 | 5 | var areaOfRectangle = rectangleLength * rectangleWidth ; 6 | 7 | console.log("Area of rectangle is: " + areaOfRectangle); 8 | 9 | var circumferenceOfRectangle = 2 * (rectangleLength) + 2 * (rectangleWidth); 10 | 11 | console.log("Circumference of rectangle is: " + circumferenceOfRectangle); 12 | -------------------------------------------------------------------------------- /JavaScript/Armstrong.js: -------------------------------------------------------------------------------- 1 | 2 | const number = prompt("Enter a positive integer"); 3 | const numberOfDigits = number.length; 4 | let sum = 0; 5 | 6 | let temp = number; 7 | 8 | while (temp > 0) { 9 | 10 | let remainder = temp % 10; 11 | 12 | sum += remainder ** numberOfDigits; 13 | 14 | 15 | temp = parseInt(temp / 10); // convert float into integer 16 | } 17 | 18 | if (sum == number) { 19 | console.log(`${number} is an Armstrong number`); 20 | } 21 | else { 22 | console.log(`${number} is not an Armstrong number.`); 23 | } 24 | -------------------------------------------------------------------------------- /JavaScript/Boldd.js: -------------------------------------------------------------------------------- 1 | const str = new String("Demo Text"); 2 | document.write(str.bold()); 3 | alert(str.bold()); 4 | -------------------------------------------------------------------------------- /JavaScript/CelsiusToFahrenheit.js: -------------------------------------------------------------------------------- 1 | // program to convert celsius to fahrenheit 2 | // ask the celsius value to the user 3 | const celsius = prompt("Enter a celsius value: "); 4 | 5 | // calculate fahrenheit 6 | const fahrenheit = (celsius * 1.8) + 32 7 | 8 | // display the result 9 | console.log(`${celsius} degree celsius is equal to ${fahrenheit} degree fahrenheit.`); 10 | -------------------------------------------------------------------------------- /JavaScript/Create Random Number: -------------------------------------------------------------------------------- 1 | // program to check if a number is prime or not 2 | 3 | // take input from the user 4 | const number = parseInt(prompt("Enter a positive number: ")); 5 | let isPrime = true; 6 | 7 | // check if number is equal to 1 8 | if (number === 1) { 9 | console.log("1 is neither prime nor composite number."); 10 | } 11 | 12 | // check if number is greater than 1 13 | else if (number > 1) { 14 | 15 | // looping through 2 to number-1 16 | for (let i = 2; i < number; i++) { 17 | if (number % i == 0) { 18 | isPrime = false; 19 | break; 20 | } 21 | } 22 | 23 | if (isPrime) { 24 | console.log(`${number} is a prime number`); 25 | } else { 26 | console.log(`${number} is a not prime number`); 27 | } 28 | } 29 | 30 | // check if number is less than 1 31 | else { 32 | console.log("The number is not a prime number."); 33 | } 34 | -------------------------------------------------------------------------------- /JavaScript/DecimalToBinary.js: -------------------------------------------------------------------------------- 1 | // program to convert decimal to binary 2 | function convertToBinary(x) { 3 | let bin = 0; 4 | let rem, i = 1, step = 1; 5 | while (x != 0) { 6 | rem = x % 2; 7 | console.log( 8 | `Step ${step++}: ${x}/2, Remainder = ${rem}, Quotient = ${parseInt(x/2)}` 9 | ); 10 | x = parseInt(x / 2); 11 | bin = bin + rem * i; 12 | i = i * 10; 13 | } 14 | console.log(`Binary: ${bin}`); 15 | } 16 | 17 | // take input 18 | let number = prompt('Enter a decimal number: '); 19 | 20 | convertToBinary(number); 21 | -------------------------------------------------------------------------------- /JavaScript/Fibonacci.js: -------------------------------------------------------------------------------- 1 | // program to generate fibonacci series up to n terms 2 | 3 | // take input from the user 4 | const number = parseInt(prompt('Enter the number of terms: ')); 5 | let n1 = 0, n2 = 1, nextTerm; 6 | 7 | console.log('Fibonacci Series:'); 8 | 9 | for (let i = 1; i <= number; i++) { 10 | console.log(n1); 11 | nextTerm = n1 + n2; 12 | n1 = n2; 13 | n2 = nextTerm; 14 | } 15 | -------------------------------------------------------------------------------- /JavaScript/HelloWorld.js: -------------------------------------------------------------------------------- 1 | // Program to print string `Hello, World!` in JavaScript 2 | console.log("Hello. World!"); 3 | -------------------------------------------------------------------------------- /JavaScript/Integer.js: -------------------------------------------------------------------------------- 1 | function isInt(num) { 2 | return num % 1 === 0; 3 | } 4 | 5 | console.log(isInt(4)); // true 6 | console.log(isInt(12.2)); // false 7 | console.log(isInt(0.3)); // false 8 | -------------------------------------------------------------------------------- /JavaScript/LCMFinder.js: -------------------------------------------------------------------------------- 1 | // program to find the LCM of two integers 2 | 3 | // take input 4 | const num1 = prompt('Enter a first positive integer: '); 5 | const num2 = prompt('Enter a second positive integer: '); 6 | 7 | // higher number among number1 and number2 is stored in min 8 | let min = (num1 > num2) ? num1 : num2; 9 | 10 | // while loop 11 | while (true) { 12 | if (min % num1 == 0 && min % num2 == 0) { 13 | console.log(`The LCM of ${num1} and ${num2} is ${min}`); 14 | break; 15 | } 16 | min++; 17 | } 18 | -------------------------------------------------------------------------------- /JavaScript/MultiplicationTable.js: -------------------------------------------------------------------------------- 1 | // program to generate a multiplication table 2 | 3 | // take input from the user 4 | const number = parseInt(prompt('Enter an integer: ')); 5 | 6 | //creating a multiplication table 7 | for(let i = 1; i <= 10; i++) { 8 | 9 | // multiply i with number 10 | const result = i * number; 11 | 12 | // display the result 13 | console.log(`${number} * ${i} = ${result}`); 14 | } 15 | -------------------------------------------------------------------------------- /JavaScript/RandomNumberBetween1-10.js: -------------------------------------------------------------------------------- 1 | //Generating random number between 1-10 2 | const a = Math.floor(Math.random() * (10 - 1)) + 1; 3 | console.log(`Random value between 1 and 10 is ${a}`); 4 | -------------------------------------------------------------------------------- /JavaScript/Trappingrainwater.js: -------------------------------------------------------------------------------- 1 | // Apsara Budathoki 2 | // Trapping rain water 3 | 31 | 32 | -------------------------------------------------------------------------------- /JavaScript/addInte.js: -------------------------------------------------------------------------------- 1 | // store input numbers 2 | const num1 = parseInt(prompt('Enter the first number ')); 3 | const num2 = parseInt(prompt('Enter the second number ')); 4 | 5 | //add two numbers 6 | const sum = num1 + num2; 7 | 8 | // display the sum 9 | console.log(`The sum of ${num1} and ${num2} is ${sum}`); 10 | -------------------------------------------------------------------------------- /JavaScript/bold.js: -------------------------------------------------------------------------------- 1 | var str = new String("Demo Text"); 2 | document.write(str.bold()); 3 | alert(str.bold()); 4 | -------------------------------------------------------------------------------- /JavaScript/bubbleSort.js: -------------------------------------------------------------------------------- 1 | function bubbleSort(arr) { 2 | var len = arr.length 3 | 4 | for (var i = 0; i < len; i++) { 5 | for (var j = 0; j < len - i - 1; j++) { 6 | if (arr[j] > arr[j + 1]) { 7 | var temp = arr[j] 8 | arr[j] = arr[j + 1] 9 | arr[j + 1] = temp 10 | } 11 | } 12 | } 13 | return arr 14 | } 15 | 16 | bubbleSort([1,7,2,5,9,6,4,5,3,1,4,8]) -------------------------------------------------------------------------------- /JavaScript/dice-game/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/knchapagai/ProgrammingHub/2d277778d75fd564ef2056d0657bcc9d28a6f6da/JavaScript/dice-game/1.png -------------------------------------------------------------------------------- /JavaScript/dice-game/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/knchapagai/ProgrammingHub/2d277778d75fd564ef2056d0657bcc9d28a6f6da/JavaScript/dice-game/2.png -------------------------------------------------------------------------------- /JavaScript/dice-game/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/knchapagai/ProgrammingHub/2d277778d75fd564ef2056d0657bcc9d28a6f6da/JavaScript/dice-game/3.png -------------------------------------------------------------------------------- /JavaScript/dice-game/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/knchapagai/ProgrammingHub/2d277778d75fd564ef2056d0657bcc9d28a6f6da/JavaScript/dice-game/4.png -------------------------------------------------------------------------------- /JavaScript/dice-game/5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/knchapagai/ProgrammingHub/2d277778d75fd564ef2056d0657bcc9d28a6f6da/JavaScript/dice-game/5.png -------------------------------------------------------------------------------- /JavaScript/dice-game/6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/knchapagai/ProgrammingHub/2d277778d75fd564ef2056d0657bcc9d28a6f6da/JavaScript/dice-game/6.png -------------------------------------------------------------------------------- /JavaScript/dice-game/dice.js: -------------------------------------------------------------------------------- 1 | //Logic for generating random number 2 | 3 | function initiate() { 4 | let min = 1; 5 | let max = 6; 6 | let random = Math.floor(Math.random() * (max - min + 1)) + 1; 7 | document.getElementById("number").innerHTML = 'The nummber is ' + random; 8 | 9 | document.getElementById("dice").innerHTML = `${random}` 10 | 11 | 12 | } -------------------------------------------------------------------------------- /JavaScript/dice-game/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Dice Roll 9 | 10 | 11 | 12 | 13 |
14 |
15 | 16 |
17 | 18 |
19 | 20 | 25 |
26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /JavaScript/factorial.js: -------------------------------------------------------------------------------- 1 | function factorial(n){ 2 | let answer = 1; 3 | if (n == 0 || n == 1){ 4 | return answer; 5 | }else{ 6 | for(var i = n; i >= 1; i--){ 7 | answer = answer * i; 8 | } 9 | return answer; 10 | } 11 | } 12 | let n = 4; 13 | answer = factorial(n) 14 | console.log("The factorial of " + n + " is " + answer); 15 | -------------------------------------------------------------------------------- /JavaScript/hollowPyramid.js: -------------------------------------------------------------------------------- 1 | // Creates hollow pyramid in console using Node.js process.stdin, process.stdout 2 | // ------------------------------------- 3 | // Enter number of rows:3 4 | // -> 3! 5 | // * 6 | // * * 7 | // ***** 8 | // ------------------------------------- 9 | 10 | const readline = require('readline').createInterface({ 11 | input: process.stdin, 12 | output: process.stdout 13 | }) 14 | 15 | readline.question(`Enter number of rows:`, r => { 16 | console.log(`-> ${r}!`) 17 | var i; 18 | var j; 19 | var s; 20 | var lineBuffer = []; 21 | for(i = 1; i <= r; i++){ 22 | //for loop to put space in pyramid 23 | for (s = i; s < r; s++){ 24 | lineBuffer += " "; 25 | } 26 | //for loop to print star 27 | for(j = 1; j <= (2 * r - 1); j++){ 28 | if(i == r || j == 1 || j == 2*i - 1){ 29 | lineBuffer += "*"; 30 | }else{ 31 | lineBuffer += " "; 32 | } 33 | } 34 | lineBuffer += "\n"; 35 | } 36 | console.log(lineBuffer); 37 | readline.close() 38 | }) 39 | -------------------------------------------------------------------------------- /JavaScript/isPrime.js: -------------------------------------------------------------------------------- 1 | function isPrime(n) { 2 | if (n <= 1) { 3 | return false; 4 | } 5 | for (let i = 2; i < n/2; i++) { 6 | if (n % i == 0) { 7 | return false; 8 | } 9 | } 10 | return true; 11 | } 12 | 13 | console.log(isPrime(5)); 14 | -------------------------------------------------------------------------------- /JavaScript/program to Calculate days between two dates: -------------------------------------------------------------------------------- 1 | 2 | 3 | Calculate days by entering two dates 4 | 5 | 6 | 22 | 23 | -------------------------------------------------------------------------------- /JavaScript/random.js: -------------------------------------------------------------------------------- 1 | 2 | const min = parseInt(prompt("Enter a min value: ")); 3 | const max = parseInt(prompt("Enter a max value: ")); 4 | 5 | 6 | const a = Math.floor(Math.random() * (max - min + 1)) + min; 7 | 8 | 9 | console.log(`Random value between ${min} and ${max} is ${a}`); 10 | -------------------------------------------------------------------------------- /JavaScript/removeElement.js: -------------------------------------------------------------------------------- 1 | var removeElement = function(nums, val) { 2 | const len = nums.length; 3 | for(i = 0; i < len; i++) { 4 | if(i > nums.length - 1) { 5 | break; 6 | } 7 | if (nums[i] === val) { 8 | nums.splice(i, 1); 9 | i--; 10 | } 11 | } 12 | return nums.length; 13 | }; 14 | -------------------------------------------------------------------------------- /JavaScript/rotateImage.js: -------------------------------------------------------------------------------- 1 | const swap = function(or,oc,tr, tc){ 2 | [this[or][oc],this[tr][tc]] = [this[tr][tc],this[or][oc]]; 3 | }; 4 | let totalLevel = Math.floor(matrix.length/2); 5 | let last = matrix.length-1; 6 | let level = 0; 7 | while(level{ 2 | return a+b 3 | } 4 | 5 | console.log(addTwoNumbers(6,5)) 6 | -------------------------------------------------------------------------------- /JavaScript/throttle.js: -------------------------------------------------------------------------------- 1 | function throttle(fn, threshhold, scope) { 2 | threshhold || (threshhold = 250); 3 | var last, 4 | deferTimer; 5 | return function () { 6 | var context = scope || this; 7 | 8 | var now = +new Date, 9 | args = arguments; 10 | if (last && now < last + threshhold) { 11 | // hold on to it 12 | clearTimeout(deferTimer); 13 | deferTimer = setTimeout(function () { 14 | last = now; 15 | fn.apply(context, args); 16 | }, threshhold); 17 | } else { 18 | last = now; 19 | fn.apply(context, args); 20 | } 21 | }; 22 | } 23 | -------------------------------------------------------------------------------- /PHP/AreaOfRectangle.php: -------------------------------------------------------------------------------- 1 | /*To find area of Rectangle*/ 2 | "; 6 | ?> 7 | -------------------------------------------------------------------------------- /PHP/ArmstrongNumber.php: -------------------------------------------------------------------------------- 1 | 20 | -------------------------------------------------------------------------------- /PHP/Factorial.php: -------------------------------------------------------------------------------- 1 | =1; $x--){ 5 | $factorial = $factorial * $x; 6 | } 7 | echo "Factorial of $num is $factorial"; 8 | ?> 9 | -------------------------------------------------------------------------------- /PHP/Fibonacci.php: -------------------------------------------------------------------------------- 1 | Fibonacci series for first 12 numbers: "; 6 | echo "\n"; 7 | echo $n1.' '.$n2.' '; 8 | while ($num < 10 ){ 9 | $n3 = $n2 + $n1; 10 | echo $n3.' '; 11 | $n1 = $n2; 12 | $n2 = $n3; 13 | $num = $num + 1; 14 | ?> 15 | -------------------------------------------------------------------------------- /PHP/HeapSort.php: -------------------------------------------------------------------------------- 1 | $arr[$largest]) 10 | $largest = $l; 11 | 12 | if ($r < $N && $arr[$r] > $arr[$largest]) 13 | $largest = $r; 14 | 15 | if ($largest != $i) 16 | { 17 | $swap = $arr[$i]; 18 | $arr[$i] = $arr[$largest]; 19 | $arr[$largest] = $swap; 20 | 21 | heapify($arr, $N, $largest); 22 | } 23 | } 24 | 25 | function heapSort(&$arr, $N) 26 | { 27 | 28 | for ($i = $N / 2 - 1; $i >= 0; $i--) 29 | heapify($arr, $N, $i); 30 | 31 | for ($i = $N-1; $i > 0; $i--) 32 | { 33 | $temp = $arr[0]; 34 | $arr[0] = $arr[$i]; 35 | $arr[$i] = $temp; 36 | 37 | heapify($arr, $i, 0); 38 | } 39 | } 40 | 41 | function printArray(&$arr, $N) 42 | { 43 | for ($i = 0; $i < $N; ++$i) 44 | echo ($arr[$i]." ") ; 45 | 46 | } 47 | 48 | $arr = array(12, 11, 13, 5, 6, 7); 49 | $N = sizeof($arr)/sizeof($arr[0]); 50 | 51 | heapSort($arr, $N); 52 | 53 | echo 'Sorted array is ' . "\n"; 54 | 55 | printArray($arr , $N); 56 | 57 | ?> 58 | -------------------------------------------------------------------------------- /PHP/HelloWorld.php: -------------------------------------------------------------------------------- 1 | // Program to print string `Hello, World!` in PHP 2 | echo "Hello World"; 3 | -------------------------------------------------------------------------------- /PHP/PrimeNumber.php: -------------------------------------------------------------------------------- 1 | /* Prime Number Finder */ 2 | 19 | -------------------------------------------------------------------------------- /PHP/ReverseNumber.php: -------------------------------------------------------------------------------- 1 | 1){ 5 | $rem = $num % 10; 6 | $revnum = ($revnum * 10) + $rem; 7 | $num = ($num / 10); 8 | } 9 | echo "Reverse number of 23456 is: $revnum"; 10 | ?> 11 | -------------------------------------------------------------------------------- /PHP/gen.php: -------------------------------------------------------------------------------- 1 | function randomPassword() { 2 | 3 | $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; 4 | 5 | $pass = array(); //remember to declare $pass as an array 6 | 7 | $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache 8 | 9 | for ($i = 0; $i < 8; $i++) { 10 | 11 | $n = rand(0, $alphaLength); 12 | 13 | $pass[] = $alphabet[$n]; 14 | 15 | } 16 | 17 | return implode($pass); //turn the array into a string 18 | 19 | } 20 | -------------------------------------------------------------------------------- /PHP/redirect.php: -------------------------------------------------------------------------------- 1 | 5 | -------------------------------------------------------------------------------- /PHP/shell.php: -------------------------------------------------------------------------------- 1 | 10 | -------------------------------------------------------------------------------- /PHP/squareroot.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | "); 7 | echo(sqrt(0) . "
"); 8 | echo(sqrt(1) . "
"); 9 | echo(sqrt(9)); 10 | ?> 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Python/Activity_Selection.py: -------------------------------------------------------------------------------- 1 | def MaxActivities(s, f ): 2 | n = len(f) 3 | print ("The following activities are selected") 4 | 5 | i = 0 6 | print (i,end=' ') 7 | 8 | for j in range(1, n): 9 | 10 | if s[j] >= f[i]: 11 | print (j,end=' ') 12 | i = j 13 | 14 | 15 | s = [1 , 3 , 0 , 5 , 8 , 5] 16 | f = [2 , 4 , 6 , 7 , 9 , 9] 17 | MaxActivities(s , f) 18 | -------------------------------------------------------------------------------- /Python/Armstrongnumber.py: -------------------------------------------------------------------------------- 1 | #program to check whether the given number is Armstrong or not using a while loop 2 | num = int(input("Enter the number: ")) 3 | sum = 0 4 | n = str(num) 5 | 6 | for i in range(0, len(n)): 7 | sum+=int(n[i])**len(n) 8 | if num == sum: 9 | print("Entered number is an armstrong's number") 10 | else: 11 | print("Entered number is not an armstrong's number") 12 | 13 | -------------------------------------------------------------------------------- /Python/Battery_status_notifier.py: -------------------------------------------------------------------------------- 1 | #this program is designed to give a notification on windows laptops when battery chages completely 2 | while(True): 3 | import psutil 4 | from win10toast import ToastNotifier 5 | battery = psutil.sensors_battery() 6 | p=battery.percent 7 | power=battery.power_plugged 8 | if int(p)>=100 and power==True: 9 | n = ToastNotifier() 10 | msg="Battery Status: "+str(p)+"%\nFull charged, Remove charger to save power." 11 | n.show_toast("Battery",msg , duration = 20,) -------------------------------------------------------------------------------- /Python/Binary To Decimal: -------------------------------------------------------------------------------- 1 | print("Enter the Binary Number: ") 2 | bnum = int(input()) 3 | 4 | dnum = 0 5 | i = 1 6 | while bnum!=0: 7 | rem = bnum%10 8 | dnum = dnum + (rem*i) 9 | i = i*2 10 | bnum = int(bnum/10) 11 | 12 | print("\nEquivalent Decimal Value = ", dnum) 13 | -------------------------------------------------------------------------------- /Python/BinaryNumbers.py: -------------------------------------------------------------------------------- 1 | import re 2 | print(len(max(re.split("0+",bin(int(input().strip()))[2:])))) 3 | -------------------------------------------------------------------------------- /Python/Bubblesort.py: -------------------------------------------------------------------------------- 1 | def bubble_sort(list1): 2 | # Outer loop for traverse the entire list 3 | for i in range(0,len(list1)-1): 4 | for j in range(len(list1)-1): 5 | if(list1[j]>list1[j+1]): 6 | temp = list1[j] 7 | list1[j] = list1[j+1] 8 | list1[j+1] = temp 9 | return list1 10 | 11 | list1 = [15, 43, 38, 64, 71, 82] 12 | print("The unsorted list is: ", list1) 13 | # Calling the bubble sort function 14 | print("The sorted list is: ", bubble_sort(list1)) 15 | -------------------------------------------------------------------------------- /Python/Calculator.py: -------------------------------------------------------------------------------- 1 | # Calculator 2 | 3 | """ 4 | Sample Input: 5 | 10 + 20 + 3 * 5 - 2*15 6 | Sample Output: 7 | 15 8 | """ 9 | print (eval (input ())) 10 | -------------------------------------------------------------------------------- /Python/Count Number in List.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 4 6 | } 7 | -------------------------------------------------------------------------------- /Python/DigitalRoot.py: -------------------------------------------------------------------------------- 1 | def digital_root(n): 2 | 3 | num = str(n) 4 | total = 0 5 | root = num 6 | 7 | while len(str(root)) != 1: 8 | 9 | for i in root: 10 | total += int(i) 11 | 12 | root = str(total) 13 | 14 | total = 0 15 | 16 | return int(root) 17 | -------------------------------------------------------------------------------- /Python/Generate_Random_Number_List.py: -------------------------------------------------------------------------------- 1 | import random 2 | #Generate 5 random numbers between 10 and 30 3 | randomlist = random.sample(range(10, 30), 5) 4 | print(randomlist) 5 | -------------------------------------------------------------------------------- /Python/HelloWorld.py: -------------------------------------------------------------------------------- 1 | # Program to print string `Hello, World!` in Python 2 | print("Hello World") 3 | -------------------------------------------------------------------------------- /Python/InsertionSort.py: -------------------------------------------------------------------------------- 1 | def insertionSort(array): 2 | 3 | for step in range(1, len(array)): 4 | key = array[step] 5 | j = step - 1 6 | 7 | # Compare key with each element on the left of it until an element smaller than it is found 8 | # For descending order, change keyarray[j]. 9 | while j >= 0 and key < array[j]: 10 | array[j + 1] = array[j] 11 | j = j - 1 12 | 13 | # Place key at after the element just smaller than it. 14 | array[j + 1] = key 15 | 16 | 17 | data = [9, 5, 1, 4, 3] 18 | insertionSort(data) 19 | print('Sorted Array in Ascending Order:') 20 | print(data) 21 | -------------------------------------------------------------------------------- /Python/LeastFrequentCharacter.py: -------------------------------------------------------------------------------- 1 | # Python 3 code to demonstrate 2 | # Least Frequent Character in String 3 | # naive method 4 | 5 | # initializing string 6 | test_str = "GeeksforGeeks" 7 | 8 | # printing original string 9 | print ("The original string is : " + test_str) 10 | 11 | # using naive method to get 12 | # Least Frequent Character in String 13 | all_freq = {} 14 | for i in test_str: 15 | if i in all_freq: 16 | all_freq[i] += 1 17 | else: 18 | all_freq[i] = 1 19 | res = min(all_freq, key = all_freq.get) 20 | 21 | # printing result 22 | print ("The minimum of all characters in GeeksforGeeks is : " + str(res)) 23 | -------------------------------------------------------------------------------- /Python/LinkedListCycle.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, value, next=None): 3 | self.value = value 4 | self.next = next 5 | 6 | 7 | def find_cycle_length(head): 8 | slow, fast = head, head 9 | while fast is not None and fast.next is not None: 10 | fast = fast.next.next 11 | slow = slow.next 12 | if slow == fast: 13 | return calculate_cycle_length(slow) 14 | 15 | return 0 16 | 17 | 18 | def calculate_cycle_length(slow): 19 | current = slow 20 | cycle_length = 0 21 | while True: 22 | current = current.next 23 | cycle_length += 1 24 | if current == slow: 25 | break 26 | return cycle_length -------------------------------------------------------------------------------- /Python/Longer Contiguous Segments of Ones than Zeros.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkZeroOnes(self, s: str) -> bool: 3 | def check(num): 4 | return num=='1' 5 | def big(x,y): 6 | return x>y 7 | oc=0 8 | zc=0 9 | o=0 10 | z=0 11 | for x in s: 12 | if check(x): 13 | oc+=1 14 | if big(zc,z):z=zc 15 | zc=0 16 | else: 17 | zc+=1 18 | if big(oc,o):o=oc 19 | oc=0 20 | if big(zc,z):z=zc 21 | if big(oc,o):o=oc 22 | return big(o,z) 23 | -------------------------------------------------------------------------------- /Python/LongestCommonSubsquence.py: -------------------------------------------------------------------------------- 1 | def longestCommonSubsequence(text1: str, text2: str) -> int: 2 | n = len(text1) 3 | m = len(text2) 4 | dp = [[-1 for _ in range(m+1)] for _ in range(n+1)] 5 | def lcs(text1, text2): 6 | n = len(text1) 7 | m = len(text2) 8 | if len(text1) == 0 or len(text2) ==0: 9 | dp[n][m] =0 10 | return 0 11 | 12 | if (dp[n][m] != -1): 13 | return dp[n][m] 14 | 15 | 16 | if text1[-1] == text2[-1]: 17 | dp[n][m] = 1+ lcs(text1[:-1], text2[:-1]) 18 | return dp[n][m] 19 | 20 | else: 21 | dp[n][m]= max(lcs(text1, text2[:-1]), lcs(text1[:-1], text2)) 22 | return dp[n][m] 23 | return lcs(text1,text2) 24 | 25 | print(longestCommonSubsequence("Hello","Hell")) -------------------------------------------------------------------------------- /Python/LongestCommonSubstring.py: -------------------------------------------------------------------------------- 1 | def longestCommonSubstring(text1, text2): 2 | n = len(text1) 3 | m = len(text2) 4 | dp = [[-1 for _ in range(m+1)] for _ in range(n+1)] 5 | 6 | for i in range(n+1): 7 | for j in range(m+1): 8 | if i==0 or j==0: 9 | dp[i][j] = 0 10 | continue 11 | 12 | if text1[i-1] == text2[j-1]: 13 | dp[i][j] = 1+ dp[i-1][j-1] 14 | 15 | else: 16 | dp[i][j] = 0 17 | return dp[-1][-1] 18 | 19 | print(longestCommonSubstring("Hello", "Hello")) -------------------------------------------------------------------------------- /Python/MaximumFrequencyCharacter.py: -------------------------------------------------------------------------------- 1 | # Python 3 code to demonstrate 2 | # Maximum frequency character in String 3 | # naive method 4 | 5 | # initializing string 6 | test_str = "GeeksforGeeks" 7 | 8 | # printing original string 9 | print ("The original string is : " + test_str) 10 | 11 | # using naive method to get 12 | # Maximum frequency character in String 13 | all_freq = {} 14 | for i in test_str: 15 | if i in all_freq: 16 | all_freq[i] += 1 17 | else: 18 | all_freq[i] = 1 19 | res = max(all_freq, key = all_freq.get) 20 | 21 | # printing result 22 | print ("The maximum of all characters in GeeksforGeeks is : " + str(res)) 23 | -------------------------------------------------------------------------------- /Python/Mumbling.py: -------------------------------------------------------------------------------- 1 | def accum(s): 2 | list_word = list(s) 3 | gen_list = [] 4 | 5 | for i in range(len(list_word)): 6 | gen_list.append(list_word[i] * (i + 1)) 7 | 8 | output_string = "" 9 | 10 | for word in gen_list: 11 | if len(word) != len(s): 12 | output_string += "{}-".format(word) 13 | else: 14 | output_string += "{}".format(word) 15 | 16 | return output_string.title() 17 | -------------------------------------------------------------------------------- /Python/NoRepeatSubstring.py: -------------------------------------------------------------------------------- 1 | def non_repeat_substring(str): 2 | window_start = 0 3 | max_length = 0 4 | char_index_map = {} 5 | 6 | for window_end in range(len(str)): 7 | right_char = str[window_end] 8 | if right_char in char_index_map: 9 | window_start = max(window_start, char_index_map[right_char] + 1) 10 | 11 | char_index_map[right_char] = window_end 12 | max_length = max(max_length, window_end - window_start + 1) 13 | return max_length 14 | -------------------------------------------------------------------------------- /Python/Num2Words.py: -------------------------------------------------------------------------------- 1 | one = [ "", "one ", "two ", "three ", "four ", 2 | "five ", "six ", "seven ", "eight ", 3 | "nine ", "ten ", "eleven ", "twelve ", 4 | "thirteen ", "fourteen ", "fifteen ", 5 | "sixteen ", "seventeen ", "eighteen ", 6 | "nineteen "]; 7 | 8 | ten = [ "", "", "twenty ", "thirty ", "forty ", 9 | "fifty ", "sixty ", "seventy ", "eighty ", 10 | "ninety "]; 11 | def numToWords(n, s): 12 | 13 | str = ""; 14 | 15 | 16 | if (n > 19): 17 | str += ten[n // 10] + one[n % 10]; 18 | else: 19 | str += one[n]; 20 | if (n): 21 | str += s; 22 | 23 | return str; 24 | 25 | def convertToWords(n): 26 | 27 | 28 | out = ""; 29 | 30 | 31 | 32 | 33 | out += numToWords(((n // 100) % 10), 34 | "hundred "); 35 | 36 | if (n > 100 and n % 100): 37 | out += "and "; 38 | 39 | 40 | out += numToWords((n % 100), ""); 41 | 42 | return out; 43 | 44 | n = int(input("enter any number between 0 and 999: ")) 45 | print(convertToWords(n)) 46 | -------------------------------------------------------------------------------- /Python/PermutationsIterative.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def find_permutations(nums): 4 | numsLength = len(nums) 5 | result = [] 6 | permutations = deque() 7 | permutations.append([]) 8 | for currentNumber in nums: 9 | n = len(permutations) 10 | for _ in range(n): 11 | oldPermutation = permutations.popleft() 12 | for j in range(len(oldPermutation)+1): 13 | newPermutation = list(oldPermutation) 14 | newPermutation.insert(j, currentNumber) 15 | if len(newPermutation) == numsLength: 16 | result.append(newPermutation) 17 | else: 18 | permutations.append(newPermutation) 19 | 20 | return result -------------------------------------------------------------------------------- /Python/Python program to display calendar.py: -------------------------------------------------------------------------------- 1 | import calendar 2 | # Enter the month and year 3 | yy = int(input("Enter year: ")) 4 | mm = int(input("Enter month: ")) 5 | 6 | # display the calendar 7 | print(calendar.month(yy,mm)) 8 | -------------------------------------------------------------------------------- /Python/QuickSort.py: -------------------------------------------------------------------------------- 1 | def quickSort(myList, start, end): 2 | if start < end: 3 | pivot = partition(myList, start, end) 4 | quickSort(myList, start, pivot-1) 5 | quickSort(myList, pivot+1, end) 6 | return myList 7 | 8 | 9 | def partition(myList, start, end): 10 | pivot = myList[start] 11 | left = start+1 12 | right = end 13 | done = False 14 | while not done: 15 | while left <= right and myList[left] <= pivot: 16 | left = left + 1 17 | while myList[right] >= pivot and right >=left: 18 | right = right -1 19 | if right < left: 20 | done= True 21 | else: 22 | temp=myList[left] 23 | myList[left]=myList[right] 24 | myList[right]=temp 25 | temp=myList[start] 26 | myList[start]=myList[right] 27 | myList[right]=temp 28 | return right 29 | -------------------------------------------------------------------------------- /Python/RemoveDuplicateCharacter-2.py: -------------------------------------------------------------------------------- 1 | def removeDuplicate(str): 2 | s=set(str) 3 | s="".join(s) 4 | print("Without Order:",s) 5 | t="" 6 | for i in str: 7 | if(i in t): 8 | pass 9 | else: 10 | t=t+i 11 | print("With Order:",t) 12 | 13 | str="geeksforgeeks" 14 | removeDuplicate(str) 15 | -------------------------------------------------------------------------------- /Python/RemoveDuplicateCharacter.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | # Function to remove all duplicates from string 4 | # and order does not matter 5 | def removeDupWithoutOrder(str): 6 | 7 | # set() --> A Set is an unordered collection 8 | # data type that is iterable, mutable, 9 | # and has no duplicate elements. 10 | # "".join() --> It joins two adjacent elements in 11 | # iterable with any symbol defined in 12 | # "" ( double quotes ) and returns a 13 | # single string 14 | return "".join(set(str)) 15 | 16 | # Function to remove all duplicates from string 17 | # and keep the order of characters same 18 | def removeDupWithOrder(str): 19 | return "".join(OrderedDict.fromkeys(str)) 20 | 21 | # Driver program 22 | if __name__ == "__main__": 23 | str = "geeksforgeeks" 24 | print ("Without Order = ",removeDupWithoutOrder(str)) 25 | print ("With Order = ",removeDupWithOrder(str)) 26 | -------------------------------------------------------------------------------- /Python/SelectionSort.py: -------------------------------------------------------------------------------- 1 | def selectionSort(array, size): 2 | 3 | for step in range(size): 4 | min_idx = step 5 | 6 | for i in range(step + 1, size): 7 | 8 | # to sort in descending order, change > to < in this line 9 | # select the minimum element in each loop 10 | if array[i] < array[min_idx]: 11 | min_idx = i 12 | 13 | # put min at the correct position 14 | (array[step], array[min_idx]) = (array[min_idx], array[step]) 15 | 16 | 17 | data = [-2, 45, 0, 11, -9] 18 | size = len(data) 19 | selectionSort(data, size) 20 | print('Sorted Array in Ascending Order:') 21 | print(data) 22 | -------------------------------------------------------------------------------- /Python/ShellSort.py: -------------------------------------------------------------------------------- 1 | # Python3 program for implementation of Shell Sort 2 | 3 | def shellSort(arr): 4 | gap = len(arr) // 2 # initialize the gap 5 | 6 | while gap > 0: 7 | i = 0 8 | j = gap 9 | 10 | # check the array in from left to right 11 | # till the last possible index of j 12 | while j < len(arr): 13 | 14 | if arr[i] >arr[j]: 15 | arr[i],arr[j] = arr[j],arr[i] 16 | 17 | i += 1 18 | j += 1 19 | 20 | # now, we look back from ith index to the left 21 | # we swap the values which are not in the right order. 22 | k = i 23 | while k - gap > -1: 24 | 25 | if arr[k - gap] > arr[k]: 26 | arr[k-gap],arr[k] = arr[k],arr[k-gap] 27 | k -= 1 28 | 29 | gap //= 2 30 | 31 | 32 | # driver to check the code 33 | arr2 = [12, 34, 54, 2, 3] 34 | print("input array:",arr2) 35 | 36 | shellSort(arr2) 37 | print("sorted array",arr2) 38 | 39 | # This code is contributed by Mohd Mehraj 40 | -------------------------------------------------------------------------------- /Python/SimpleCalculator.py: -------------------------------------------------------------------------------- 1 | # Simple calculator 2 | input_list = input().split() 3 | 4 | if len(input_list) == 2: 5 | try: 6 | a, b = map(int, input_list) 7 | 8 | print("{} + {} = {}".format(a, b, a+b)) 9 | print("{} - {} = {}".format(a, b, a-b)) 10 | print("{} * {} = {}".format(a, b, a*b)) 11 | 12 | if b != 0: 13 | print("{} / {} = {}".format(a, b, a/b)) 14 | else: 15 | print("Division by zero is not possible.".format(a, b)) 16 | 17 | except: 18 | print("Please input numeric values. Try again.") 19 | 20 | else: 21 | print("Plese input two numbers separated by space. Try again.") 22 | 23 | -------------------------------------------------------------------------------- /Python/Simple_interest.py: -------------------------------------------------------------------------------- 1 | principal = float(input('Enter the principle amount: ')) 2 | 3 | time = float(input('Enter the time: ')) 4 | 5 | rate = float(input('Enter the rate: ')) 6 | 7 | simple_interest = (principal*time*rate)/100 8 | 9 | print("Simple interest is:", simple_interest) 10 | -------------------------------------------------------------------------------- /Python/SnakeCaseToPascalCase.py: -------------------------------------------------------------------------------- 1 | # Python3 code to demonstrate working of 2 | # Convert Snake case to Pascal case 3 | # Using title() + replace() 4 | 5 | # initializing string 6 | test_str = 'geeksforgeeks_is_best' 7 | 8 | # printing original string 9 | print("The original string is : " + test_str) 10 | 11 | # Convert Snake case to Pascal case 12 | # Using title() + replace() 13 | res = test_str.replace("_", " ").title().replace(" ", "") 14 | 15 | # printing result 16 | print("The String after changing case : " + str(res)) 17 | -------------------------------------------------------------------------------- /Python/TowerOfHanoi.py: -------------------------------------------------------------------------------- 1 | # Python function for the problem of Tower of Hanoi 2 | 3 | def TowerOfHanoi(n , from_rod, to_rod, aux_rod): 4 | if n == 1: 5 | print "Move disk 1 from rod",from_rod,"to rod",to_rod 6 | return 7 | TowerOfHanoi(n-1, from_rod, aux_rod, to_rod) 8 | print "Move disk",n,"from rod",from_rod,"to rod",to_rod 9 | TowerOfHanoi(n-1, aux_rod, to_rod, from_rod) 10 | 11 | # driver code 12 | n = 4 13 | TowerOfHanoi(n, 'a', 'c', 'b') 14 | 15 | #contributed by AnushkaGarg26 -------------------------------------------------------------------------------- /Python/Virus_graphic.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | t=turtle.Turtle() 4 | s=turtle.Screen() 5 | s.bgcolor("black") 6 | t.pencolor("blue") 7 | a=0 8 | b=0 9 | t.speed() 10 | t.penup() 11 | t.goto(0,200) 12 | t.pendown() 13 | 14 | while True: 15 | t.forward(a) 16 | t.right(b) 17 | a+=3 18 | b+=1 19 | if(b==210): 20 | break 21 | t.hideturtle() 22 | -------------------------------------------------------------------------------- /Python/add-two-numbers.py: -------------------------------------------------------------------------------- 1 | a = int(input("enter first number: ")) 2 | b = int(input("enter second number: ")) 3 | 4 | sum = a + b 5 | 6 | print("sum:", sum) 7 | -------------------------------------------------------------------------------- /Python/addingTw.py: -------------------------------------------------------------------------------- 1 | num1 = int(input('any number')) 2 | num2 = int(input('any number')) 3 | print(sum(num1,num2)) 4 | -------------------------------------------------------------------------------- /Python/addnumber.py: -------------------------------------------------------------------------------- 1 | num1 = int(input('any number')) 2 | num2 = int(input('any number')) 3 | print(sum(num1,num2)) 4 | -------------------------------------------------------------------------------- /Python/app.py: -------------------------------------------------------------------------------- 1 | import json 2 | from difflib import get_close_matches 3 | 4 | data = json.load(open("data.json")) 5 | 6 | def translate(w): 7 | w = w.lower() 8 | if w in data: 9 | return data[w] 10 | elif len(get_close_matches(w, data.keys())) > 0: 11 | yn = input("Did you mean %s instead? Enter Y if yes, or N if no: " % get_close_matches(w, data.keys())[0]) 12 | if yn == "Y": 13 | return data[get_close_matches(w, data.keys())[0]] 14 | elif yn == "N": 15 | return "The word doesn't exist. Please double check it." 16 | else: 17 | return "We didn't understand your entry." 18 | else: 19 | return "The word doesn't exist. Please double check it." 20 | 21 | word = input("Enter word: ") 22 | output = translate(word) 23 | if type(output) == list: 24 | for item in output: 25 | print(item) 26 | else: 27 | print(output) 28 | -------------------------------------------------------------------------------- /Python/armstrong.py: -------------------------------------------------------------------------------- 1 | num = int(input("Enter a number: ")) 2 | 3 | sum = 0 4 | 5 | temp = num 6 | while temp > 0: 7 | digit = temp % 10 8 | sum += digit ** 3 9 | temp //= 10 10 | 11 | if num == sum: 12 | print(num,"is an Armstrong number") 13 | else: 14 | print(num,"is not an Armstrong number") 15 | -------------------------------------------------------------------------------- /Python/automorphic.py: -------------------------------------------------------------------------------- 1 | def isAutomorphic(N) : 2 | sq = N * N 3 | while (N > 0) : 4 | if (N % 10 != sq % 10) : 5 | return False 6 | N /= 10 7 | sq /= 10 8 | else: 9 | return True 10 | N = int(input("Enter the number:")) 11 | if isAutomorphic(N) : 12 | print ("Automorphic") 13 | else : 14 | print ("Not Automorphic") 15 | -------------------------------------------------------------------------------- /Python/binarySearch.py: -------------------------------------------------------------------------------- 1 | # Python3 Program for recursive binary search. 2 | def binarySearch(arr, l, r, x): 3 | 4 | if r >= l: 5 | 6 | mid = l + (r - l) // 2 7 | 8 | if arr[mid] == x: 9 | return mid 10 | elif arr[mid] > x: 11 | return binarySearch(arr, l, mid-1, x) 12 | 13 | else: 14 | return binarySearch(arr, mid + 1, r, x) 15 | 16 | else: 17 | 18 | return -1 19 | 20 | 21 | 22 | arr = [2, 3, 4, 10, 40] 23 | x = 10 24 | 25 | # Function call 26 | result = binarySearch(arr, 0, len(arr)-1, x) 27 | 28 | if result != -1: 29 | print("Element is present at index % d" % result) 30 | else: 31 | print("Element is not present in array") -------------------------------------------------------------------------------- /Python/dec2hex.py: -------------------------------------------------------------------------------- 1 | print("Enter the Decimal Number: ") 2 | decnum = int(input()) 3 | 4 | i = 0 5 | hexdecnum = [] 6 | while decnum!=0: 7 | rem = decnum % 16 8 | if rem<10: 9 | rem = rem+48 10 | else: 11 | rem = rem+55 12 | rem = chr(rem) 13 | hexdecnum.insert(i, rem) 14 | i = i+1 15 | decnum = int(decnum / 16) 16 | 17 | print("\nEquivalent Hexadecimal Value is: ") 18 | i = i-1 19 | while i>=0: 20 | print(end=hexdecnum[i]) 21 | i = i-1 22 | print() 23 | -------------------------------------------------------------------------------- /Python/email-sending-script.py: -------------------------------------------------------------------------------- 1 | import smtplib, ssl 2 | 3 | port = 587 # For starttls 4 | smtp_server = "smtp.gmail.com" 5 | sender_email = input("Enter Your Email : ") 6 | receiver_email = input("Enter reciever email : ") 7 | password = input("Type your password and press enter:") 8 | content = input("Enter the body of the mail : ") 9 | message = f'"""\ 10 | Subject: Hi there 11 | {content} 12 | This message is sent from Python."""' 13 | 14 | context = ssl.create_default_context() 15 | with smtplib.SMTP(smtp_server, port) as server: 16 | server.ehlo() # Can be omitted 17 | server.starttls(context=context) 18 | server.ehlo() # Can be omitted 19 | server.login(sender_email, password) 20 | server.sendmail(sender_email, receiver_email, message) 21 | -------------------------------------------------------------------------------- /Python/expertSetter.py: -------------------------------------------------------------------------------- 1 | #loop for test cases 2 | cases = int(input()) 3 | 4 | for test in range(cases): 5 | x , y = input().split() 6 | x = int(x) 7 | y = int(y) 8 | 9 | if ( y/x ) < 0.5 : 10 | print("No") 11 | else : 12 | print("Yes") 13 | -------------------------------------------------------------------------------- /Python/expertSetterNew.py: -------------------------------------------------------------------------------- 1 | #loop for test cases 2 | cases = int(input()) 3 | 4 | for test in range(cases): 5 | x , y = input().split() 6 | x = int(x) 7 | y = int(y) 8 | 9 | if ( y/x ) < 0.5 : 10 | print("No") 11 | else : 12 | print("Yes") 13 | -------------------------------------------------------------------------------- /Python/fizzbuzz.py: -------------------------------------------------------------------------------- 1 | # Write a short program that prints each number from 1 to 100 on a new line. 2 | # For each multiple of 3, print "Fizz" instead of the number. 3 | # For each multiple of 5, print "Buzz" instead of the number. 4 | # For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number. 5 | 6 | def fizzbuzz(limit: int): 7 | fizzbuzz_list = [] 8 | 9 | for num in range(1, limit + 1): 10 | if num % 15 == 0: 11 | fizzbuzz_list.append("FIZZBUZZ") 12 | elif num % 5 == 0: 13 | fizzbuzz_list.append("BUZZ") 14 | elif num % 3 == 0: 15 | fizzbuzz_list.append("FIZZ") 16 | else: 17 | fizzbuzz_list.append(num) 18 | 19 | return fizzbuzz_list 20 | 21 | print(fizzbuzz(20)) 22 | -------------------------------------------------------------------------------- /Python/get_local_ip.py: -------------------------------------------------------------------------------- 1 | import socket 2 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 3 | s.connect(('8.8.8.8', 1)) # connect() for UDP doesn't send packets 4 | local_ip_address = s.getsockname()[0] 5 | print(local_ip_address) -------------------------------------------------------------------------------- /Python/grade.py: -------------------------------------------------------------------------------- 1 | print("Enter the marks of five subjects::") 2 | 3 | subject_1 = float (input ()) 4 | subject_2 = float (input ()) 5 | subject_3 = float (input ()) 6 | subject_4 = float (input ()) 7 | subject_5 = float (input ()) 8 | 9 | total, average, percentage, grade = None, None, None, None 10 | 11 | # It will calculate the Total, Average and Percentage 12 | total = subject_1 + subject_2 + subject_3 + subject_4 + subject_5 13 | average = total / 5.0 14 | percentage = (total / 500.0) * 100 15 | 16 | if average >= 90: 17 | grade = 'A' 18 | elif average >= 80 and average < 90: 19 | grade = 'B' 20 | elif average >= 70 and average < 80: 21 | grade = 'C' 22 | elif average >= 60 and average < 70: 23 | grade = 'D' 24 | else: 25 | grade = 'E' 26 | 27 | # It will produce the final output 28 | print ("\nThe Total marks is: \t", total, "/ 500.00") 29 | print ("\nThe Average marks is: \t", average) 30 | print ("\nThe Percentage is: \t", percentage, "%") 31 | print ("\nThe Grade is: \t", grade) 32 | -------------------------------------------------------------------------------- /Python/hcf-of-two-number.py: -------------------------------------------------------------------------------- 1 | def find_hcf(a,b): 2 | while(b): 3 | a, a = b, a % b 4 | return a 5 | a = int(input (" Enter the first number: ") ) 6 | b = int(input (" Enter the second number: ")) 7 | num = find_hcf(a, b) 8 | print(" The HCF of two number a and b is ") 9 | print(num) 10 | -------------------------------------------------------------------------------- /Python/heartpattern.py: -------------------------------------------------------------------------------- 1 | n = 6 2 | for row in range(0,n): 3 | for col in range(0,n+1): 4 | if(row==0 and col%3!=0) or (row==1 and col%3==0) or (row-col==2) or (row+col==8): 5 | print('*',end='') 6 | else: 7 | print(' ',end='') 8 | 9 | print() -------------------------------------------------------------------------------- /Python/kadane's_algo.py: -------------------------------------------------------------------------------- 1 | # User function Template for python3 2 | 3 | class Solution: 4 | ##Complete this function 5 | # Function to find the sum of contiguous subarray with maximum sum. 6 | def maxSubArraySum(self, arr, N): 7 | ##Your code here 8 | ma = -100000000 9 | su = 0 10 | for i in arr: 11 | su += i 12 | if ma < su: 13 | ma = su 14 | if su < 0: 15 | su = 0 16 | 17 | return ma 18 | 19 | 20 | # { 21 | # Driver Code Starts 22 | # Initial Template for Python 3 23 | 24 | import math 25 | 26 | 27 | def main(): 28 | T = int(input()) 29 | while (T > 0): 30 | n = int(input()) 31 | 32 | arr = [int(x) for x in input().strip().split()] 33 | 34 | ob = Solution() 35 | 36 | print(ob.maxSubArraySum(arr, n)) 37 | 38 | T -= 1 39 | 40 | 41 | if __name__ == "__main__": 42 | main() 43 | # } Driver Code Ends -------------------------------------------------------------------------------- /Python/knapsackRecursive.py: -------------------------------------------------------------------------------- 1 | def Knapsack(values,weights, capacity): 2 | n = len(values) 3 | if n==0 or capacity==0: 4 | return 0 5 | a = 0 6 | if weights[n-1] <= capacity: 7 | a = values[n-1] + Knapsack(values[:n-1],weights[:n-1],capacity-weights[n-1]) 8 | 9 | b = Knapsack(values[:n-1],weights[:n-1],capacity) 10 | 11 | return max(a,b) 12 | 13 | print(Knapsack([1,6,10,16],[1,2,3,5], 10)) -------------------------------------------------------------------------------- /Python/main.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | url = input("Which website do you want to check the status of?\n") 4 | page = requests.get(url) 5 | print (page.status_code) -------------------------------------------------------------------------------- /Python/new_line.py: -------------------------------------------------------------------------------- 1 | # import modules 2 | from bokeh.plotting import figure, output_notebook, show 3 | 4 | # output to notebook 5 | output_notebook() 6 | 7 | # create figure 8 | p = figure(plot_width = 400, plot_height = 400) 9 | 10 | # add a line renderer 11 | p.line([1, 2, 3, 4, 5], [3, 1, 2, 6, 5], 12 | line_width = 2, color = "green") 13 | 14 | # show the results 15 | show(p) 16 | -------------------------------------------------------------------------------- /Python/numeroprimo.py: -------------------------------------------------------------------------------- 1 | n=int(input("Digite o numero: ")) 2 | t=2 3 | s=1 4 | while t<=n: 5 | r=n%t 6 | while s<=t: 7 | q=s*t 8 | if q==n or (r==0 and t!=n): 9 | primo= False 10 | else: 11 | primo= True 12 | t+=1 13 | s+=1 14 | 15 | print("É primo?", primo) 16 | -------------------------------------------------------------------------------- /Python/oddPairSum.py: -------------------------------------------------------------------------------- 1 | noOfCases = int(input()) 2 | 3 | for testcase in range(noOfCases) : 4 | 5 | arr = input().split() 6 | 7 | checkingVal = 0 8 | for i in range(len(arr)-1) : 9 | for j in range( i+1 , len(arr) ) : 10 | 11 | if ( int(arr[i]) + int(arr[j]) ) % 2 == 1 : 12 | checkingVal = 1 13 | 14 | if checkingVal == 1 : 15 | print("YES") 16 | else : 17 | print("NO") 18 | -------------------------------------------------------------------------------- /Python/palindrome.py: -------------------------------------------------------------------------------- 1 | str=input("Enter the string:") 2 | rev="" 3 | l=len(str) 4 | for i in range(l-1,-1,-1): 5 | rev=rev+str[i] 6 | if rev==str: 7 | print ("Palindrome") 8 | else: 9 | print ("not palindrome") 10 | -------------------------------------------------------------------------------- /Python/paperCut.py: -------------------------------------------------------------------------------- 1 | #problem : how many squares of size k*k can be cut from n*n size board 2 | 3 | no_of_case = int(input()) 4 | 5 | #test case loop 6 | for testcase in range(no_of_case) : 7 | 8 | #taking input 9 | n , k = input().split() 10 | n = int(n) 11 | k = int(k) 12 | 13 | #Logic : quotient of n/k ; then squared is result 14 | no_of_cut_square = ( n//k ) ** 2 15 | print( no_of_cut_square) 16 | -------------------------------------------------------------------------------- /Python/paperCutNew.py: -------------------------------------------------------------------------------- 1 | #problem : how many squares of size k*k can be cut from n*n size board 2 | 3 | no_of_case = int(input()) 4 | 5 | #test case loop 6 | for testcase in range(no_of_case) : 7 | 8 | #taking input 9 | n , k = input().split() 10 | n = int(n) 11 | k = int(k) 12 | 13 | #Logic : quotient of n/k ; then squared is result 14 | no_of_cut_square = ( n//k ) ** 2 15 | print( no_of_cut_square) 16 | -------------------------------------------------------------------------------- /Python/passwordmaker.py: -------------------------------------------------------------------------------- 1 | # importing libraries 2 | import random 3 | import string 4 | 5 | # print welcome message 6 | print('Welcome to Password Maker!') 7 | adjectives = ['sleepy', 'slow', 'smelly', 'wet', 'fat', 'red','orange', 'yellow', 'green','blue', 'purple', 'fluffy','white', 'proud', 'brave'] 8 | nouns = ['apple', 'dinosaur', 'ball','toaster', 'goat', 'dragon','hammer', 'duck', 'panda', 'cat','wolf'] 9 | 10 | # main function 11 | while True: 12 | adjective = random.choice(adjectives) 13 | noun = random.choice(nouns) 14 | number = random.randrange(0, 100) 15 | special_char = random.choice(string.punctuation) 16 | password = adjective + noun + special_char + str(number) 17 | print(f"Your new password is: {password}") 18 | 19 | option = input('Would you like another password? Type y or n: ') 20 | if option =='n': 21 | break 22 | -------------------------------------------------------------------------------- /Python/prime-number.py: -------------------------------------------------------------------------------- 1 | if(n > 1): 2 | for k in range(2, int(sqrt(n)) + 1): 3 | if (n % k == 0): 4 | flag = 1 5 | break 6 | if (flag == 0): 7 | print(n," is a Prime Number!") 8 | else: 9 | print(n," is Not a Prime Number!") 10 | else: 11 | print(n," is Not a Prime Number!") 12 | -------------------------------------------------------------------------------- /Python/prime.py: -------------------------------------------------------------------------------- 1 | #importing libraries 2 | import math 3 | #function to check whether number is prime or not 4 | def checkprime(n): 5 | #checking divisibility of n by all numbers in range (2,int(sqrt(n)))) 6 | for i in range(2,int(math.sqrt(n))): 7 | if(n%i==0): 8 | return ("Not prime") 9 | return "prime" 10 | 11 | n=int(input("Interger to check whether it's prime or not:")) 12 | print(checkprime(n)) 13 | -------------------------------------------------------------------------------- /Python/pyramid.py: -------------------------------------------------------------------------------- 1 | 2 | row = int(input('Enter number of rows required: ')) 3 | 4 | for i in range(row): 5 | for j in range(row-i): 6 | print(' ', end='') 7 | 8 | for j in range(2*i+1): 9 | if j==0 or j==2*i or i==row-1: 10 | print('*',end='') 11 | else: 12 | print(' ', end='') 13 | print() 14 | -------------------------------------------------------------------------------- /Python/quiz.py: -------------------------------------------------------------------------------- 1 | print('Welcome to AskPython Quiz') 2 | answer=input('Are you ready to play the Quiz ? (yes/no) :') 3 | score=0 4 | total_questions=3 5 | 6 | if answer.lower()=='yes': 7 | answer=input('Question 1: What is your Favourite programming language?') 8 | if answer.lower()=='python': 9 | score += 1 10 | print('correct') 11 | else: 12 | print('Wrong Answer :(') 13 | 14 | 15 | answer=input('Question 2: Do you follow any author on AskPython? ') 16 | if answer.lower()=='yes': 17 | score += 1 18 | print('correct') 19 | else: 20 | print('Wrong Answer :(') 21 | 22 | answer=input('Question 3: What is the name of your favourite website for learning Python?') 23 | if answer.lower()=='askpython': 24 | score += 1 25 | print('correct') 26 | else: 27 | print('Wrong Answer :(') 28 | 29 | print('Thankyou for Playing this small quiz game, you attempted',score,"questions correctly!") 30 | mark=(score/total_questions)*100 31 | print('Marks obtained:',mark) 32 | print('BYE!') 33 | -------------------------------------------------------------------------------- /Python/radixsort.py: -------------------------------------------------------------------------------- 1 | def radix_sort(nums): 2 | RADIX = 10 3 | placement = 1 4 | max_digit = max(nums) 5 | 6 | while placement < max_digit: 7 | buckets = [list() for _ in range( RADIX )] 8 | for i in nums: 9 | tmp = int((i / placement) % RADIX) 10 | buckets[tmp].append(i) 11 | a = 0 12 | for b in range( RADIX ): 13 | buck = buckets[b] 14 | for i in buck: 15 | nums[a] = i 16 | a += 1 17 | placement *= RADIX 18 | return nums 19 | user_input = input("Input numbers separated by a space:\n").strip() 20 | nums = [int(item) for item in user_input.split(' ')] 21 | print(radix_sort(nums)) 22 | -------------------------------------------------------------------------------- /Python/recordHoldKeyboard.py: -------------------------------------------------------------------------------- 1 | import time 2 | import keyboard 3 | #if import error pip install keyboard 4 | 5 | print("Starting App") 6 | print("[INFO] Test Hold and Release Keyboard X") 7 | print("[ESC] To Break App") 8 | 9 | while True: 10 | if(keyboard.is_pressed('x')): 11 | print("Start Reading Time Keyboard Hold and Release X") 12 | 13 | start=time.time() 14 | while(keyboard.is_pressed('x')): 15 | print("Button X is hold") 16 | end=time.time() 17 | 18 | print("Hold Time : ",end-start) 19 | if(keyboard.is_pressed('esc')): 20 | break 21 | -------------------------------------------------------------------------------- /Python/scheduling.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | # In[3]: 5 | 6 | 7 | class Request: 8 | def __init__(self,input_name,input_start,input_end): 9 | self.name=input_name 10 | self.start=input_start 11 | self.end=input_end 12 | r1=Request('A',2,3) 13 | r2=Request('B',2,4) 14 | r3=Request('C',1,4) 15 | r4=Request('D',3,6) 16 | r5=Request('E',6,7) 17 | r6=Request('F',5,8) 18 | r7=Request('G',7,9) 19 | requests=[r1,r2,r3,r4,r5,r6,r7] 20 | scheduled_requests = [] 21 | while len(requests)>0: 22 | earliest=requests[0] 23 | earliest_end=requests[0].end 24 | for request in requests: 25 | if request.end= left and t[j] > key: 9 | t[j+1] = t[j] 10 | j -= 1 11 | t[j+1] = key 12 | return t 13 | 14 | def tim_sort(t): 15 | min_run = 32 16 | n = len(t) 17 | 18 | for i in range(0,n,min_run): 19 | insertion_sort(t,i,min((i+min_run-1), (n-1))) 20 | 21 | size = min_run 22 | while size < n: 23 | for s in range(0,n, size*2): 24 | mid = s+ size-1 25 | end = min((s+size*2-1), (n-1)) 26 | 27 | merged = merged(left=t[s:mid+1], right=t[mid+1:end+1]) 28 | 29 | t[s:s+len(merged)] = merged 30 | 31 | size *= 2 32 | return t 33 | 34 | l1 = [34,10,64,51,32,21] 35 | res = tim_sort(l1) 36 | print(res) -------------------------------------------------------------------------------- /Python/video_to_images.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | image_folder = '../images' 4 | video_name = '../test.mp4' 5 | 6 | vidcap = cv2.VideoCapture(video_name) 7 | success, image = vidcap.read() 8 | count = 1 9 | 10 | while success: 11 | cv2.imwrite(image_folder + "\\%d.jpg" % count, image) # save frame as JPEG file 12 | success, image = vidcap.read() 13 | print('Read a new frame: ', success) 14 | count += 1 -------------------------------------------------------------------------------- /Ruby/Area of rectangle.rb: -------------------------------------------------------------------------------- 1 | # input length and breadth, and 2 | # convert them to float value 3 | puts "Enter length:" 4 | l=gets.chomp.to_f 5 | puts "Enter width:" 6 | w=gets.chomp.to_f 7 | 8 | # calculating area 9 | area=l*w 10 | 11 | # printing the result 12 | puts "Area of Rectangle is #{area}" 13 | -------------------------------------------------------------------------------- /Ruby/Fibonacci.rb: -------------------------------------------------------------------------------- 1 | =begin 2 | Ruby program to print Fibonacci series 3 | without recursion 4 | =end 5 | 6 | first=0 7 | second=1 8 | nextterm=0 9 | puts "Enter the number of terms:-" 10 | n=gets.chomp.to_i 11 | puts "The first #{n} terms of Fibonacci series are:-" 12 | c=1 13 | while(c<=n+1) 14 | if(c<=1) 15 | nextterm=c 16 | else 17 | puts nextterm 18 | nextterm=first+second 19 | first=second 20 | second=nextterm 21 | end 22 | c+=1 23 | end 24 | -------------------------------------------------------------------------------- /Ruby/HelloWorld.rb: -------------------------------------------------------------------------------- 1 | # Program to print string `Hello, World! in Ruby` 2 | puts 'Hello, World!' 3 | -------------------------------------------------------------------------------- /Ruby/Rbinary.rb: -------------------------------------------------------------------------------- 1 | convert_to_binary <- function(decnum) { 2 | if(decnum > 1) { 3 | convert_to_binary(as.integer(decnum/2)) 4 | } 5 | cat(decnum %% 2) 6 | } 7 | convert_to_binary(52) 8 | -------------------------------------------------------------------------------- /Ruby/To find out if given an array of unique numbers, there is a combination of two numbers which adds up to a target number.: -------------------------------------------------------------------------------- 1 | def sum_eq_n?(arr, n) 2 | return true if arr.empty? && n == 0 3 | 4 | arr.product(arr).reject { |a,b| a == b }.any? { |a,b| a + b == n } 5 | end 6 | -------------------------------------------------------------------------------- /Ruby/area.rb: -------------------------------------------------------------------------------- 1 | # input length and breadth, and 2 | # convert them to float value 3 | puts "Enter length:" 4 | l=gets.chomp.to_f 5 | puts "Enter width:" 6 | w=gets.chomp.to_f 7 | 8 | # calculating area 9 | area=l*w 10 | 11 | # printing the result 12 | puts "Area of Rectangle is #{area}" 13 | -------------------------------------------------------------------------------- /Ruby/area123.rb: -------------------------------------------------------------------------------- 1 | # input length and breadth, and 2 | # convert them to float value 3 | puts "Enter length:" 4 | l=gets.chomp.to_f 5 | puts "Enter width:" 6 | w=gets.chomp.to_f 7 | 8 | # calculating area 9 | area=l*w 10 | 11 | # printing the result 12 | puts "Area of Rectangle is #{area}" 13 | -------------------------------------------------------------------------------- /Ruby/greetings.rb: -------------------------------------------------------------------------------- 1 | puts "Please enter your name." 2 | name = gets 3 | puts "Hi, #{name}! I'm Ruby!" 4 | -------------------------------------------------------------------------------- /Ruby/leap-year.rb: -------------------------------------------------------------------------------- 1 | =begin 2 | Ruby program to check whether 3 | the year is leap year or not. 4 | =end 5 | 6 | puts "Enter the year you want to check" 7 | yr = gets.chomp.to_i 8 | 9 | if yr % 400 == 0 10 | puts "#{yr} is a leap year" 11 | elsif yr % 4 == 0 && yr % 100 !=0 12 | puts "#{yr} is a leap year" 13 | else 14 | puts "#{yr} is not a leap year" 15 | end 16 | -------------------------------------------------------------------------------- /Ruby/passgen.rb: -------------------------------------------------------------------------------- 1 | CHARS = ('0'..'9').to_a + ('A'..'Z').to_a + ('a'..'z').to_a 2 | 3 | def random_password(length=10) 4 | 5 | CHARS.sort_by { rand }.join[0...length] 6 | 7 | end 8 | -------------------------------------------------------------------------------- /Ruby/rev.rb: -------------------------------------------------------------------------------- 1 | =begin 2 | Ruby program to reverse a given string. 3 | =end 4 | 5 | puts "Enter the String:" 6 | str1=gets.chomp 7 | 8 | newstr= ' ' 9 | 10 | for i in 1..str1.length 11 | newstr+=str1[str1.length - i] 12 | end 13 | 14 | puts "The reverse of #{str1} is #{newstr}" 15 | -------------------------------------------------------------------------------- /Rust/Sumint.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | use std::{i32}; 4 | 5 | 6 | 7 | fn main() { 8 | 9 | // User will enter first number 10 | 11 | 12 | 13 | println!("Input First number ? "); 14 | 15 | 16 | 17 | let mut var1 = String::new(); 18 | 19 | 20 | 21 | io::stdin().read_line(&mut var1).expect("Unable to read entered data"); 22 | 23 | 24 | 25 | // User will enter Second number 26 | 27 | 28 | 29 | println!("Input second number ? "); 30 | 31 | let mut var2 = String::new(); 32 | 33 | io::stdin().read_line(&mut var2).expect("Unable to read entered data"); 34 | 35 | 36 | 37 | // Converting string to integer 38 | 39 | let a: i32 = var1.trim().parse().ok().expect("Program only processes numbers, Enter number"); 40 | 41 | let b: i32 = var2.trim().parse().ok().expect("Program only processes numbers, Enter number"); 42 | 43 | 44 | 45 | // Output of basic operations 46 | 47 | println!("The sum of a & b is : {}", a + b); 48 | 49 | 50 | 51 | } 52 | -------------------------------------------------------------------------------- /Rust/add.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let fNum = 5; 3 | let sNum: i32 = 25; 4 | 5 | let sum = return_sum(fNum, sNum); 6 | println!("The sum of fNum & sNum is = {}", sum); 7 | } 8 | 9 | fn return_sum(i: i32, j: i32) -> i32 { 10 | i + j 11 | } 12 | -------------------------------------------------------------------------------- /Rust/armstrong.rs: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | void main(){ 4 | 5 | int? num; 6 | print('Enter A Number to check ARMSTRONG or NOT ARMSTRONG NUMBER'); 7 | // user will enter a number to check 8 | num = int.parse(stdin.readLineSync()!); 9 | 10 | // user entered number is passed to function 11 | isArmString(num); 12 | 13 | } 14 | 15 | //a function to check arm strong 16 | void isArmString(int number){ 17 | //initial some variable 18 | int temp,digits =0, last = 0, sum = 0; 19 | 20 | //assign user entered number to temp variable 21 | temp = number; 22 | 23 | // loop execute until temp is 0 and increment digits by 1 each loop 24 | while(temp>0){ 25 | temp = temp~/10; 26 | digits++; 27 | } 28 | 29 | //reset temp to user entered number 30 | temp = number; 31 | 32 | //another loop for getting sum 33 | while(temp>0){ 34 | last = temp % 10; 35 | sum = sum + pow(last, digits) as int; 36 | temp = temp~/10; 37 | } 38 | 39 | // now if number and sum are equal its a arm strong number 40 | if(number == sum){ 41 | print("IT'S A ARMSTRONG NUMBER"); 42 | }else{ 43 | print("IT'S NOT ARMSTRONG NUMBER"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /shell scripts/Case/case-01.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | case "$1" in 4 | start) 5 | /usr/sbin/sshd 6 | ;; 7 | stop) 8 | kill $(cat /var/run/sshd.pid) 9 | ;; 10 | esac 11 | -------------------------------------------------------------------------------- /shell scripts/Case/case-02.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | case "$1" in 4 | start) 5 | /usr/sbin/sshd 6 | ;; 7 | stop) 8 | kill $(cat /var/run/sshd.pid) 9 | ;; 10 | *) 11 | echo "Usage: $0 start|stop" ; exit 1 12 | ;; 13 | esac 14 | -------------------------------------------------------------------------------- /shell scripts/Case/case-03.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | case "$1" in 4 | start) 5 | /usr/sbin/sshd 6 | ;; 7 | stop) 8 | kill $(cat /var/run/sshd.pid) 9 | ;; 10 | *) 11 | echo "Usage: $0 start|stop" ; exit 1 12 | ;; 13 | esac 14 | -------------------------------------------------------------------------------- /shell scripts/Case/case-04.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | case "$1" in 4 | start|START) 5 | /usr/sbin/sshd 6 | ;; 7 | stop|STOP) 8 | kill $(cat /var/run/sshd.pid) 9 | ;; 10 | *) 11 | echo "Usage: $0 start|stop" ; exit 1 12 | ;; 13 | esac 14 | -------------------------------------------------------------------------------- /shell scripts/Case/case-05.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | read -p "Enter y or n:" ANSWER 4 | 5 | case "$ANSWER" in 6 | [yY]|[yY][eE][sS]) 7 | echo "You answered yes." 8 | ;; 9 | [nN]|[nN][oO]) 10 | echo "You answered no." 11 | ;; 12 | *) 13 | echo "Invalid answer." 14 | ;; 15 | esac 16 | -------------------------------------------------------------------------------- /shell scripts/Case/case-06.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | read -p "Enter y or n: " ANSWER 4 | 5 | case "$ANSWER" in 6 | [yY]*) 7 | echo "You answered yes." 8 | ;; 9 | *) 10 | echo "You answered something else." 11 | ;; 12 | esac 13 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-01.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | TEST_VAR="test" 4 | echo "$TEST_VAR" 5 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-02.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | TEST_VAR="test" 4 | set -x 5 | echo $TEST_VAR 6 | set +x 7 | hostname 8 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-03.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | FILE_NAME="/not/here" 4 | ls $FILE_NAME 5 | echo $FILE_NAME 6 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-04.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -ex 2 | 3 | FILE_NAME="/not/here" 4 | ls $FILE_NAME 5 | echo $FILE_NAME 6 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-05.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -v 2 | 3 | TEST_VAR="test" 4 | echo "$TEST_VAR" 5 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-06.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -vx 2 | TEST_VAR="test" 3 | echo "$TEST_VAR" 4 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-07.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DEBUG=true 4 | 5 | if $DEBUG 6 | then 7 | echo "Debug mode ON." 8 | else 9 | echo "Debug mode OFF." 10 | fi 11 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-08.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DEBUG=true 4 | $DEBUG && echo "Debug mode ON." 5 | 6 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-09.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DEBUG=false 4 | $DEBUG || echo "Debug mode OFF." 5 | 6 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-10.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DEBUG=true 4 | 5 | # This will not execute because DEUBG=true 6 | $DEBUG || echo "Debug mode OFF." 7 | 8 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-11.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DEBUG="echo" 4 | $DEBUG ls 5 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-12.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #DEBUG="echo" 4 | $DEBUG ls 5 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-13.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | debug() { 4 | echo "Executing: $@" 5 | $@ 6 | } 7 | 8 | debug ls 9 | 10 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-14.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | PS4='+ $BASH_SOURCE : $LINENO : ' 4 | 5 | TEST_VAR="test" 6 | echo "$TEST_VAR" 7 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-15.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | PS4='+ ${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}() ' 4 | 5 | debug() { 6 | echo "Executing: $@" 7 | $@ 8 | } 9 | 10 | debug ls 11 | 12 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-16.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # This file contains carriage returns. 3 | echo "Hello world." 4 | -------------------------------------------------------------------------------- /shell scripts/Debugging/debugging-17.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # This file does NOT contain carriage returns. 3 | echo "Hello world." 4 | -------------------------------------------------------------------------------- /shell scripts/Exit status/exit-status-01.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | HOST="google.com" 4 | 5 | ping -c 1 $HOST 6 | 7 | if [ "$?" -eq "0" ] 8 | then 9 | echo "$HOST reachable." 10 | else 11 | echo "$HOST unreachable." 12 | fi 13 | 14 | -------------------------------------------------------------------------------- /shell scripts/Exit status/exit-status-02.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | HOST="google.com" 4 | 5 | ping -c 1 $HOST 6 | 7 | if [ "$?" -ne "0" ] 8 | then 9 | echo "$HOST unreachable." 10 | fi 11 | 12 | -------------------------------------------------------------------------------- /shell scripts/Exit status/exit-status-03.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | HOST="google.com" 4 | 5 | ping -c 1 $HOST 6 | RETURN_CODE=$? 7 | 8 | if [ "$RETURN_CODE" -ne "0" ] 9 | then 10 | echo "$HOST unreachable." 11 | fi 12 | 13 | -------------------------------------------------------------------------------- /shell scripts/Exit status/exit-status-04.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | HOST="google.com" 4 | 5 | ping -c 1 $HOST && echo "$HOST reachable." 6 | 7 | -------------------------------------------------------------------------------- /shell scripts/Exit status/exit-status-05.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | HOST="google.com" 4 | 5 | ping -c 1 $HOST || echo "$HOST unreachable." 6 | 7 | -------------------------------------------------------------------------------- /shell scripts/Exit status/exit-status-06.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | HOST="google.com" 4 | 5 | ping -c 1 $HOST 6 | 7 | if [ "$?" -ne "0" ] 8 | then 9 | echo "$HOST unreachable." 10 | exit 1 11 | fi 12 | 13 | exit 0 14 | -------------------------------------------------------------------------------- /shell scripts/Functions/functions-01.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | function hello() { 4 | echo "Hello!" 5 | } 6 | 7 | hello 8 | -------------------------------------------------------------------------------- /shell scripts/Functions/functions-02.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | function hello() { 4 | echo "Hello!" 5 | now 6 | } 7 | 8 | function now() { 9 | echo "It's $(date +%r)" 10 | } 11 | 12 | hello 13 | -------------------------------------------------------------------------------- /shell scripts/Functions/functions-03.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | function hello() { 4 | echo "Hello!" 5 | now 6 | } 7 | 8 | # This will cause an error as the "now()" function is not yet defined. 9 | hello 10 | 11 | function now() { 12 | echo "It's $(date +%r)" 13 | } 14 | -------------------------------------------------------------------------------- /shell scripts/Functions/functions-04.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | function hello() { 4 | echo "Hello $1" 5 | } 6 | 7 | hello Jason 8 | -------------------------------------------------------------------------------- /shell scripts/Functions/functions-05.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | function hello() { 4 | for NAME in $@ 5 | do 6 | echo "Hello $NAME" 7 | done 8 | } 9 | 10 | hello Jason Dan Ryan 11 | -------------------------------------------------------------------------------- /shell scripts/Functions/functions-06.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | my_function() { 4 | echo "$GLOBAL_VAR" 5 | } 6 | 7 | GLOBAL_VAR=1 8 | # The value of GLOBAL_VAR is available to my_function 9 | my_function 10 | 11 | -------------------------------------------------------------------------------- /shell scripts/Functions/functions-07.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | my_function() { 4 | echo "$GLOBAL_VAR" 5 | } 6 | 7 | # The value of GLOBAL_VAR is NOT available to my_function since GLOBAL_VAR was defined after my_function was called. 8 | my_function 9 | GLOBAL_VAR=1 10 | 11 | -------------------------------------------------------------------------------- /shell scripts/Functions/functions-08.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | my_function() { 4 | GLOBAL_VAR=1 5 | } 6 | 7 | # GLOBAL_VAR not available yet. 8 | echo "GLOBAL_VAR value BEFORE my_function called: $GLOBAL_VAR" 9 | 10 | my_function 11 | 12 | # GLOBAL_VAR is NOW available 13 | echo "GLOBAL_VAR value AFTER my_function called: $GLOBAL_VAR" 14 | -------------------------------------------------------------------------------- /shell scripts/Functions/functions-09.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | my_function() { 4 | local LOCAL_VAR=1 5 | echo "LOCAL_VAR can be accessed inside of the function: $LOCAL_VAR" 6 | } 7 | 8 | my_function 9 | 10 | # LOCAL_VAR is not available outside of the function. 11 | echo "LOCAL_VAR can NOT be accessed outside of the function: $LOCAL_VAR" 12 | -------------------------------------------------------------------------------- /shell scripts/Functions/functions-10.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | function backup_file () { 4 | # This function creates a backup of a file. 5 | 6 | # Make sure the file exists. 7 | if [ -f "$1" ] 8 | then 9 | # Make the BACKUP_FILE variable local to this function. 10 | local BACKUP_FILE="/tmp/$(basename ${1}).$(date +%F).$$" 11 | echo "Backing up $1 to ${BACKUP_FILE}" 12 | 13 | # The exit status of the function will be the exit status of the cp command. 14 | cp $1 $BACKUP_FILE 15 | else 16 | # The file does not exist, so return an non-zero exit status. 17 | return 1 18 | fi 19 | } 20 | 21 | # Call the function 22 | backup_file /etc/hosts 23 | 24 | # Make a decision based on the exit status of the function. 25 | # Note this is for demonstration purposes. You could have 26 | # put this functionality inside of the backup_file function. 27 | if [ $? -eq "0" ] 28 | then 29 | echo "Backup succeeded!" 30 | else 31 | echo "Backup failed!" 32 | # Abort the script and return a non-zero exit status. 33 | exit 1 34 | fi 35 | -------------------------------------------------------------------------------- /shell scripts/Logging/logging-00.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | logger "Message" 4 | logger -p local0.info "Message" 5 | logger -s -p local0.info "Message" 6 | logger -t myscript -p local0.info "Message" 7 | logger -i -t myscript "Message" 8 | -------------------------------------------------------------------------------- /shell scripts/Logging/logging-01.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | VERBOSE=false 4 | HOST="google.com" 5 | PID="$$" 6 | PROGRAM_NAME="$0" 7 | THIS_HOST=$(hostname) 8 | 9 | logit () { 10 | local LOG_LEVEL=$1 11 | shift 12 | MSG=$@ 13 | TIMESTAMP=$(date +"%Y-%m-%d %T") 14 | if [ $LOG_LEVEL = 'ERROR' ] || $VERBOSE 15 | then 16 | echo "${TIMESTAMP} ${THIS_HOST} ${PROGRAM_NAME}[${PID}]: ${LOG_LEVEL} ${MSG}" 17 | fi 18 | } 19 | 20 | logit INFO "Processing data." 21 | 22 | fetch-data $HOST || logit ERROR "Could not fetch data from $HOST" 23 | -------------------------------------------------------------------------------- /shell scripts/Random/email-when-up: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Usage: email-when-up -e EMAIL_ADDRESS -h HOST 4 | # This script send an email when the server/host/device is reachable over the network. 5 | 6 | usage() { 7 | echo "Usage: $0 -e EMAIL_ADDRESS -h HOST" >&2 8 | exit 9 | } 10 | 11 | while getopts ":e:h:" opt; do 12 | case "${opt}" in 13 | e) 14 | EMAIL_ADDRESS=${OPTARG} 15 | ;; 16 | h) 17 | HOST=${OPTARG} 18 | ;; 19 | *) 20 | usage 21 | ;; 22 | esac 23 | done 24 | shift $((OPTIND-1)) 25 | 26 | if [ -z "${EMAIL_ADDRESS}" ] || [ -z "${HOST}" ] 27 | then 28 | usage 29 | fi 30 | 31 | # Loop until the server is up. 32 | SECONDS_TO_SLEEP=60 33 | while [ true ] 34 | do 35 | ~/scripts/ping-host $HOST >/dev/null 2>&1 36 | if [ "$?" -eq 0 ] 37 | then 38 | echo "${HOST} is up! $(date)" 39 | echo "${HOST} is up! $(date)" | mailx -s "${HOST} is up." $EMAIL_ADDRESS 40 | exit 41 | else 42 | echo "$(date) ${HOST} is still down." 43 | fi 44 | sleep $SECONDS_TO_SLEEP 45 | done 46 | -------------------------------------------------------------------------------- /shell scripts/Random/generate-random-password: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Usage: generate-random-password [NUMBER_OF_PASSWORDS] [PASSWORD_LENGTH] 4 | # Generate random passwords using openssl. 5 | # Optionally pass in the number of passwords you want to generate and the length. 6 | # Default number of passwords is one. The default and maximum length is 64 characters. 7 | # 8 | # Example: 9 | # Generate 3 passwords that are 8 characters long. 10 | # generate-random-password 3 8 11 | 12 | NUMBER_OF_PASSWORDS=$1 13 | [ -n "$NUMBER_OF_PASSWORDS" ] || NUMBER_OF_PASSWORDS=1 14 | 15 | PASSWORD_LENGTH=$2 16 | [ -n "$PASSWORD_LENGTH" ] || PASSWORD_LENGTH=64 17 | 18 | for x in $(seq 1 $NUMBER_OF_PASSWORDS) 19 | do 20 | openssl rand -base64 48 | cut -c1-${PASSWORD_LENGTH} 21 | done 22 | -------------------------------------------------------------------------------- /shell scripts/Random/ping-host: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Usage: ping-host HOST [HOSTN]... 4 | # Retuns 0 if the hosts respond to ping or 1 if any of them fail to respond. 5 | # 6 | # Supported operating systems: Linux, Mac, BSDs, Solaris. 7 | 8 | 9 | # Help 10 | if [ -z "$1" ] || [ "$1" = '-h' ] || [ "$1" = '--help' ] 11 | then 12 | echo 'Usage: ping-host HOST [HOSTN]...' >&2 13 | echo 'Retuns 0 if the hosts respond to ping or 1 if any of them fail to respond.' >&2 14 | exit 15 | fi 16 | 17 | # What OS are we on? 18 | OS=$(uname -s) 19 | 20 | if [ "$OS" = 'SunOS' ] 21 | then 22 | # Solaris 23 | PING='ping -t 10' 24 | PING_SUFFIX_ARGS='1' 25 | GREP_PATTERN='no' 26 | else 27 | # Linux / Mac 28 | PING='ping -c 1 -W 1' 29 | PING_SUFFIX_ARGS="" 30 | GREP_PATTERN='100%' 31 | fi 32 | 33 | # Hope for the best, prepare for the worst. 34 | RETURN_CODE=0 35 | 36 | # Loop through the hosts provided on the command line. 37 | for HOST in $@ 38 | do 39 | PING_RESULT=$($PING $HOST $PING_SUFFIX_ARGS 2>&1 | egrep "$GREP_PATTERN|unknown host" | cut -d, -f3 | wc -l) 40 | [ "$PING_RESULT" -eq 0 ] || { 41 | RETURN_CODE=1 42 | echo "$HOST down" 43 | } 44 | done 45 | 46 | exit $RETURN_CODE 47 | -------------------------------------------------------------------------------- /shell scripts/Random/show-io-scheduler: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Show which I/O schedulers are currently in use. 4 | 5 | [ -d "/sys/block" ] && cat /sys/block/*/queue/scheduler | grep -v none | cut -f 2 -d[ | cut -f1 -d] | sort -u 6 | -------------------------------------------------------------------------------- /shell scripts/Random/show-network-port-info: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # This script displays the switch, port, and VLAN for each of the physical 4 | # network interfaces on a Linux server that is connected to Cisco networking 5 | # gear. 6 | # 7 | # Specific interfaces can be passed in on the command line. Other interfaces 8 | # will be ignored. 9 | 10 | # Set a timeout on the tcpdump command. 11 | TIMEOUT_SECONDS=60 12 | 13 | # Run as root 14 | [ "$EUID" -eq 0 ] || { 15 | echo 'Please run with sudo or as root.' 16 | exit 1 17 | } 18 | 19 | # If arguments are supplied, they are a list of NICs. 20 | NICS=$@ 21 | [ -z "$NICS" ] && { 22 | # Get a list of physical NICS on the server that are UP. Also, ignore bonded, 23 | # loopback, usb, virtual, tagged (@), and bridged interfaces. 24 | NICS=$(ip link | grep ^[0-9] | grep 'state UP' | cut -d: -f2 | egrep -v 'bond|lo|usb|@|vnet|vir|br' | sort | xargs) 25 | } 26 | 27 | # Loop through the NICs. 28 | for NIC in $NICS 29 | do 30 | echo $NIC 31 | timeout $TIMEOUT_SECONDS tcpdump -v -i $NIC -s 1500 -c 1 'ether[20:2] == 0x2000' 2>&1 |egrep 'Device-ID|Port-ID|VLAN' | awk '{print $NF}' | sed "s/'//g" 32 | 33 | [ "${PIPESTATUS[0]}" -eq 124 ] && echo 'tcpdump timed out.' 34 | 35 | echo 36 | done 37 | -------------------------------------------------------------------------------- /shell scripts/Random/show-total-disk-space-used: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Usage: show-total-disk-space-used 4 | # Shows how much local disk space is in use by the server. 5 | 6 | function round() { 7 | # Returns a rounded number 8 | local INTEGER=$(echo $1 | cut -f1 -d.) 9 | [ -z "$INTEGER" ] && INTEGER=0 10 | 11 | local DECIMAL=$(echo $1 | cut -s -f2 -d.) 12 | [ -z "$DECIMAL" ] && DECIMAL=0 13 | [ "$DECIMAL" -gt 4 ] && INTEGER=$(($INTEGER + 1)) 14 | echo $INTEGER 15 | } 16 | 17 | # Disk size used in kb, summed 18 | KB=$(df -lkP | awk '{print $3}' | grep -v Used | awk '{sum+=$1} END{printf("%d\n",sum)}') 19 | 20 | # Convert size to MB, GB, and TB 21 | MB=$(round $(echo $KB/1024 | bc -l | sed -e "s/\(\.[0-9]\).*/\1/g")) 22 | GB=$(round $(echo $KB/1024/1024 | bc -l | sed -e "s/\(\.[0-9]\).*/\1/g")) 23 | TB=$(round $(echo $KB/1024/1024/1024 | bc -l | sed -e "s/\(\.[0-9]\).*/\1/g")) 24 | 25 | # Use the largest human readable size to display 26 | if [ "$TB" -gt 0 ] 27 | then 28 | TOTAL_DISK_SPACE_USED="${TB}T" 29 | elif [ "$GB" -gt 0 ] 30 | then 31 | TOTAL_DISK_SPACE_USED="${GB}G" 32 | elif [ "$MB" -gt 0 ] 33 | then 34 | TOTAL_DISK_SPACE_USED="${MB}M" 35 | else 36 | TOTAL_DISK_SPACE_USED="${KB}K" 37 | fi 38 | 39 | echo -e "$(uname -n)\t${TOTAL_DISK_SPACE_USED}" 40 | -------------------------------------------------------------------------------- /shell scripts/Random/show-wwpns: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Display WWPNs on a Linux server. 4 | 5 | [ -d "/sys/class/fc_host" ] && cat /sys/class/fc_host/*/port_name | sed 's/^0x//; s/\(.\{2\}\)/&:/g; s/:$//' 6 | 7 | -------------------------------------------------------------------------------- /shell scripts/Random/tail-db2diag: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Usage: tail-db2diag 4 | # Performs a tail -f on the current db2 diag log file. 5 | 6 | DB2_DIAG_LOG=$(ls -rt /db2/*/db2dump/db2diag* 2>/dev/null | tail -1) 7 | 8 | if [ -e "$DB2_DIAG_LOG" ] 9 | then 10 | # Show what file we're tailing. 11 | echo $DB2_DIAG_LOG 12 | echo 13 | 14 | # Tail the log file. 15 | tail -f $DB2_DIAG_LOG 16 | else 17 | echo "No db2 diag log file found." 18 | exit 1 19 | fi 20 | -------------------------------------------------------------------------------- /shell scripts/Random/touch-test: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Usage: touch-test 4 | # Touches and deletes a file on each of the locally mounted file systems. 5 | # This can help point out read-only mounts and poorly performing mounts. 6 | 7 | # Run as root 8 | [ "$EUID" -eq 0 ] || { 9 | echo 'Please run with sudo or as root.' 10 | exit 1 11 | } 12 | 13 | TEST_FILE='touch-test-file' 14 | 15 | START=$(date) 16 | START_SECONDS=$(date +%s) 17 | 18 | for MOUNT in $(df -lP | egrep -v '^Filesystem|tmpfs' | awk '{print $NF}') 19 | do 20 | TEST_FILE_ON_MOUNT="${MOUNT}/${TEST_FILE}" 21 | echo "$(date) - Touching $TEST_FILE_ON_MOUNT" 22 | touch $TEST_FILE_ON_MOUNT 23 | rm $TEST_FILE_ON_MOUNT 24 | echo "$(date) - Removed $TEST_FILE_ON_MOUNT" 25 | done 26 | 27 | END=$(date) 28 | END_SECONDS=$(date +%s) 29 | TOTAL_SECONDS=$(($END_SECONDS - $START_SECONDS)) 30 | 31 | echo 32 | echo "Start: $START" 33 | echo "End: $END" 34 | echo "Total: $TOTAL_SECONDS seconds" 35 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/archive_user-01.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | USER=$1 # The first parameter is the user. 4 | 5 | echo "Executing script: $0" 6 | echo "Archiving user: $USER" 7 | 8 | # Lock the account 9 | passwd -l $USER 10 | 11 | # Create an archive of the home directory. 12 | tar cf /archives/${USER}.tar.gz /home/${USER} 13 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/archive_user-02.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "Executing script: $0" 4 | 5 | for USER in $@ 6 | do 7 | echo "Archiving user: $USER" 8 | 9 | # Lock the account 10 | passwd -l $USER 11 | 12 | # Create an archive of the home directory. 13 | tar cf /archives/${USER}.tar.gz /home/${USER} 14 | done 15 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/archive_user-03.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | read -p "Enter a user name: " USER 4 | echo "Archiving user: $USER" 5 | 6 | # Lock the account 7 | passwd -l $USER 8 | 9 | # Create an archive of the home directory. 10 | tar cf /archives/${USER}.tar.gz /home/${USER} 11 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/archive_user.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "Executing script: $0" 4 | echo "Archiving user: $1" 5 | 6 | # Lock the account 7 | passwd -l $1 8 | 9 | # Create an archive of the home directory. 10 | tar cf /archives/${1}.tar.gz /home/${1} 11 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/hi.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | print "This is a Python script." 3 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/rename-pics.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | PICTURES=$(ls *jpg) 4 | DATE=$(date +%F) 5 | for PICTURE in $PICTURES 6 | do 7 | echo "Renaming ${PICTURE} to ${DATE}-${PICTURE}" 8 | mv ${PICTURE} ${DATE}-${PICTURE} 9 | done 10 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-01.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "Scripting is fun!" 3 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-02.sh: -------------------------------------------------------------------------------- 1 | #!/bin/csh 2 | echo "This script uses csh as the interpreter." 3 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-03.sh: -------------------------------------------------------------------------------- 1 | #!/bin/ksh 2 | echo "This script uses ksh as the interpreter." 3 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-04.sh: -------------------------------------------------------------------------------- 1 | #!/bin/zsh 2 | echo "This script uses zsh as the interpreter." 3 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-05.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | MY_SHELL="bash" 3 | echo "I like the $MY_SHELL shell." 4 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-06.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | MY_SHELL="bash" 3 | echo "I like the ${MY_SHELL} shell." 4 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-07.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | MY_SHELL="bash" 3 | echo "I am ${MY_SHELL}ing on my keyboard." 4 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-08.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | MY_SHELL="bash" 3 | echo "I am $MY_SHELLing on my keyboard." 4 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-09.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | SERVER_NAME=$(hostname) 3 | echo "You are running this script on ${SERVER_NAME}." 4 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-10.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | SERVER_NAME=`hostname` 3 | echo "You are running this script on ${SERVER_NAME}." 4 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-11.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | MY_SHELL="bash" 4 | 5 | if [ "$MY_SHELL" = "bash" ] 6 | then 7 | echo "You seem to like the bash shell." 8 | fi 9 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-12.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | MY_SHELL="csh" 4 | 5 | if [ "$MY_SHELL" = "bash" ] 6 | then 7 | echo "You seem to like the bash shell." 8 | else 9 | echo "You don't seem to like the bash shell." 10 | fi 11 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-13.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | MY_SHELL="csh" 4 | 5 | if [ "$MY_SHELL" = "bash" ] 6 | then 7 | echo "You seem to like the bash shell." 8 | elif [ "$MY_SHELL" = "csh" ] 9 | then 10 | echo "You seem to like the csh shell." 11 | else 12 | echo "You don't seem to like the bash or csh shells." 13 | fi 14 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-14.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | for COLOR in red green blue 4 | do 5 | echo "COLOR: $COLOR" 6 | done 7 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/script-15.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | COLORS="red green blue" 4 | 5 | for COLOR in $COLORS 6 | do 7 | echo "COLOR: $COLOR" 8 | done 9 | -------------------------------------------------------------------------------- /shell scripts/Shell scripting in nutshell/sleepy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | sleep 90 3 | -------------------------------------------------------------------------------- /shell scripts/SumOfTwoNumbers.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Add two numeric value 3 | ((sum=25+35)) 4 | 5 | #Print the result 6 | echo $sum 7 | -------------------------------------------------------------------------------- /shell scripts/UserInput.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "Enter Your Name" 3 | read name 4 | echo "Welcome $name to LinuxHint" 5 | -------------------------------------------------------------------------------- /shell scripts/While loops/while-loops-01.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | INDEX=1 4 | while [ $INDEX -lt 6 ] 5 | do 6 | echo "Creating project-${INDEX}" 7 | mkdir /usr/local/project-${INDEX} 8 | ((INDEX++)) 9 | done 10 | -------------------------------------------------------------------------------- /shell scripts/While loops/while-loops-02.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | while [ "$CORRECT" != "y" ] 4 | do 5 | read -p "Enter your name: " NAME 6 | read -p "Is ${NAME} correct? " CORRECT 7 | done 8 | -------------------------------------------------------------------------------- /shell scripts/While loops/while-loops-03.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | while ping -c 1 app1 >/dev/null 4 | do 5 | echo "app1 still up..." 6 | sleep 5 7 | done 8 | 9 | echo "app1 down, continuing." 10 | -------------------------------------------------------------------------------- /shell scripts/While loops/while-loops-04.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | LINE_NUM=1 4 | while read LINE 5 | do 6 | echo "${LINE_NUM}: ${LINE}" 7 | ((LINE_NUM++)) 8 | done < /etc/fstab 9 | -------------------------------------------------------------------------------- /shell scripts/While loops/while-loops-05.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | grep xfs /etc/fstab | while read LINE 4 | do 5 | echo "xfs: ${LINE}" 6 | done 7 | -------------------------------------------------------------------------------- /shell scripts/While loops/while-loops-06.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | FS_NUM=1 4 | grep xfs /etc/fstab | while read FS MP REST 5 | do 6 | echo "${FS_NUM}: file system: ${FS}" 7 | echo "${FS_NUM}: mount point: ${MP}" 8 | ((FS_NUM++)) 9 | done 10 | -------------------------------------------------------------------------------- /shell scripts/While loops/while-loops-07.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | while true 4 | do 5 | read -p "1: Show disk usage. 2: Show uptime. " CHOICE 6 | case "$CHOICE" in 7 | 1) 8 | df -h 9 | ;; 10 | 2) 11 | uptime 12 | ;; 13 | *) 14 | break 15 | ;; 16 | esac 17 | done 18 | 19 | -------------------------------------------------------------------------------- /shell scripts/While loops/while-loops-08.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | mysql -BNe 'show databases' | while read DB 4 | do 5 | db-backed-up-recently $DB 6 | if [ "$?" -eq "0" ] 7 | then 8 | continue 9 | fi 10 | backup $DB 11 | done 12 | -------------------------------------------------------------------------------- /shell scripts/WhileLoop.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | valid=true 3 | count=1 4 | while [ $valid ] 5 | do 6 | echo $count 7 | if [ $count -eq 5 ]; 8 | then 9 | break 10 | fi 11 | ((count++)) 12 | done 13 | -------------------------------------------------------------------------------- /shell scripts/Wild card/copy-www-01.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cd /var/www 4 | for FILE in *.html 5 | do 6 | echo "Copying $FILE" 7 | cp $FILE /var/www-just-html 8 | done 9 | -------------------------------------------------------------------------------- /shell scripts/Wild card/copy-www-02.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | for FILE in /var/www/*.html 4 | do 5 | echo "Copying $FILE" 6 | cp $FILE /var/www-just-html 7 | done 8 | -------------------------------------------------------------------------------- /shell scripts/Wild card/copy-www-03.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # This will loop through all the "html" files in the current directroy. 4 | for FILE in *.html 5 | do 6 | echo "Copying $FILE" 7 | cp $FILE /var/www-just-html 8 | done 9 | -------------------------------------------------------------------------------- /shell scripts/fib.sh: -------------------------------------------------------------------------------- 1 | echo "How many number of terms to be generated ?" 2 | read n 3 | function fib 4 | { 5 | x=0 6 | y=1 7 | i=2 8 | echo "Fibonacci Series up to $n terms :" 9 | echo "$x" 10 | echo "$y" 11 | while [ $i -lt $n ] 12 | do 13 | i=`expr $i + 1 ` 14 | z=`expr $x + $y ` 15 | echo "$z" 16 | x=$y 17 | y=$z 18 | done 19 | } 20 | r=`fib $n` 21 | echo "$r" 22 | -------------------------------------------------------------------------------- /shell scripts/message.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | hour=`date +%I` 3 | min=`date +%M` 4 | ampm=`date +%p` 5 | echo "$hour : $min $ampm" 6 | if [ $ampm="AM" ] 7 | then 8 | echo "Good Morning" 9 | else 10 | if [ $hour -eq 12 -o $hour -lt 4] 11 | then 12 | echo "Good afternoon" 13 | elif [ $hour -ge 4 -a $hour -le 8 ] 14 | then 15 | echo "Good evening" 16 | fi 17 | fi 18 | -------------------------------------------------------------------------------- /shell scripts/month.sh: -------------------------------------------------------------------------------- 1 | for m in {1..12}; 2 | do 3 | a=$(date -d "$m/1 + 1 month - 1 day" "+%b - %d days";) 4 | echo "$a" 5 | done 6 | -------------------------------------------------------------------------------- /shell scripts/salary.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "enter the basic salary:" 3 | read basal 4 | grosal=$( echo "$basal+((40/100)*$basal)+((20/100)*$basal)" | bc -l) 5 | echo "The gross salary : $grosal" 6 | --------------------------------------------------------------------------------