From f4fa9cdf8e0b8bb83068cb251c0ae7ef629b065f Mon Sep 17 00:00:00 2001 From: Michael Reber Date: Mon, 18 Nov 2019 14:44:36 +0100 Subject: [PATCH] Upload basic README.md --- assembly/README.md | 3 + c++/Basic/2D Array.cpp | 43 ++ c++/Basic/Add n numbers.cpp | 17 + c++/Basic/Add subtract multiply divide.cpp | 19 + c++/Basic/Addition of digits.cpp | 17 + c++/Basic/Addition of matrices.cpp | 28 + c++/Basic/Area of a triangle.cpp | 12 + c++/Basic/BellmanFord.cpp | 82 +++ c++/Basic/Binary Operator Overloading.cpp | 73 ++ .../Binary Searching using recursion.cpp | 50 ++ c++/Basic/Binary to Decimal.cpp | 19 + c++/Basic/Binary to Hexadecimal.cpp | 17 + c++/Basic/Binary to Octal.cpp | 17 + c++/Basic/BinaryPow.cpp | 20 + c++/Basic/Check Positive or Negative.cpp | 20 + c++/Basic/Comparator.cpp | 37 + c++/Basic/ConvexHull.cpp | 39 + c++/Basic/Current Date.cpp | 14 + c++/Basic/Decimal to Binary.cpp | 19 + c++/Basic/Decimal to Octal.cpp | 18 + c++/Basic/Delete Vowels.cpp | 47 ++ c++/Basic/Diameter.cpp | 67 ++ c++/Basic/Dijkstra.cpp | 73 ++ c++/Basic/DijkstraHeap.cpp | 123 ++++ c++/Basic/DisjointSets.cpp | 36 + c++/Basic/FFT.cpp | 137 ++++ c++/Basic/FenwickTree.cpp | 47 ++ c++/Basic/FenwickTreeOnMap.cpp | 31 + c++/Basic/Find ASCII value of a character.cpp | 12 + c++/Basic/FindIntersection.cpp | 103 +++ c++/Basic/Get IP Address.cpp | 8 + c++/Basic/Hcf & Lcm.cpp | 36 + c++/Basic/KdTree.cpp | 103 +++ c++/Basic/Manacher.cpp | 65 ++ c++/Basic/Matrix.cpp | 62 ++ c++/Basic/MaxFlowDinic.cpp | 87 +++ c++/Basic/MaxMatching.cpp | 86 +++ c++/Basic/MinCostFlow.cpp | 121 ++++ c++/Basic/MinCostFlowBF.cpp | 92 +++ c++/Basic/Odd or Even.cpp | 19 + c++/Basic/Pattern 1.cpp | 18 + c++/Basic/Pattern 10.cpp | 31 + c++/Basic/Pattern 2.cpp | 27 + c++/Basic/Pattern 3.cpp | 27 + c++/Basic/Pattern 4.cpp | 27 + c++/Basic/Pattern 5.cpp | 27 + c++/Basic/Pattern 6.cpp | 27 + c++/Basic/Pattern 7.cpp | 27 + c++/Basic/Pattern 8.cpp | 34 + c++/Basic/Pattern 9.cpp | 44 ++ c++/Basic/Prim.cpp | 55 ++ c++/Basic/PrimesGenerator.cpp | 43 ++ c++/Basic/Scanner.cpp | 53 ++ c++/Basic/Shutdown Computer.cpp | 14 + c++/Basic/SuffixArrayLcp.cpp | 162 +++++ c++/Basic/TreeIsomorphism.cpp | 164 +++++ c++/Basic/bigint-full.cpp | 506 +++++++++++++ c++/Basic/bigint.cpp | 446 ++++++++++++ c++/Basic/nCr & nPr.cpp | 41 ++ c++/Basic/polynom-roots.cpp | 88 +++ ...D FFT Inplace Given a Complex 2D Array.cpp | 70 ++ ...Check Multiplicability of Two Matrices.cpp | 40 ++ ...ram to Check if a Matrix is Invertible.cpp | 76 ++ ...gram to Check if it is a Sparse Matrix.cpp | 54 ++ ...m to Compute DFT Coefficients Directly.cpp | 65 ++ ...ram to Compute Determinant of a Matrix.cpp | 69 ++ ...Fourier Transform Using Naive Approach.cpp | 84 +++ ...ng the Fast Fourier Transform Approach.cpp | 73 ++ .../C++ Program to Emulate N Dice Roller.cpp | 25 + ...o Find Basis and Dimension of a Matrix.cpp | 74 ++ ...ind Closest Pair of Points in an Array.cpp | 137 ++++ ...gram to Find Factoial of Large Numbers.cpp | 83 +++ ... of a Number using Dynamic Programming.cpp | 55 ++ ...d Factoial of a Number using Iteration.cpp | 49 ++ ... Factorial of a Number using Recursion.cpp | 47 ++ ...acci Numbers using Dynamic Programming.cpp | 71 ++ ...Find Fibonacci Numbers using Iteration.cpp | 68 ++ ...ci Numbers using Matrix Exponentiation.cpp | 92 +++ ...Find Fibonacci Numbers using Recursion.cpp | 62 ++ ...mbers Using Recursive Euclid Algorithm.cpp | 35 + ...++ Program to Find Inverse of a Matrix.cpp | 565 +++++++++++++++ ...Find Path Between Two Nodes in a Graph.cpp | 109 +++ ...m to Find the GCD and LCM of n Numbers.cpp | 57 ++ ...N Number of Passwords of Length M Each.cpp | 179 +++++ ...iven Range Using the Sieve of Sundaram.cpp | 72 ++ ...m to Generate Random Hexadecimal Bytes.cpp | 18 + ...dom Numbers Using Middle Square Method.cpp | 45 ++ ...mbers Using Multiply with Carry Method.cpp | 31 + ...sing Probability Distribution Function.cpp | 34 + ...zed Sequence of Given Range of Numbers.cpp | 26 + ...m for Multiplication of 2 signed Numbers.cpp | 141 ++++ ...ement Coppersmith Freivald’s Algorithm.cpp | 129 ++++ ...C++ Program to Implement Euler Theorem.cpp | 37 + ...Implement Extended Eucledian Algorithm.cpp | 55 ++ ...ram to Implement Fermat Primality Test.cpp | 67 ++ ...m to Implement Fermat’s Little Theorem.cpp | 49 ++ ...er-Yates Algorithm for Array Shuffling.cpp | 48 ++ ...ogram to Implement Gauss Seidel Method.cpp | 80 +++ ... Implement Miller Rabin Primality Test.cpp | 98 +++ ...ement Modular Exponentiation Algorithm.cpp | 48 ++ ...t Naor-Reingold Pseudo Random Function.cpp | 35 + ...ler Random Number Generation Algorithm.cpp | 51 ++ ...plement Russian Peasant Multiplication.cpp | 38 + ...+ Program to Implement Segmented Sieve.cpp | 91 +++ ...+ Program to Implement Sieve of Atkins.cpp | 92 +++ ...ram to Implement Sieve of Eratosthenes.cpp | 30 + ...lement Solovay-Strassen Primality Test.cpp | 110 +++ ...gram to Implement Strassen’s Algorithm.cpp | 229 ++++++ ...to Implement the Bin Packing Algorithm.cpp | 52 ++ ...ithm for Multiplication of Two Numbers.cpp | 62 ++ ...or for Pseudo Random Number Generation.cpp | 95 +++ ...rate Prime Numbers Between Given Range.cpp | 84 +++ ...mize Wire Length in Electrical Circuit.cpp | 113 +++ ...tion Operation Using Bitwise Operators.cpp | 27 + ... a Message Using Matrix Multiplication.cpp | 77 ++ ...Perform LU Decomposition of any Matrix.cpp | 103 +++ ...ogram to Perform Matrix Multiplication.cpp | 112 +++ ...nthesization Using Dynamic Programming.cpp | 65 ++ ...ion of an Integer in All Possible Ways.cpp | 80 +++ ...Unique Factorization of a Given Number.cpp | 81 +++ ...resent Linear Equations in Matrix Form.cpp | 49 ++ ...sack Problem Using Dynamic Programming.cpp | 65 ++ ...ve any Linear Equation in One Variable.cpp | 647 +++++++++++++++++ ...gram to Solve the 0-1 Knapsack Problem.cpp | 61 ++ ... Solve the Fractional Knapsack Problem.cpp | 78 ++ ...rogram to Use rand and srand Functions.cpp | 20 + ...nt Gauss Jordan Elimination algorithm..cpp | 82 +++ ... to Compare Two Strings Using Pointers.cpp | 31 + ...C++ program to add two complex numbers.cpp | 31 + ...C++ program to generate random numbers.cpp | 20 + .../C++ program to reverse a number.cpp | 38 + ...ram to swap two numbers using pointers.cpp | 0 ...cessing Member Function Through Object.cpp | 49 ++ .../CPP Program For Call By Reference.cpp | 31 + .../CPP Program For Call By Value.cpp | 23 + ...P Program For Constructor Over Loading.cpp | 76 ++ ...For Declaring Pointers as Class Member.cpp | 34 + ...claring Static Members as Class Member.cpp | 49 ++ .../CPP Program For Matrix Addition.cpp | 48 ++ ... Program For Parameterized Constructor.cpp | 68 ++ ...Program For Unary Operator Overloading.cpp | 83 +++ ... Outside Classes Using Friend Function.cpp | 46 ++ ...o Implement Constructor and Destructor.cpp | 77 ++ ...CPP Program To Implement Encapsulation.cpp | 42 ++ ...gram To Implement Function Overloading.cpp | 39 + .../CPP Program To Implement Inheritance.cpp | 142 ++++ ... Parameters To Base Class Constructors.cpp | 71 ++ ...ram To Implement Pure Virtual Function.cpp | 67 ++ ... Implement Random Access File Handling.cpp | 34 + ...lement Sequential Access File Handling.cpp | 32 + ...gram To Implement Virtual Base Classes.cpp | 43 ++ ...Program To Implement Virtual Functions.cpp | 149 ++++ ...rogram To Overriding Template Function.cpp | 49 ++ ...or delete and new Operator Overloading.cpp | 134 ++++ ...g Including Unary and Binary Operators.cpp | 44 ++ ...tanding Protected Qualifier Activities.cpp | 74 ++ c++/README.md | 3 + .../C++ Program to Construct DFA from NFA.cpp | 189 +++++ ... Message Encoded Using Playfair Cipher.cpp | 121 ++++ ...Encode a Message Using Playfair Cipher.cpp | 158 +++++ ...ind Length of Longest Common Substring.cpp | 48 ++ ...easing Subsequence of a Given Sequence.cpp | 59 ++ ...C++ Program to Implement Affine Cipher.cpp | 57 ++ ...Corasick Algorithm for String Matching.cpp | 146 ++++ ...nt Bitap Algorithm for String Matching.cpp | 64 ++ ...er-Moore Algorithm for String Matching.cpp | 61 ++ ...C++ Program to Implement Caesar Cypher.cpp | 40 ++ ...rogram to Implement Kadane’s Algorithm.cpp | 39 + ...ent Knuth–Morris–Pratt Algorithm (KMP).cpp | 72 ++ ...venshtein Distance Computing Algorithm.cpp | 42 ++ ...m to Implement Longest Prefix Matching.cpp | 120 ++++ ...gram to Implement Rabin-Karp Algorithm.cpp | 63 ++ ...mplement String Matching Using Vectors.cpp | 97 +++ ...r Algorithm for online String Matching.cpp | 41 ++ .../C++ Program to Implement Z-Algorithm.cpp | 62 ++ ...+ Program to Implement the Hill Cypher.cpp | 110 +++ ...to Implement the Monoalphabetic Cypher.cpp | 88 +++ ...o Implement the One Time Pad Algorithm.cpp | 92 +++ ...Program to Implement the RSA Algorithm.cpp | 183 +++++ ... Search Algorithm for Short Text Sizes.cpp | 52 ++ ...ogram to Implement the Vigenere Cypher.cpp | 71 ++ ...tography Using Transposition Technique.cpp | 163 +++++ ...rm Finite State Automaton based Search.cpp | 74 ++ ...ogram to Perform Naive String Matching.cpp | 38 + ...m String Matching Using String Library.cpp | 32 + ...as Bible by building a Data Structure).cpp | 49 ++ ...e user and Display it if it is Positive.cs | 30 + ... & Categorize as Tall, Dwarf or Average.cs | 27 + .../C# Program to Calculate Acceleration.cs | 23 + ... the Entered Year is a Leap Year or Not.cs | 42 ++ ...ether the Entered Number is Even or Odd.cs | 34 + ... given Integer has an Alternate Pattern.cs | 45 ++ .../Basic/C# Program to Compare Two Dates.cs | 26 + ...o Compute Average for the Set of Values.cs | 35 + ...the Number of 1’s in the Entered Number.cs | 46 ++ .../C# Program to Create Sealed Class.cs | 24 + ... All the Prime Numbers Between 1 to 100.cs | 41 ++ ...Display Numbers in the form of Triangle.cs | 42 ++ ...rogram to Display Squarefeet of a House.cs | 23 + ... Program to Display the ATM Transaction.cs | 77 ++ ... to Display the Date in Various Formats.cs | 36 + ...rogram to Find Greatest among 2 numbers.cs | 29 + ...C# Program to Find Magnitude of Integer.cs | 26 + ... Find a Number using Pythagoras Theorem.cs | 28 + .../C# Program to Generate Random Numbers.cs | 34 + ...and Display the Number with its Reverse.cs | 31 + ...umber and Display the Sum of the Digits.cs | 31 + ...gram to Illustrate LeftShift Operations.cs | 28 + ...Illustrate the Use of Access Specifiers.cs | 48 ++ .../C# Program to Implement PhoneBook.cs | 52 ++ ...ogram to Implement for-each in Inteface.cs | 85 +++ ...form Division of Exponents of Same Base.cs | 29 + ...# Program to Perform Unboxing Operation.cs | 29 + .../C# Program to Print a BinaryTriangle.cs | 46 ++ ...am to Print a Diamond Using Nested Loop.cs | 43 ++ ...de & Display the Equivalent Description.cs | 41 ++ c-sharp/Basic/C# Program to Swap 2 Numbers.cs | 35 + ...two Numbers using Bitwise XOR Operation.cs | 27 + ...nput and print its multiplication table.cs | 31 + ...le 20) as input and prints something as.cs | 13 + ...nput to calculate and print the average.cs | 19 + ...elsius degrees to Kelvin and Fahrenheit.cs | 11 + ... Hello and your name in a separate line.cs | 12 + ...mbers which will be entered by the user.cs | 16 + ...mbers which will be entered by the user.cs | 17 + ...rint the result of dividing two numbers.cs | 7 + ... the result of the specified operations.cs | 32 + ...program to print the sum of two numbers.cs | 7 + .../C# Sharp program to swap two numbers.cs | 19 + ...int the output of (x+y)úz and xúy + yúz.cs | 16 + ...s wide and 5 rows tall using that digit.cs | 15 + ...mes in the next row, with no separation.cs | 29 + c-sharp/README.md | 3 + c/Basic/Accessing an array using pointers.c | 17 + ... & Categorize as Taller, Dwarf & Average.c | 21 + ...two Integers and Check if they are Equal.c | 14 + .../C Program to Add two Complex Numbers.c | 31 + ... Calculate the Sum of Odd & Even Numbers.c | 20 + ... Check if a given Integer is Odd or Even.c | 16 + ... a given Integer is Positive or Negative.c | 16 + ...heck whether a given Number is Armstrong.c | 24 + ...whether a given Number is Perfect Number.c | 24 + ...Palindrome or not using Bitwise Operator.c | 70 ++ ...cci Numbers using Command Line Arguments.c | 34 + ...ute the Sum of Digits in a given Integer.c | 20 + ...s Equivalent Gray’s Code using Recursion.c | 40 ++ ...lent Gray’s Code without using Recursion.c | 35 + ...Program to Convert Binary to Hexadecimal.c | 20 + .../C Program to Convert Binary to Octal.c | 20 + ...Program to Convert Hexadecimal to Binary.c | 91 +++ ...ram to Convert Numbers to Roman Numerals.c | 125 ++++ .../C Program to Convert Octal to Binary.c | 49 ++ .../C Program to Convert Octal to Decimal.c | 20 + ...o Convert Roman Number to Decimal Number.c | 66 ++ ...umber to Binary & Count the Number of 1s.c | 28 + ... of Days in terms of Years, Weeks & Days.c | 19 + ... System to Binary System using Recursion.c | 28 + ...ert the given Binary Number into Decimal.c | 21 + ...ber of Words in a given Text Or Sentence.c | 27 + ...ing the Case of Alphabets & Display them.c | 86 +++ ...gram to Count the Number of Unique Words.c | 65 ++ ... of each C Keyword using Array Structure.c | 104 +++ ...Function without using the Main Function.c | 11 + ...isplay its own Source Code as its Output.c | 19 + ...C Program to Display the ATM Transaction.c | 72 ++ ... to Display the IP Address of the System.c | 29 + ...isplay the Inventory of Items in a Store.c | 62 ++ ... Extract Last two Digits of a given Year.c | 14 + ...ind Multiplication of two Binary Numbers.c | 50 ++ ...uct of 2 Numbers without using Recursion.c | 28 + ...um of Digits of a Number using Recursion.c | 28 + ...m to Find if a given Year is a Leap Year.c | 17 + ...Program to Find the Biggest of 3 Numbers.c | 27 + ...f String2 in string1 & also its Position.c | 51 ++ ...nd the Number of Integers Divisible by 5.c | 29 + .../C Program to Find the Size of a Union.c | 23 + ... first 50 Natural Numbers using For Loop.c | 15 + ...am to Find the Sum of two Binary Numbers.c | 28 + ...a Number is Prime or Not using Recursion.c | 42 ++ .../C Program to Generate Fibonacci Series.c | 24 + ... Program to Illustrate Pass by Reference.c | 19 + .../C Program to Illustrate Pass by Value.c | 21 + ...lustrate how User Authentication is Done.c | 29 + ...gram to Illustrate the Concept of Unions.c | 20 + ...o Implements Regular Expression Matching.c | 295 ++++++++ ...inary Strings and Print their Binary Sum.c | 117 +++ ...and Operate Appropriately on the Numbers.c | 35 + ...in an Inventory of items in Online Store.c | 47 ++ ...iven Number by 4 using Bitwise Operators.c | 15 + ...to Print Armstrong Number from 1 to 1000.c | 23 + ...Equivalent of an Integer using Recursion.c | 28 + ...two given Strings without any Repetition.c | 48 ++ c/Basic/C Program to Print Diamond Pattern.c | 42 ++ ...t using a Semicolon anywhere in the Code.c | 14 + ... Print Statement without using Semicolon.c | 11 + ...t the Program Name and All its Arguments.c | 14 + ... to Print the Words Ending with Letter S.c | 38 + ...Two Integers M and N & Swap their Values.c | 25 + ...ade & Display the Equivalent Description.c | 43 ++ c/Basic/C Program to Reverse a Given Number.c | 20 + ...e a Number & Check if it is a Palindrome.c | 27 + ...ord & Replace it with the Specified Word.c | 72 ++ ...utdown or Turn Off the Computer in Linux.c | 10 + ... two Numbers using Bitwise XOR Operation.c | 18 + ...e Number of Leading Zero's in a Number x.c | 114 +++ ...te the total execution time of a program.c | 19 + ...ind Product of 2 Numbers using Recursion.c | 32 + ...find Reverse of a Number using Recursion.c | 36 + ...to find Sum of N Numbers using Recursion.c | 31 + ... to next higher value of n with same 1's.c | 63 ++ ...ace first letter of every word with caps.c | 61 ++ ...paces and repeating characters only once.c | 64 ++ ...program for Binary to decimal conversion.c | 16 + ...C program for decimal to octal converter.c | 17 + ...ram for hexadecimal to binary conversion.c | 85 +++ ...rogram to Convert Decimal to Hexadecimal.c | 27 + .../C program to Convert Decimal to Octal.c | 22 + ...ease 1 to all of the given Integer Digit.c | 19 + ... for a given number using binary search..c | 121 ++++ ... using pointers and display the results..c | 47 ++ ...on also check whether it is a palindrome.c | 47 ++ ...f occurences of a given number in a list.c | 50 ++ ...rint hello world without using semicolon.c | 5 + ... characters by uppercase and vice-versa..c | 41 ++ ...m to sort n given numbers using pointers.c | 37 + ... size of an array be declared at runtime.c | 44 ++ ...se Your Own Header File in C Programming.c | 8 + ...ss of an array using Arrays and Pointers.c | 14 + c/Basic/Print mark-sheet of students.c | 43 ++ c/Basic/Reverse a string using pointers.c | 15 + ...f each word of the string using pointers.c | 28 + c/Basic/Show the ticking of Clock.c | 104 +++ c/Basic/Time functions in c.c | 36 + ...verage of n given numbers using pointers.c | 26 + ...ute the seconds from a given age using C.c | 12 + ...er within n given numbers using pointers.c | 28 + ...e address of two variables using pointer.c | 20 + ...What happens if you free a pointer twice.c | 21 + ...given string is palindrome number or not.c | 18 + c/Basic/indirection in pointer.c | 40 ++ c/Basic/null pointer in c.c | 15 + c/README.md | 3 + css/README.md | 3 + ...skeleton (Basic Javascript Animation).html | 16 + ...ent-demo (Basic Javascript Animation).html | 29 + ...e-events (Basic Javascript Animation).html | 34 + ...position (Basic Javascript Animation).html | 27 + ...h-events (Basic Javascript Animation).html | 30 + ...d-events (Basic Javascript Animation).html | 26 + ...ey-codes (Basic Javascript Animation).html | 40 ++ ...ey-names (Basic Javascript Animation).html | 41 ++ html/Basics/A simple HTML document.html | 9 + html/Basics/Abbreviations and acronyms.html | 11 + html/Basics/Aligning images.html | 11 + ...rendering text on web pages using SVG.html | 24 + html/Basics/Checkboxes and radio buttons.html | 26 + ...roups - The col and colgroup elements.html | 22 + html/Basics/Computer output tags.html | 13 + html/Basics/Create hyperlink.html | 11 + .../Creating HTML5 color input type.html | 13 + .../Creating HTML5 date input type.html | 13 + .../Creating HTML5 datetime input type.html | 13 + ...ating HTML5 datetime-local input type.html | 13 + .../Creating HTML5 email input type.html | 21 + .../Creating HTML5 month input type.html | 13 + .../Creating HTML5 number input type.html | 22 + .../Creating HTML5 range input type.html | 13 + .../Creating HTML5 search input type.html | 13 + .../Basics/Creating HTML5 tel input type.html | 13 + .../Creating HTML5 time input type.html | 13 + .../Basics/Creating HTML5 url input type.html | 22 + .../Creating HTML5 week input type.html | 13 + html/Basics/Creating a circle using SVG.html | 17 + html/Basics/Creating a definition list.html | 16 + html/Basics/Creating a line using SVG.html | 17 + ...to link - A link that sends an e-mail.html | 12 + .../Creating a nested list - Multi level.html | 32 + ...Creating a nested list - Single level.html | 20 + .../Creating a rectangle using SVG.html | 17 + ...map - An image with clickable regions.html | 16 + html/Basics/Creating an ordered list.html | 15 + html/Basics/Creating an unordered list.html | 15 + html/Basics/Creating buttons.html | 11 + ...other HTML documents or Web resources.html | 12 + .../Creating password input fields.html | 13 + html/Basics/Creating text input fields.html | 12 + ...alternative sources for audio element.html | 14 + ...alternative sources for video element.html | 10 + .../Drawing a circle onto the canvas.html | 23 + .../Drawing a line onto the canvas.html | 24 + .../Drawing a rectangle onto the canvas.html | 23 + .../Drawing an arc onto the canvas.html | 23 + .../Embedding SVG into HTML documents.html | 15 + .../Embedding audio in HTML documents.html | 12 + .../Embedding canvas into HTML documents.html | 17 + ...g the YouTube video in HTML documents.html | 12 + .../Embedding video in HTML documents.html | 14 + ...ultiple selection inside a select box.html | 21 + html/Basics/File select field.html | 12 + ...lor inside a circular shape on canvas.html | 27 + ...or inside a rectangle shape on canvas.html | 27 + ... linear gradient inside canvas shapes.html | 28 + ... radial gradient inside canvas shapes.html | 28 + ...ouping of options inside a select box.html | 20 + html/Basics/Grouping similar form fields.html | 17 + html/Basics/Headings - h1 to h6.html | 15 + html/Basics/Insert contact information.html | 14 + ...TML documents using the embed element.html | 11 + ...ML documents using the object element.html | 11 + html/Basics/Inserting comments.html | 13 + html/Basics/Inserting horizontal lines.html | 11 + ...serting images into the HTML document.html | 14 + .../Inserting paragraphs of text content.html | 11 + ...TML documents using the embed element.html | 11 + ...ML documents using the object element.html | 10 + html/Basics/Linking the audio files.html | 11 + html/Basics/Long and short quotations.html | 12 + html/Basics/Make a hyperlink of an image.html | 9 + ...able - The most basic form of a table.html | 35 + .../Marking deleted and inserted text.html | 15 + html/Basics/Move outside of an iframe.html | 9 + .../Navigate inside page - Jump link.html | 10 + .../Open link in a new browser window.html | 9 + html/Basics/Paragraph and line breaks.html | 11 + ...ext (Preserve line breaks and spaces).html | 13 + ...Rendering text on web pages using SVG.html | 22 + .../Select box with a pre-selected value.html | 15 + .../Select boxes - A drop-down list.html | 15 + ...ble cells - The cellspacing attribute.html | 20 + ...ble cells - The cellpadding attribute.html | 20 + .../Setting text direction of an element.html | 9 + ...he cap style for the stroke on canvas.html | 26 + .../Setting the dimension of a table.html | 19 + ... the stroke color and width on canvas.html | 26 + ...etting width and height of the images.html | 14 + .../Specify headings for the content.html | 15 + html/Basics/Specify the table caption.html | 40 ++ html/Basics/Sub and Superscript text.html | 11 + ... - The use of submit and reset button.html | 14 + ...column - The rowspancolspan attribute.html | 50 ++ ...rs - Adding the default table borders.html | 19 + html/Basics/Text formatting.html | 19 + ...tarea - A multi-line text input field.html | 12 + html/Basics/Using image as a link.html | 9 + html/Basics/blockquote.html | 12 + html/Basics/definition_list.html | 17 + html/Basics/drag-and-drop.html | 128 ++++ html/Basics/drag-handle.html | 46 ++ html/Basics/draggable.html | 48 ++ html/Basics/home.html | 666 ++++++++++++++++++ html/Basics/kanban.html | 162 +++++ html/Basics/nested_list.html | 23 + html/Basics/paragraphs.html | 21 + html/Basics/separators.html | 12 + html/Basics/sortable.html | 103 +++ html/Basics/sorted_list.html | 17 + html/Basics/title.html | 15 + html/Basics/title_css.html | 16 + html/Basics/unsorted_list.html | 17 + html/README.md | 3 + .../A Ball Moving round the window.java | 153 ++++ java/Basics/Account application.java | 10 + java/Basics/Account this.java | 23 + java/Basics/Account.java | 23 + java/Basics/An interface.java | 57 ++ java/Basics/ArithmeticProgression.java | 44 ++ java/Basics/Armstrong (Java).java | 19 + java/Basics/Arrays and collections.java | 27 + java/Basics/Arrays of arrays.java | 32 + java/Basics/BasicDateFormatting.java | 38 + java/Basics/BinaryConverter (Java).java | 56 ++ java/Basics/Break statements.java | 32 + java/Basics/BubbleSort (Java).java | 37 + java/Basics/CLock CAN TAlk REALLy.java | 88 +++ .../Basics/Calculating compound interest.java | 29 + java/Basics/Calculator In Java.java | 157 +++++ ...ith both Standard and Scientific Mode.java | 634 +++++++++++++++++ .../Calling Windows Runtime Commands.java | 12 + java/Basics/Catching an exception.java | 15 + ...ck The Equality Of Two Arrays In Java.java | 27 + java/Basics/Complex.java | 60 ++ java/Basics/Constants.java | 24 + java/Basics/Constructors.java | 36 + java/Basics/Continue Statements.java | 17 + java/Basics/Coprimes.java | 42 ++ .../Demonstrating the runnable interface.java | 118 ++++ java/Basics/Deposit Account.java | 32 + java/Basics/Distance.java | 31 + java/Basics/Division.java | 87 +++ java/Basics/Factorial (Java).java | 13 + java/Basics/FastFourierTransform.java | 52 ++ java/Basics/Fibonacci (Java).java | 15 + java/Basics/FibonacciSequence.java | 135 ++++ java/Basics/For Loops.java | 26 + java/Basics/GetTheCurrentTime.java | 20 + java/Basics/GreatestCommonDivisor.java | 59 ++ java/Basics/Hanoi Algorithm Recursion.java | 23 + java/Basics/Horoscope.java | 73 ++ ...d time(Days, years , seconds) to Date.java | 15 + ... modification time of a file in java .java | 11 + java/Basics/How to compare two strings.java | 10 + ...vert a string totally into upper case.java | 8 + ...to display date in different formats .java | 16 + ...splay name of a month in (MMM) format.java | 11 + .../How to display name of the weekdays.java | 11 + ...lay time in different countrys format.java | 11 + ...to find which week of the year, month.java | 11 + java/Basics/How to format seconds.java | 9 + .../How to format time in 24 hour format.java | 9 + .../How to format time in AM-PM format.java | 10 + .../How to get a files size in bytes.java | 16 + ...get the maximum element from a vector.java | 14 + java/Basics/How to make a file read-only.java | 9 + .../How to match regions in strings.java | 9 + ... a particular character from a string.java | 9 + ...string inside a string by another one.java | 8 + java/Basics/How to reverse a String.java | 8 + .../How to reverse a string using stack.java | 53 ++ .../How to roll through hours & months.java | 13 + .../How to search a word inside a string.java | 11 + ...nce of a substring inside a substring.java | 12 + ... a string into a number of substrings.java | 23 + .../How to swap two elements in a vector.java | 16 + ...bers without using temporary variable.java | 16 + java/Basics/If Else Statement.java | 46 ++ java/Basics/InsertionSort (Java).java | 35 + java/Basics/Integers.java | 215 ++++++ java/Basics/Java Doc Comments.java | 40 ++ ...gram to convert Fahrenheit to Celsius.java | 14 + ...gram to display Current date and time.java | 22 + ...am to find all substrings of a string.java | 23 + ...program to perform garbage collection.java | 12 + .../Java program to transpose matrix.java | 31 + java/Basics/KnuthMorrisPratt.java | 56 ++ .../Basics/Letter combinations recursion.java | 31 + java/Basics/Listing all running threads.java | 42 ++ java/Basics/LongestCommonSubsequence.java | 175 +++++ java/Basics/LongestIncreasingSubsequence.java | 38 + java/Basics/Longs.java | 48 ++ java/Basics/Multiple Inheritance.java | 28 + java/Basics/Null Reference.java | 33 + java/Basics/Palindrome (Java).java | 19 + java/Basics/Pie Eater.java | 21 + java/Basics/Pie Maker.java | 27 + java/Basics/Pie exception.java | 16 + .../Pre and post increment operators.java | 34 + ...onverting numbers in a file to corres.java | 114 +++ java/Basics/Program for counting no.java | 35 + ...Program to Add of two matrices (Java).java | 36 + ...gram to Calculate Circle Area (Java).java | 51 ++ ...to Calculate Circle Perimeter (Java).java | 51 ++ ...rogram to Calculate Rect Area (Java).java | 56 ++ ...m to Calculate Rect Perimeter (Java).java | 56 ++ ...am to Find Even Or Odd Number (Java).java | 41 ++ ... Find Largest Smallest Number (Java).java | 32 + ...number in java without sorting (Java).java | 26 + ...g without repeating characters (Java).java | 78 ++ ... number between 1 to N numbers (Java).java | 37 + ...re sum of both ends are equal. (Java).java | 50 ++ ...by avoiding duplicate elements (Java).java | 33 + ...ogram to Multiply two matrices (Java).java | 52 ++ ... to Reverse Singly Linked List (Java).java | 121 ++++ .../Program to ReverseNumber (Java) v2.java | 20 + .../Program to ReverseNumber (Java).java | 31 + ... Stack using a temporary Stack (Java).java | 42 ++ .../Program to Swap Elements (Java).java | 40 ++ ...ements Without Third Variable (Java).java | 37 + ...ram to Write a singleton class (Java).java | 39 + ...number is binary number or not (Java).java | 38 + ...eck the input characcter for uppercas.java | 46 ++ ...vert binary to decimal number. (Java).java | 36 + ...cimal number to binary format. (Java).java | 28 + ...sing Integer.parseInt() method (Java).java | 28 + ...reate GUI for Bank Account Simulation.java | 135 ++++ ... deadlock between two threads. (Java).java | 57 ++ ...determine if a number is Prime (Java).java | 20 + ...en file. Remove special chars. (Java).java | 71 ++ ...n elements between two arrays. (Java).java | 26 + ...um repeated words from a file. (Java).java | 98 +++ ...nd missing numbers in an array (Java).java | 53 ++ ...licate characters in a string. (Java).java | 43 ++ ...to find perfect number or not. (Java).java | 42 ++ ... given number using recursion. (Java).java | 30 + ...f the first 1000 prime numbers (Java).java | 35 + ...wo maximum numbers in a array. (Java).java | 42 ++ ...characters in descending order (Java).java | 85 +++ ...ord count from the given file. (Java).java | 97 +++ ...word list from the given file. (Java).java | 71 ++ ...Program to implement ArrayList (Java).java | 105 +++ ...ogram to implement Gregorian Calendar.java | 72 ++ ...implement hashcode and equals. (Java).java | 81 +++ ... duplicates from sorted array. (Java).java | 45 ++ ...ing using recursive algorithm. (Java).java | 32 + ...rogram to sort a map by value. (Java).java | 41 ++ java/Basics/Raise Exceptions.java | 42 ++ java/Basics/Rotation.java | 93 +++ java/Basics/School Management System.java | 405 +++++++++++ java/Basics/SelectionSort (Java).java | 37 + ...round and background color to the tex.java | 186 +++++ java/Basics/Simple Arithmetic.java | 35 + java/Basics/Simple Inheritance.java | 51 ++ .../Simple Mathematical Calculations 2.java | 61 ++ .../Simple Mathematical Calculations.java | 51 ++ java/Basics/Simple Strings.java | 79 +++ java/Basics/SimpleWordCounter (Java).java | 39 + java/Basics/Stop watch programme.java | 83 +++ java/Basics/StringFunctions.java | 308 ++++++++ java/Basics/SubsequenceCounter.java | 60 ++ java/Basics/Swap two numbers.java | 22 + java/Basics/Switch Statements.java | 57 ++ java/Basics/This is a simple text clock.java | 60 ++ java/Basics/TimeQuery.java | 83 +++ java/Basics/TimeServer.java | 74 ++ java/Basics/Timer.java | 19 + java/Basics/TimerClient.java | 55 ++ java/Basics/To compare two strings.java | 23 + .../To find all substrings of a string.java | 28 + java/Basics/To reverse a string.java | 20 + java/Basics/Transfer Account.java | 24 + java/Basics/Try Finally.java | 21 + java/Basics/Try Pie Finally.java | 33 + java/Basics/Type Casting.java | 35 + java/Basics/Use of Runtime Class.java | 32 + java/Basics/Using Primitive Arrays.java | 43 ++ java/Basics/While Loops.java | 30 + java/Basics/WordCount (Java).java | 194 +++++ .../Working with static class members.java | 29 + ...o remove duplicates from sorted array.java | 33 + .../create list using an Array in java.java | 17 + ... array by avoiding duplicate elements.java | 24 + java/README.md | 3 + ... of the three of its sides are 5, 6, 7..js | 6 + ...int the contents of the current window..js | 4 + ...e string and attaching it to the front..js | 12 + ...ision of two numbers (input from user)..js | 13 + ...mber of days left until next Christmas..js | 9 + ...atures to and from celsius, fahrenheit..js | 17 + ... a leap year in the Gregorian calendar..js | 3 + ...t day and time in the following format..js | 38 + ...s being a Sunday between 2014 and 2050..js | 8 + ...Script program to get the current date..js | 22 + ... to get the website URL (loading page)..js | 2 + ... then prompted to input a guess number..js | 7 + js/README.md | 3 + perl/Basics/! $v1 && $v2.pl | 13 + ... that uses the pre-increment operation..pl | 8 + perl/Basics/Adding a number and a string.pl | 8 + perl/Basics/After incrementing.pl | 8 + perl/Basics/After pre-decrement.pl | 8 + perl/Basics/Arithmetic Operators in action.pl | 7 + perl/Basics/Assign value to four variables.pl | 10 + perl/Basics/Assignment Operators.pl | 15 + perl/Basics/Assignment Statements.pl | 14 + ... Autodecrement Operators and Assignment.pl | 15 + ...sic Math Compound Assignment Statements.pl | 24 + perl/Basics/Basic Numeric Operations.pl | 17 + .../Basics/Bitwise And Operators in action.pl | 7 + perl/Basics/Bitwise Logical Operators.pl | 7 + perl/Basics/Bitwise Or Operators in action.pl | 7 + perl/Basics/Bitwise operator.pl | 17 + perl/Basics/Boolean and &&.pl | 11 + perl/Basics/Boolean operator.pl | 15 + .../Built-in Perl Arithmetic Functions.pl | 27 + perl/Basics/Complex Assignment.pl | 16 + perl/Basics/Compound Assignment Operators.pl | 31 + perl/Basics/Compound operator.pl | 13 + ...fference between pre- and postincrement.pl | 11 + perl/Basics/Getting Input in Perl Scripts.pl | 14 + .../Increment and Decrement Operations.pl | 14 + perl/Basics/Logical Word Operators.pl | 11 + perl/Basics/Logical operators are defined.pl | 12 + ...TOR PURPOSENumeric operators.pl | 51 ++ .../Basics/Operating and Assigning at Once.pl | 14 + perl/Basics/Post-increment operation..pl | 7 + perl/Basics/Precedence and Associativity.pl | 22 + ...d operators and short-circuit operators.pl | 12 + ... input and use if statement to check it.pl | 24 + perl/Basics/Remainder and power.pl | 26 + perl/Basics/Short-circuit operators.pl | 15 + perl/Basics/Square $var.pl | 6 + perl/Basics/Subtract 1 from $var.pl | 7 + perl/Basics/The assignment operators.pl | 11 + perl/Basics/The autoincrement operator.pl | 9 + .../To set a variable, use the = operator.pl | 6 + ...s wherever possible to force precedence.pl | 22 + ...ssignment Operators on Scalar Variables.pl | 16 + ...ement operator for a string with digits.pl | 6 + ...ng auto-increment operator for a string.pl | 5 + perl/README.md | 3 + php/Basics/Add two numbers Program in PHP.php | 11 + .../Armstrong number Program in PHP.php | 26 + php/Basics/Even Odd number program in PHP.php | 14 + php/Basics/Factorial of a number in PHP.php | 16 + .../Fibonacci Series Program in PHP.php | 30 + php/Basics/Number Pattern Problems in PHP.php | 59 ++ .../PHP Program for Bubble sorting in PHP.php | 24 + ...rray without using any array functions.php | 15 + ...inding the smallest number in an array.php | 16 + ...ind whether a year is LEAP year or not.php | 14 + ...y until the result has a single digit..php | 16 + ...ers is a geometric progression or not..php | 28 + ...s is an arithmetic progression or not..php | 20 + ...n positive integer is a power of four..php | 22 + ... positive integer is a power of three..php | 22 + ...en positive integer is a power of two..php | 16 + ...is an anagram of another given string..php | 15 + ...teger is the power of another integer..php | 23 + ...ther a given number is an ugly number..php | 31 + ...urn the square root of a given number..php | 15 + ... and display the sum in reversed form..php | 21 + ...PHP program to find HCF of two numbers.php | 37 + ...find a missing number(s) from an array.php | 14 + ...nt appears three times except for one..php | 24 + ... in an array that doesn't occur twice..php | 20 + ...P program to find factor of any number.php | 17 + ... to find majority element in an array..php | 29 + .../PHP program to find table of a number.php | 16 + ...e length of the last word in a string..php | 23 + ...y element appears twice except for one.php | 15 + ...s and other numbers occur even number..php | 19 + ...utive numbers equal to a given number..php | 17 + ...hree consecutive numbers equal to zero.php | 20 + ...d whether a number is Armstrong or not.php | 26 + ...er a given number is a Hamming number..php | 41 ++ ...program to print Reverse of any number.php | 14 + ...push all zeros to the end of an array..php | 28 + ...bits of an integer (32 bits unsigned)..php | 15 + ...m to reverse the digits of an integer..php | 15 + ... even, divide it by 2 to get n (by) 2..php | 26 + .../Palindrome number Program in PHP.php | 24 + php/Basics/Pattern Problems in PHP.php | 406 +++++++++++ ...int Table of aby number Program in PHP.php | 23 + php/Basics/Print an array in PHP.php | 16 + .../Print an array using foreach in php.php | 11 + ...ts into a string with given delimiter..php | 7 + ...Program to create a Simple Calculator..php | 33 + ...ogin and Logout example using sessions.php | 56 ++ ...o find number of elements in an array..php | 7 + ... find prime numbers in between a Range.php | 33 + ...d the product of elements in an array..php | 6 + ... find the sum of elements in an array..php | 6 + ...join the array elements into a string..php | 7 + ... to merge two arrays into a new array..php | 9 + ...ve the duplicate values from an array..php | 6 + ...ements in an array in ascending order..php | 7 + ...ments in an array in descending order..php | 7 + ... an array elements based on delimiter..php | 7 + php/Basics/Reverse String Program in PHP.php | 25 + ...er using third variable program in PHP.php | 23 + ...ut using third variable program in PHP.php | 24 + php/README.md | 3 + ...ight of a triangle and compute the area.py | 6 + ...nd print a URL's content to the console.py | 7 + python/Basics/Access environment variables.py | 10 + .../Basics/Calculate midpoints of a line.py | 15 + ...culate number of days between two dates.py | 6 + ...e hypotenuse of a right angled triangle.py | 7 + ...ate the sum of the digits in an integer.py | 6 + ...e equal then return thrice of their sum.py | 10 + ... executing in 32bit or 64bit mode on OS.py | 3 + ...Compute the distance between two points.py | 7 + ...te all elements in a list into a string.py | 7 + .../Convert all units of time into seconds.py | 8 + ...ght (in feet and inches) to centimeters.py | 8 + ...nvert pressure in kilopascals to pounds.py | 7 + ...nce in feet to inches, yards, and miles.py | 8 + ...histogram from a given list of integers.py | 10 + .../Determine profiling of Python programs.py | 4 + .../Find out the number of CPUs using.py | 2 + ... and tuple with comma-separated numbers.py | 5 + ... name, platform and release information.py | 5 + ...ative integer) copies of a given string.py | 8 + ...7 return double the absolute difference.py | 8 + ...of the file that is currently executing.py | 2 + ...ilename and print the extension of that.py | 3 + ... (n) and computes the value of n+nn+nnn.py | 5 + ...radius of a circle and compute the area.py | 3 + ...List all files in a directory in Python.py | 4 + python/Basics/Measure execution time.py | 11 + ...reverse order with a space between them.py | 3 + python/Basics/Program to add two numbers.py | 10 + .../Program to calculate the square root.py | 9 + ...enerate a random number between 0 and 9.py | 6 + ...ay Powers of 2 Using Anonymous Function.py | 29 + .../Python Program to Add Two Matrices.py | 22 + ...ython Program to Check Armstrong Number.py | 20 + .../Python Program to Check Leap Year.py | 17 + .../Python Program to Check Prime Number.py | 22 + ...k Whether a String is Palindrome or Not.py | 17 + ...ram to Check if a Number is Odd or Even.py | 5 + ...rogram to Convert Celsius To Fahrenheit.py | 8 + ...nvert Decimal to Binary Using Recursion.py | 11 + ...ecimal to Binary, Octal and Hexadecimal.py | 9 + ... Program to Convert Kilometers to Miles.py | 11 + ...ogram to Count the Number of Each Vowel.py | 23 + .../Python Program to Display Calendar.py | 14 + ...play Fibonacci Sequence Using Recursion.py | 23 + ...ram to Display the multiplication Table.py | 11 + ...rogram to Find ASCII Value of Character.py | 9 + ...to Find Armstrong Number in an Interval.py | 26 + ...ind Factorial of Number Using Recursion.py | 23 + ...ython Program to Find Factors of Number.py | 18 + .../Python Program to Find HCF or GCD.py | 26 + .../Python Program to Find Hash of File.py | 27 + python/Basics/Python Program to Find LCM.py | 30 + ...ind Numbers Divisible by Another Number.py | 10 + ... Sum of Natural Numbers Using Recursion.py | 20 + ...ogram to Find the Factorial of a Number.py | 19 + ...to Find the Largest Among Three Numbers.py | 21 + ... to Find the Size (Resolution) of Image.py | 26 + ...o Find the Size (Resolution) of a Image.py | 24 + ...gram to Find the Sum of Natural Numbers.py | 17 + ... to Illustrate Different Set Operations.py | 17 + ...hon Program to Make a Simple Calculator.py | 44 ++ .../Basics/Python Program to Merge Mails.py | 20 + ...Python Program to Multiply Two Matrices.py | 25 + ... Print all Prime Numbers in an Interval.py | 20 + ...Program to Print the Fibonacci sequence.py | 29 + ...am to Remove Punctuations From a String.py | 16 + ...Python Program to Shuffle Deck of Cards.py | 15 + ...Program to Solve the quadratic equation.py | 22 + ...ogram to Sort Words in Alphabetic Order.py | 19 + .../Python Program to Transpose a Matrix.py | 17 + ...on Program to find the area of triangle.py | 17 + ...words in sorted form (alphanumerically).py | 3 + ...cters (character frequency) in a string.py | 10 + ...rences of each word in a given sentence.py | 13 + ...ed to '$', except the first char itself.py | 9 + ... the last 2 chars from a given a string.py | 9 + ...he the volume of a sphere with radius 6.py | 4 + .../Python program to swap two variables.py | 16 + ...hat input back in upper and lower cases.py | 3 + ...e equal or their sum or difference is 5.py | 9 + python/Basics/Sort files by date.py | 6 + .../Sum of the first n positive integers.py | 3 + ... a number is within 100 of 1000 or 2000.py | 6 + ...ether a passed letter is a vowel or not.py | 5 + python/README.md | 3 + ruby/Basics/CheckForPowerOfTwo.rb | 13 + ruby/Basics/CheckIFEvenOrOdd.rb | 12 + ruby/Basics/CountSetBits.rb | 12 + ruby/Basics/UnsetRightmostSetBit.rb | 8 + ruby/Basics/auth.rb | 45 ++ ruby/Basics/basic_game.rb | 19 + ruby/Basics/card_deck.rb | 14 + ruby/Basics/dependency_inversion.rb | 48 ++ ruby/Basics/family.rb | 8 + ruby/Basics/fibers.rb | 22 + ruby/Basics/fibonacci.rb | 4 + ruby/Basics/fighter.rb | 23 + ruby/Basics/game_rankings.rb | 17 + ruby/Basics/gil.rb | 25 + ruby/Basics/inheritance robots.rb | 15 + ruby/Basics/interface_segregation.rb | 96 +++ ruby/Basics/liskov_substitution.rb | 82 +++ ruby/Basics/mixins.rb | 15 + ruby/Basics/mutex.rb | 46 ++ ruby/Basics/names.rb | 8 + ruby/Basics/netflix.rb | 41 ++ ruby/Basics/open_close.rb | 84 +++ ruby/Basics/order.rb | 59 ++ ruby/Basics/phones.rb | 30 + ruby/Basics/rails.rb | 56 ++ ruby/Basics/single_responsibility.rb | 92 +++ ruby/Basics/sites.rb | 10 + ruby/Basics/towers.rb | 16 + ruby/README.md | 3 + 867 files changed, 35571 insertions(+) create mode 100644 assembly/README.md create mode 100644 c++/Basic/2D Array.cpp create mode 100644 c++/Basic/Add n numbers.cpp create mode 100644 c++/Basic/Add subtract multiply divide.cpp create mode 100644 c++/Basic/Addition of digits.cpp create mode 100644 c++/Basic/Addition of matrices.cpp create mode 100644 c++/Basic/Area of a triangle.cpp create mode 100644 c++/Basic/BellmanFord.cpp create mode 100644 c++/Basic/Binary Operator Overloading.cpp create mode 100644 c++/Basic/Binary Searching using recursion.cpp create mode 100644 c++/Basic/Binary to Decimal.cpp create mode 100644 c++/Basic/Binary to Hexadecimal.cpp create mode 100644 c++/Basic/Binary to Octal.cpp create mode 100644 c++/Basic/BinaryPow.cpp create mode 100644 c++/Basic/Check Positive or Negative.cpp create mode 100644 c++/Basic/Comparator.cpp create mode 100644 c++/Basic/ConvexHull.cpp create mode 100644 c++/Basic/Current Date.cpp create mode 100644 c++/Basic/Decimal to Binary.cpp create mode 100644 c++/Basic/Decimal to Octal.cpp create mode 100644 c++/Basic/Delete Vowels.cpp create mode 100644 c++/Basic/Diameter.cpp create mode 100644 c++/Basic/Dijkstra.cpp create mode 100644 c++/Basic/DijkstraHeap.cpp create mode 100644 c++/Basic/DisjointSets.cpp create mode 100644 c++/Basic/FFT.cpp create mode 100644 c++/Basic/FenwickTree.cpp create mode 100644 c++/Basic/FenwickTreeOnMap.cpp create mode 100644 c++/Basic/Find ASCII value of a character.cpp create mode 100644 c++/Basic/FindIntersection.cpp create mode 100644 c++/Basic/Get IP Address.cpp create mode 100644 c++/Basic/Hcf & Lcm.cpp create mode 100644 c++/Basic/KdTree.cpp create mode 100644 c++/Basic/Manacher.cpp create mode 100644 c++/Basic/Matrix.cpp create mode 100644 c++/Basic/MaxFlowDinic.cpp create mode 100644 c++/Basic/MaxMatching.cpp create mode 100644 c++/Basic/MinCostFlow.cpp create mode 100644 c++/Basic/MinCostFlowBF.cpp create mode 100644 c++/Basic/Odd or Even.cpp create mode 100644 c++/Basic/Pattern 1.cpp create mode 100644 c++/Basic/Pattern 10.cpp create mode 100644 c++/Basic/Pattern 2.cpp create mode 100644 c++/Basic/Pattern 3.cpp create mode 100644 c++/Basic/Pattern 4.cpp create mode 100644 c++/Basic/Pattern 5.cpp create mode 100644 c++/Basic/Pattern 6.cpp create mode 100644 c++/Basic/Pattern 7.cpp create mode 100644 c++/Basic/Pattern 8.cpp create mode 100644 c++/Basic/Pattern 9.cpp create mode 100644 c++/Basic/Prim.cpp create mode 100644 c++/Basic/PrimesGenerator.cpp create mode 100644 c++/Basic/Scanner.cpp create mode 100644 c++/Basic/Shutdown Computer.cpp create mode 100644 c++/Basic/SuffixArrayLcp.cpp create mode 100644 c++/Basic/TreeIsomorphism.cpp create mode 100644 c++/Basic/bigint-full.cpp create mode 100644 c++/Basic/bigint.cpp create mode 100644 c++/Basic/nCr & nPr.cpp create mode 100644 c++/Basic/polynom-roots.cpp create mode 100644 c++/Numerical_Problems/C++ Perform to a 2D FFT Inplace Given a Complex 2D Array.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Check Multiplicability of Two Matrices.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Check if a Matrix is Invertible.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Check if it is a Sparse Matrix.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Compute DFT Coefficients Directly.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Compute Determinant of a Matrix.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Compute Discrete Fourier Transform Using Naive Approach.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Emulate N Dice Roller.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Find Basis and Dimension of a Matrix.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Find Closest Pair of Points in an Array.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Find Factoial of Large Numbers.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Find Factoial of a Number using Dynamic Programming.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Find Factoial of a Number using Iteration.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Find Factorial of a Number using Recursion.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Find Fibonacci Numbers using Dynamic Programming.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Find Fibonacci Numbers using Iteration.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Find Fibonacci Numbers using Matrix Exponentiation.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Find Fibonacci Numbers using Recursion.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Find GCD of Two Numbers Using Recursive Euclid Algorithm.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Find Inverse of a Matrix.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Find Path Between Two Nodes in a Graph.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Find the GCD and LCM of n Numbers.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Generate N Number of Passwords of Length M Each.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Generate Prime Numbers Between a Given Range Using the Sieve of Sundaram.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Generate Random Hexadecimal Bytes.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Generate Random Numbers Using Middle Square Method.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Generate Random Numbers Using Multiply with Carry Method.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Generate Random Numbers Using Probability Distribution Function.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Generate Randomized Sequence of Given Range of Numbers.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Booth’s Multiplication Algorithm for Multiplication of 2 signed Numbers.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Coppersmith Freivald’s Algorithm.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Euler Theorem.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Extended Eucledian Algorithm.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Fermat Primality Test.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Fermat’s Little Theorem.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Fisher-Yates Algorithm for Array Shuffling.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Gauss Seidel Method.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Miller Rabin Primality Test.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Modular Exponentiation Algorithm.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Naor-Reingold Pseudo Random Function.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Park-Miller Random Number Generation Algorithm.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Russian Peasant Multiplication.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Segmented Sieve.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Sieve of Atkins.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Sieve of Eratosthenes.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Solovay-Strassen Primality Test.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement Strassen’s Algorithm.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement the Bin Packing Algorithm.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement the linear congruential generator for Pseudo Random Number Generation.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Optimize Wire Length in Electrical Circuit.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Perform Addition Operation Using Bitwise Operators.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Perform Encoding of a Message Using Matrix Multiplication.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Perform LU Decomposition of any Matrix.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Perform Matrix Multiplication.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Perform Optimal Paranthesization Using Dynamic Programming.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Perform Partition of an Integer in All Possible Ways.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Perform the Unique Factorization of a Given Number.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Represent Linear Equations in Matrix Form.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Solve Knapsack Problem Using Dynamic Programming.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Solve any Linear Equation in One Variable.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Solve the 0-1 Knapsack Problem.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Solve the Fractional Knapsack Problem.cpp create mode 100644 c++/Numerical_Problems/C++ Program to Use rand and srand Functions.cpp create mode 100644 c++/Numerical_Problems/C++ Program to implement Gauss Jordan Elimination algorithm..cpp create mode 100644 c++/Overview/C++ Program to Compare Two Strings Using Pointers.cpp create mode 100644 c++/Overview/C++ program to add two complex numbers.cpp create mode 100644 c++/Overview/C++ program to generate random numbers.cpp create mode 100644 c++/Overview/C++ program to reverse a number.cpp create mode 100644 c++/Overview/C++ program to swap two numbers using pointers.cpp create mode 100644 c++/Overview/CPP Program For Accessing Member Function Through Object.cpp create mode 100644 c++/Overview/CPP Program For Call By Reference.cpp create mode 100644 c++/Overview/CPP Program For Call By Value.cpp create mode 100644 c++/Overview/CPP Program For Constructor Over Loading.cpp create mode 100644 c++/Overview/CPP Program For Declaring Pointers as Class Member.cpp create mode 100644 c++/Overview/CPP Program For Declaring Static Members as Class Member.cpp create mode 100644 c++/Overview/CPP Program For Matrix Addition.cpp create mode 100644 c++/Overview/CPP Program For Parameterized Constructor.cpp create mode 100644 c++/Overview/CPP Program For Unary Operator Overloading.cpp create mode 100644 c++/Overview/CPP Program To Access Private and Protected Members Outside Classes Using Friend Function.cpp create mode 100644 c++/Overview/CPP Program To Implement Constructor and Destructor.cpp create mode 100644 c++/Overview/CPP Program To Implement Encapsulation.cpp create mode 100644 c++/Overview/CPP Program To Implement Function Overloading.cpp create mode 100644 c++/Overview/CPP Program To Implement Inheritance.cpp create mode 100644 c++/Overview/CPP Program To Implement Multiple Inheritance and also Passing Parameters To Base Class Constructors.cpp create mode 100644 c++/Overview/CPP Program To Implement Pure Virtual Function.cpp create mode 100644 c++/Overview/CPP Program To Implement Random Access File Handling.cpp create mode 100644 c++/Overview/CPP Program To Implement Sequential Access File Handling.cpp create mode 100644 c++/Overview/CPP Program To Implement Virtual Base Classes.cpp create mode 100644 c++/Overview/CPP Program To Implement Virtual Functions.cpp create mode 100644 c++/Overview/CPP Program To Overriding Template Function.cpp create mode 100644 c++/Overview/CPP Program for delete and new Operator Overloading.cpp create mode 100644 c++/Overview/CPP Program to Implement Operator Overloading Including Unary and Binary Operators.cpp create mode 100644 c++/Overview/CPP Program to Understanding Protected Qualifier Activities.cpp create mode 100644 c++/README.md create mode 100644 c++/Sets_&_Strings/C++ Program to Construct DFA from NFA.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Decode a Message Encoded Using Playfair Cipher.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Encode a Message Using Playfair Cipher.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Find Length of Longest Common Substring.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Find the Longest Increasing Subsequence of a Given Sequence.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement Affine Cipher.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement Aho-Corasick Algorithm for String Matching.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement Bitap Algorithm for String Matching.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement Boyer-Moore Algorithm for String Matching.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement Caesar Cypher.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement Kadane’s Algorithm.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement Knuth–Morris–Pratt Algorithm (KMP).cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement Levenshtein Distance Computing Algorithm.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement Longest Prefix Matching.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement Rabin-Karp Algorithm.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement String Matching Using Vectors.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement Wagner and Fisher Algorithm for online String Matching.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement Z-Algorithm.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement the Hill Cypher.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement the Monoalphabetic Cypher.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement the One Time Pad Algorithm.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement the RSA Algorithm.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement the String Search Algorithm for Short Text Sizes.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Implement the Vigenere Cypher.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Perform Cryptography Using Transposition Technique.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Perform Finite State Automaton based Search.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Perform Naive String Matching.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Perform String Matching Using String Library.cpp create mode 100644 c++/Sets_&_Strings/C++ Program to Repeatedly Search the Same Text (such as Bible by building a Data Structure).cpp create mode 100644 c-sharp/Basic/C# Program to Accept a Number from the user and Display it if it is Positive.cs create mode 100644 c-sharp/Basic/C# Program to Accept the Height of a Person & Categorize as Tall, Dwarf or Average.cs create mode 100644 c-sharp/Basic/C# Program to Calculate Acceleration.cs create mode 100644 c-sharp/Basic/C# Program to Check Whether the Entered Year is a Leap Year or Not.cs create mode 100644 c-sharp/Basic/C# Program to Check whether the Entered Number is Even or Odd.cs create mode 100644 c-sharp/Basic/C# Program to Check whether the given Integer has an Alternate Pattern.cs create mode 100644 c-sharp/Basic/C# Program to Compare Two Dates.cs create mode 100644 c-sharp/Basic/C# Program to Compute Average for the Set of Values.cs create mode 100644 c-sharp/Basic/C# Program to Count the Number of 1’s in the Entered Number.cs create mode 100644 c-sharp/Basic/C# Program to Create Sealed Class.cs create mode 100644 c-sharp/Basic/C# Program to Display All the Prime Numbers Between 1 to 100.cs create mode 100644 c-sharp/Basic/C# Program to Display Numbers in the form of Triangle.cs create mode 100644 c-sharp/Basic/C# Program to Display Squarefeet of a House.cs create mode 100644 c-sharp/Basic/C# Program to Display the ATM Transaction.cs create mode 100644 c-sharp/Basic/C# Program to Display the Date in Various Formats.cs create mode 100644 c-sharp/Basic/C# Program to Find Greatest among 2 numbers.cs create mode 100644 c-sharp/Basic/C# Program to Find Magnitude of Integer.cs create mode 100644 c-sharp/Basic/C# Program to Find a Number using Pythagoras Theorem.cs create mode 100644 c-sharp/Basic/C# Program to Generate Random Numbers.cs create mode 100644 c-sharp/Basic/C# Program to Get a Number and Display the Number with its Reverse.cs create mode 100644 c-sharp/Basic/C# Program to Get a Number and Display the Sum of the Digits.cs create mode 100644 c-sharp/Basic/C# Program to Illustrate LeftShift Operations.cs create mode 100644 c-sharp/Basic/C# Program to Illustrate the Use of Access Specifiers.cs create mode 100644 c-sharp/Basic/C# Program to Implement PhoneBook.cs create mode 100644 c-sharp/Basic/C# Program to Implement for-each in Inteface.cs create mode 100644 c-sharp/Basic/C# Program to Perform Division of Exponents of Same Base.cs create mode 100644 c-sharp/Basic/C# Program to Perform Unboxing Operation.cs create mode 100644 c-sharp/Basic/C# Program to Print a BinaryTriangle.cs create mode 100644 c-sharp/Basic/C# Program to Print a Diamond Using Nested Loop.cs create mode 100644 c-sharp/Basic/C# Program to Read a Grade & Display the Equivalent Description.cs create mode 100644 c-sharp/Basic/C# Program to Swap 2 Numbers.cs create mode 100644 c-sharp/Basic/C# Program to Swap the Contents of two Numbers using Bitwise XOR Operation.cs create mode 100644 c-sharp/Basic/C# Sharp program that takes a number as input and print its multiplication table.cs create mode 100644 c-sharp/Basic/C# Sharp program that takes an age (for example 20) as input and prints something as.cs create mode 100644 c-sharp/Basic/C# Sharp program that takes four numbers as input to calculate and print the average.cs create mode 100644 c-sharp/Basic/C# Sharp program to convert from celsius degrees to Kelvin and Fahrenheit.cs create mode 100644 c-sharp/Basic/C# Sharp program to print Hello and your name in a separate line.cs create mode 100644 c-sharp/Basic/C# Sharp program to print on screen the output of adding, subtracting, multiplying and dividing of two numbers which will be entered by the user.cs create mode 100644 c-sharp/Basic/C# Sharp program to print the output of multiplication of three numbers which will be entered by the user.cs create mode 100644 c-sharp/Basic/C# Sharp program to print the result of dividing two numbers.cs create mode 100644 c-sharp/Basic/C# Sharp program to print the result of the specified operations.cs create mode 100644 c-sharp/Basic/C# Sharp program to print the sum of two numbers.cs create mode 100644 c-sharp/Basic/C# Sharp program to swap two numbers.cs create mode 100644 c-sharp/Basic/C# Sharp program to that takes three numbers(x,y,z) as input and print the output of (x+y)úz and xúy + yúz.cs create mode 100644 c-sharp/Basic/C# program that takes a number as input and then displays a rectangle of 3 columns wide and 5 rows tall using that digit.cs create mode 100644 c-sharp/Basic/C# program to that takes a number as input and display it four times in a row (separated by blank spaces), and then four times in the next row, with no separation.cs create mode 100644 c-sharp/README.md create mode 100644 c/Basic/Accessing an array using pointers.c create mode 100644 c/Basic/C Program to Accept the Height of a Person & Categorize as Taller, Dwarf & Average.c create mode 100644 c/Basic/C Program to Accept two Integers and Check if they are Equal.c create mode 100644 c/Basic/C Program to Add two Complex Numbers.c create mode 100644 c/Basic/C Program to Calculate the Sum of Odd & Even Numbers.c create mode 100644 c/Basic/C Program to Check if a given Integer is Odd or Even.c create mode 100644 c/Basic/C Program to Check if a given Integer is Positive or Negative.c create mode 100644 c/Basic/C Program to Check whether a given Number is Armstrong.c create mode 100644 c/Basic/C Program to Check whether a given Number is Perfect Number.c create mode 100644 c/Basic/C Program to Check whether the given Number is Palindrome or not using Bitwise Operator.c create mode 100644 c/Basic/C Program to Compute First N Fibonacci Numbers using Command Line Arguments.c create mode 100644 c/Basic/C Program to Compute the Sum of Digits in a given Integer.c create mode 100644 c/Basic/C Program to Convert Binary Code of a Number into its Equivalent Gray’s Code using Recursion.c create mode 100644 c/Basic/C Program to Convert Binary Code of a Number into its Equivalent Gray’s Code without using Recursion.c create mode 100644 c/Basic/C Program to Convert Binary to Hexadecimal.c create mode 100644 c/Basic/C Program to Convert Binary to Octal.c create mode 100644 c/Basic/C Program to Convert Hexadecimal to Binary.c create mode 100644 c/Basic/C Program to Convert Numbers to Roman Numerals.c create mode 100644 c/Basic/C Program to Convert Octal to Binary.c create mode 100644 c/Basic/C Program to Convert Octal to Decimal.c create mode 100644 c/Basic/C Program to Convert Roman Number to Decimal Number.c create mode 100644 c/Basic/C Program to Convert a Decimal Number to Binary & Count the Number of 1s.c create mode 100644 c/Basic/C Program to Convert a Given Number of Days in terms of Years, Weeks & Days.c create mode 100644 c/Basic/C Program to Convert a Number Decimal System to Binary System using Recursion.c create mode 100644 c/Basic/C Program to Convert the given Binary Number into Decimal.c create mode 100644 c/Basic/C Program to Count Number of Words in a given Text Or Sentence.c create mode 100644 c/Basic/C Program to Count the Number of Occurrence of each Character Ignoring the Case of Alphabets & Display them.c create mode 100644 c/Basic/C Program to Count the Number of Unique Words.c create mode 100644 c/Basic/C Program to Count the Occurrences of each C Keyword using Array Structure.c create mode 100644 c/Basic/C Program to Display Function without using the Main Function.c create mode 100644 c/Basic/C Program to Display its own Source Code as its Output.c create mode 100644 c/Basic/C Program to Display the ATM Transaction.c create mode 100644 c/Basic/C Program to Display the IP Address of the System.c create mode 100644 c/Basic/C Program to Display the Inventory of Items in a Store.c create mode 100644 c/Basic/C Program to Extract Last two Digits of a given Year.c create mode 100644 c/Basic/C Program to Find Multiplication of two Binary Numbers.c create mode 100644 c/Basic/C Program to Find Product of 2 Numbers without using Recursion.c create mode 100644 c/Basic/C Program to Find Sum of Digits of a Number using Recursion.c create mode 100644 c/Basic/C Program to Find if a given Year is a Leap Year.c create mode 100644 c/Basic/C Program to Find the Biggest of 3 Numbers.c create mode 100644 c/Basic/C Program to Find the First Occurence of the any Character of String2 in string1 & also its Position.c create mode 100644 c/Basic/C Program to Find the Number of Integers Divisible by 5.c create mode 100644 c/Basic/C Program to Find the Size of a Union.c create mode 100644 c/Basic/C Program to Find the Sum of first 50 Natural Numbers using For Loop.c create mode 100644 c/Basic/C Program to Find the Sum of two Binary Numbers.c create mode 100644 c/Basic/C Program to Find whether a Number is Prime or Not using Recursion.c create mode 100644 c/Basic/C Program to Generate Fibonacci Series.c create mode 100644 c/Basic/C Program to Illustrate Pass by Reference.c create mode 100644 c/Basic/C Program to Illustrate Pass by Value.c create mode 100644 c/Basic/C Program to Illustrate how User Authentication is Done.c create mode 100644 c/Basic/C Program to Illustrate the Concept of Unions.c create mode 100644 c/Basic/C Program to Implements Regular Expression Matching.c create mode 100644 c/Basic/C Program to Input 2 Binary Strings and Print their Binary Sum.c create mode 100644 c/Basic/C Program to Input 3 Arguments and Operate Appropriately on the Numbers.c create mode 100644 c/Basic/C Program to Maintain an Inventory of items in Online Store.c create mode 100644 c/Basic/C Program to Multiply given Number by 4 using Bitwise Operators.c create mode 100644 c/Basic/C Program to Print Armstrong Number from 1 to 1000.c create mode 100644 c/Basic/C Program to Print Binary Equivalent of an Integer using Recursion.c create mode 100644 c/Basic/C Program to Print Combination of two Words of two given Strings without any Repetition.c create mode 100644 c/Basic/C Program to Print Diamond Pattern.c create mode 100644 c/Basic/C Program to Print a Semicolon without using a Semicolon anywhere in the Code.c create mode 100644 c/Basic/C Program to Print any Print Statement without using Semicolon.c create mode 100644 c/Basic/C Program to Print the Program Name and All its Arguments.c create mode 100644 c/Basic/C Program to Print the Words Ending with Letter S.c create mode 100644 c/Basic/C Program to Read Two Integers M and N & Swap their Values.c create mode 100644 c/Basic/C Program to Read a Grade & Display the Equivalent Description.c create mode 100644 c/Basic/C Program to Reverse a Given Number.c create mode 100644 c/Basic/C Program to Reverse a Number & Check if it is a Palindrome.c create mode 100644 c/Basic/C Program to Search a Word & Replace it with the Specified Word.c create mode 100644 c/Basic/C Program to Shutdown or Turn Off the Computer in Linux.c create mode 100644 c/Basic/C Program to Swap the Contents of two Numbers using Bitwise XOR Operation.c create mode 100644 c/Basic/C Program to Use Bitwise Operations to Count the Number of Leading Zero's in a Number x.c create mode 100644 c/Basic/C Program to calculate the total execution time of a program.c create mode 100644 c/Basic/C Program to find Product of 2 Numbers using Recursion.c create mode 100644 c/Basic/C Program to find Reverse of a Number using Recursion.c create mode 100644 c/Basic/C Program to find Sum of N Numbers using Recursion.c create mode 100644 c/Basic/C Program to next higher value of n with same 1's.c create mode 100644 c/Basic/C Program to replace first letter of every word with caps.c create mode 100644 c/Basic/C Program to sort string ignoring whitespaces and repeating characters only once.c create mode 100644 c/Basic/C program for Binary to decimal conversion.c create mode 100644 c/Basic/C program for decimal to octal converter.c create mode 100644 c/Basic/C program for hexadecimal to binary conversion.c create mode 100644 c/Basic/C program to Convert Decimal to Hexadecimal.c create mode 100644 c/Basic/C program to Convert Decimal to Octal.c create mode 100644 c/Basic/C program to Increase 1 to all of the given Integer Digit.c create mode 100644 c/Basic/C program to accept N numbers sorted in ascending order and to search for a given number using binary search..c create mode 100644 c/Basic/C program to accept an array of 10 elements and swap 3rd element with 4th element using pointers and display the results..c create mode 100644 c/Basic/C program to find the length of a string without using the built-in function also check whether it is a palindrome.c create mode 100644 c/Basic/C program to find the number of occurences of a given number in a list.c create mode 100644 c/Basic/C program to print hello world without using semicolon.c create mode 100644 c/Basic/C program to read an English sentence and replace lowercase characters by uppercase and vice-versa..c create mode 100644 c/Basic/C program to sort n given numbers using pointers.c create mode 100644 c/Basic/Can the size of an array be declared at runtime.c create mode 100644 c/Basic/Create and Use Your Own Header File in C Programming.c create mode 100644 c/Basic/Get Address of an array using Arrays and Pointers.c create mode 100644 c/Basic/Print mark-sheet of students.c create mode 100644 c/Basic/Reverse a string using pointers.c create mode 100644 c/Basic/Reverse the order of each word of the string using pointers.c create mode 100644 c/Basic/Show the ticking of Clock.c create mode 100644 c/Basic/Time functions in c.c create mode 100644 c/Basic/To compute the average of n given numbers using pointers.c create mode 100644 c/Basic/To compute the seconds from a given age using C.c create mode 100644 c/Basic/To find the maximum number within n given numbers using pointers.c create mode 100644 c/Basic/To swap the address of two variables using pointer.c create mode 100644 c/Basic/What happens if you free a pointer twice.c create mode 100644 c/Basic/Write a c program to check given string is palindrome number or not.c create mode 100644 c/Basic/indirection in pointer.c create mode 100644 c/Basic/null pointer in c.c create mode 100644 c/README.md create mode 100644 css/README.md create mode 100644 html/Basics/01-skeleton (Basic Javascript Animation).html create mode 100644 html/Basics/02-event-demo (Basic Javascript Animation).html create mode 100644 html/Basics/03-mouse-events (Basic Javascript Animation).html create mode 100644 html/Basics/04-mouse-position (Basic Javascript Animation).html create mode 100644 html/Basics/05-touch-events (Basic Javascript Animation).html create mode 100644 html/Basics/06-keyboard-events (Basic Javascript Animation).html create mode 100644 html/Basics/07-key-codes (Basic Javascript Animation).html create mode 100644 html/Basics/08-key-names (Basic Javascript Animation).html create mode 100644 html/Basics/A simple HTML document.html create mode 100644 html/Basics/Abbreviations and acronyms.html create mode 100644 html/Basics/Aligning images.html create mode 100644 html/Basics/Apply transformation while rendering text on web pages using SVG.html create mode 100644 html/Basics/Checkboxes and radio buttons.html create mode 100644 html/Basics/Column groups - The col and colgroup elements.html create mode 100644 html/Basics/Computer output tags.html create mode 100644 html/Basics/Create hyperlink.html create mode 100644 html/Basics/Creating HTML5 color input type.html create mode 100644 html/Basics/Creating HTML5 date input type.html create mode 100644 html/Basics/Creating HTML5 datetime input type.html create mode 100644 html/Basics/Creating HTML5 datetime-local input type.html create mode 100644 html/Basics/Creating HTML5 email input type.html create mode 100644 html/Basics/Creating HTML5 month input type.html create mode 100644 html/Basics/Creating HTML5 number input type.html create mode 100644 html/Basics/Creating HTML5 range input type.html create mode 100644 html/Basics/Creating HTML5 search input type.html create mode 100644 html/Basics/Creating HTML5 tel input type.html create mode 100644 html/Basics/Creating HTML5 time input type.html create mode 100644 html/Basics/Creating HTML5 url input type.html create mode 100644 html/Basics/Creating HTML5 week input type.html create mode 100644 html/Basics/Creating a circle using SVG.html create mode 100644 html/Basics/Creating a definition list.html create mode 100644 html/Basics/Creating a line using SVG.html create mode 100644 html/Basics/Creating a mailto link - A link that sends an e-mail.html create mode 100644 html/Basics/Creating a nested list - Multi level.html create mode 100644 html/Basics/Creating a nested list - Single level.html create mode 100644 html/Basics/Creating a rectangle using SVG.html create mode 100644 html/Basics/Creating an image-map - An image with clickable regions.html create mode 100644 html/Basics/Creating an ordered list.html create mode 100644 html/Basics/Creating an unordered list.html create mode 100644 html/Basics/Creating buttons.html create mode 100644 html/Basics/Creating links to other HTML documents or Web resources.html create mode 100644 html/Basics/Creating password input fields.html create mode 100644 html/Basics/Creating text input fields.html create mode 100644 html/Basics/Defining alternative sources for audio element.html create mode 100644 html/Basics/Defining alternative sources for video element.html create mode 100644 html/Basics/Drawing a circle onto the canvas.html create mode 100644 html/Basics/Drawing a line onto the canvas.html create mode 100644 html/Basics/Drawing a rectangle onto the canvas.html create mode 100644 html/Basics/Drawing an arc onto the canvas.html create mode 100644 html/Basics/Embedding SVG into HTML documents.html create mode 100644 html/Basics/Embedding audio in HTML documents.html create mode 100644 html/Basics/Embedding canvas into HTML documents.html create mode 100644 html/Basics/Embedding the YouTube video in HTML documents.html create mode 100644 html/Basics/Embedding video in HTML documents.html create mode 100644 html/Basics/Enable multiple selection inside a select box.html create mode 100644 html/Basics/File select field.html create mode 100644 html/Basics/Filling color inside a circular shape on canvas.html create mode 100644 html/Basics/Filling color inside a rectangle shape on canvas.html create mode 100644 html/Basics/Filling linear gradient inside canvas shapes.html create mode 100644 html/Basics/Filling radial gradient inside canvas shapes.html create mode 100644 html/Basics/Grouping of options inside a select box.html create mode 100644 html/Basics/Grouping similar form fields.html create mode 100644 html/Basics/Headings - h1 to h6.html create mode 100644 html/Basics/Insert contact information.html create mode 100644 html/Basics/Inserting audio in HTML documents using the embed element.html create mode 100644 html/Basics/Inserting audio in HTML documents using the object element.html create mode 100644 html/Basics/Inserting comments.html create mode 100644 html/Basics/Inserting horizontal lines.html create mode 100644 html/Basics/Inserting images into the HTML document.html create mode 100644 html/Basics/Inserting paragraphs of text content.html create mode 100644 html/Basics/Inserting video in HTML documents using the embed element.html create mode 100644 html/Basics/Inserting video in HTML documents using the object element.html create mode 100644 html/Basics/Linking the audio files.html create mode 100644 html/Basics/Long and short quotations.html create mode 100644 html/Basics/Make a hyperlink of an image.html create mode 100644 html/Basics/Making a simple table - The most basic form of a table.html create mode 100644 html/Basics/Marking deleted and inserted text.html create mode 100644 html/Basics/Move outside of an iframe.html create mode 100644 html/Basics/Navigate inside page - Jump link.html create mode 100644 html/Basics/Open link in a new browser window.html create mode 100644 html/Basics/Paragraph and line breaks.html create mode 100644 html/Basics/Preformatted text (Preserve line breaks and spaces).html create mode 100644 html/Basics/Rendering text on web pages using SVG.html create mode 100644 html/Basics/Select box with a pre-selected value.html create mode 100644 html/Basics/Select boxes - A drop-down list.html create mode 100644 html/Basics/Sets the distance between table cells - The cellspacing attribute.html create mode 100644 html/Basics/Sets the padding of table cells - The cellpadding attribute.html create mode 100644 html/Basics/Setting text direction of an element.html create mode 100644 html/Basics/Setting the cap style for the stroke on canvas.html create mode 100644 html/Basics/Setting the dimension of a table.html create mode 100644 html/Basics/Setting the stroke color and width on canvas.html create mode 100644 html/Basics/Setting width and height of the images.html create mode 100644 html/Basics/Specify headings for the content.html create mode 100644 html/Basics/Specify the table caption.html create mode 100644 html/Basics/Sub and Superscript text.html create mode 100644 html/Basics/Submit or reset a form - The use of submit and reset button.html create mode 100644 html/Basics/Table cells that span more than one rowcolumn - The rowspancolspan attribute.html create mode 100644 html/Basics/Tables with borders - Adding the default table borders.html create mode 100644 html/Basics/Text formatting.html create mode 100644 html/Basics/Textarea - A multi-line text input field.html create mode 100644 html/Basics/Using image as a link.html create mode 100644 html/Basics/blockquote.html create mode 100644 html/Basics/definition_list.html create mode 100644 html/Basics/drag-and-drop.html create mode 100644 html/Basics/drag-handle.html create mode 100644 html/Basics/draggable.html create mode 100644 html/Basics/home.html create mode 100644 html/Basics/kanban.html create mode 100644 html/Basics/nested_list.html create mode 100644 html/Basics/paragraphs.html create mode 100644 html/Basics/separators.html create mode 100644 html/Basics/sortable.html create mode 100644 html/Basics/sorted_list.html create mode 100644 html/Basics/title.html create mode 100644 html/Basics/title_css.html create mode 100644 html/Basics/unsorted_list.html create mode 100644 html/README.md create mode 100644 java/Basics/A Ball Moving round the window.java create mode 100644 java/Basics/Account application.java create mode 100644 java/Basics/Account this.java create mode 100644 java/Basics/Account.java create mode 100644 java/Basics/An interface.java create mode 100644 java/Basics/ArithmeticProgression.java create mode 100644 java/Basics/Armstrong (Java).java create mode 100644 java/Basics/Arrays and collections.java create mode 100644 java/Basics/Arrays of arrays.java create mode 100644 java/Basics/BasicDateFormatting.java create mode 100644 java/Basics/BinaryConverter (Java).java create mode 100644 java/Basics/Break statements.java create mode 100644 java/Basics/BubbleSort (Java).java create mode 100644 java/Basics/CLock CAN TAlk REALLy.java create mode 100644 java/Basics/Calculating compound interest.java create mode 100644 java/Basics/Calculator In Java.java create mode 100644 java/Basics/Calculator with both Standard and Scientific Mode.java create mode 100644 java/Basics/Calling Windows Runtime Commands.java create mode 100644 java/Basics/Catching an exception.java create mode 100644 java/Basics/Check The Equality Of Two Arrays In Java.java create mode 100644 java/Basics/Complex.java create mode 100644 java/Basics/Constants.java create mode 100644 java/Basics/Constructors.java create mode 100644 java/Basics/Continue Statements.java create mode 100644 java/Basics/Coprimes.java create mode 100644 java/Basics/Demonstrating the runnable interface.java create mode 100644 java/Basics/Deposit Account.java create mode 100644 java/Basics/Distance.java create mode 100644 java/Basics/Division.java create mode 100644 java/Basics/Factorial (Java).java create mode 100644 java/Basics/FastFourierTransform.java create mode 100644 java/Basics/Fibonacci (Java).java create mode 100644 java/Basics/FibonacciSequence.java create mode 100644 java/Basics/For Loops.java create mode 100644 java/Basics/GetTheCurrentTime.java create mode 100644 java/Basics/GreatestCommonDivisor.java create mode 100644 java/Basics/Hanoi Algorithm Recursion.java create mode 100644 java/Basics/Horoscope.java create mode 100644 java/Basics/How to add time(Days, years , seconds) to Date.java create mode 100644 java/Basics/How to change(set) or Get the last modification time of a file in java .java create mode 100644 java/Basics/How to compare two strings.java create mode 100644 java/Basics/How to convert a string totally into upper case.java create mode 100644 java/Basics/How to display date in different formats .java create mode 100644 java/Basics/How to display name of a month in (MMM) format.java create mode 100644 java/Basics/How to display name of the weekdays.java create mode 100644 java/Basics/How to display time in different countrys format.java create mode 100644 java/Basics/How to find which week of the year, month.java create mode 100644 java/Basics/How to format seconds.java create mode 100644 java/Basics/How to format time in 24 hour format.java create mode 100644 java/Basics/How to format time in AM-PM format.java create mode 100644 java/Basics/How to get a files size in bytes.java create mode 100644 java/Basics/How to get the maximum element from a vector.java create mode 100644 java/Basics/How to make a file read-only.java create mode 100644 java/Basics/How to match regions in strings.java create mode 100644 java/Basics/How to remove a particular character from a string.java create mode 100644 java/Basics/How to replace a substring inside a string by another one.java create mode 100644 java/Basics/How to reverse a String.java create mode 100644 java/Basics/How to reverse a string using stack.java create mode 100644 java/Basics/How to roll through hours & months.java create mode 100644 java/Basics/How to search a word inside a string.java create mode 100644 java/Basics/How to search last occurance of a substring inside a substring.java create mode 100644 java/Basics/How to split a string into a number of substrings.java create mode 100644 java/Basics/How to swap two elements in a vector.java create mode 100644 java/Basics/How to swap two numbers without using temporary variable.java create mode 100644 java/Basics/If Else Statement.java create mode 100644 java/Basics/InsertionSort (Java).java create mode 100644 java/Basics/Integers.java create mode 100644 java/Basics/Java Doc Comments.java create mode 100644 java/Basics/Java program to convert Fahrenheit to Celsius.java create mode 100644 java/Basics/Java program to display Current date and time.java create mode 100644 java/Basics/Java program to find all substrings of a string.java create mode 100644 java/Basics/Java program to perform garbage collection.java create mode 100644 java/Basics/Java program to transpose matrix.java create mode 100644 java/Basics/KnuthMorrisPratt.java create mode 100644 java/Basics/Letter combinations recursion.java create mode 100644 java/Basics/Listing all running threads.java create mode 100644 java/Basics/LongestCommonSubsequence.java create mode 100644 java/Basics/LongestIncreasingSubsequence.java create mode 100644 java/Basics/Longs.java create mode 100644 java/Basics/Multiple Inheritance.java create mode 100644 java/Basics/Null Reference.java create mode 100644 java/Basics/Palindrome (Java).java create mode 100644 java/Basics/Pie Eater.java create mode 100644 java/Basics/Pie Maker.java create mode 100644 java/Basics/Pie exception.java create mode 100644 java/Basics/Pre and post increment operators.java create mode 100644 java/Basics/Program for converting numbers in a file to corres.java create mode 100644 java/Basics/Program for counting no.java create mode 100644 java/Basics/Program to Add of two matrices (Java).java create mode 100644 java/Basics/Program to Calculate Circle Area (Java).java create mode 100644 java/Basics/Program to Calculate Circle Perimeter (Java).java create mode 100644 java/Basics/Program to Calculate Rect Area (Java).java create mode 100644 java/Basics/Program to Calculate Rect Perimeter (Java).java create mode 100644 java/Basics/Program to Find Even Or Odd Number (Java).java create mode 100644 java/Basics/Program to Find Largest Smallest Number (Java).java create mode 100644 java/Basics/Program to Find Second smallest number in java without sorting (Java).java create mode 100644 java/Basics/Program to Find longest substring without repeating characters (Java).java create mode 100644 java/Basics/Program to Find out duplicate number between 1 to N numbers (Java).java create mode 100644 java/Basics/Program to Find out middle index where sum of both ends are equal. (Java).java create mode 100644 java/Basics/Program to Get distinct elements from an array by avoiding duplicate elements (Java).java create mode 100644 java/Basics/Program to Multiply two matrices (Java).java create mode 100644 java/Basics/Program to Reverse Singly Linked List (Java).java create mode 100644 java/Basics/Program to ReverseNumber (Java) v2.java create mode 100644 java/Basics/Program to ReverseNumber (Java).java create mode 100644 java/Basics/Program to Sort a Stack using a temporary Stack (Java).java create mode 100644 java/Basics/Program to Swap Elements (Java).java create mode 100644 java/Basics/Program to Swap Elements Without Third Variable (Java).java create mode 100644 java/Basics/Program to Write a singleton class (Java).java create mode 100644 java/Basics/Program to check the given number is binary number or not (Java).java create mode 100644 java/Basics/Program to check the input characcter for uppercas.java create mode 100644 java/Basics/Program to convert binary to decimal number. (Java).java create mode 100644 java/Basics/Program to convert decimal number to binary format. (Java).java create mode 100644 java/Basics/Program to convert string to number without using Integer.parseInt() method (Java).java create mode 100644 java/Basics/Program to create GUI for Bank Account Simulation.java create mode 100644 java/Basics/Program to create deadlock between two threads. (Java).java create mode 100644 java/Basics/Program to determine if a number is Prime (Java).java create mode 100644 java/Basics/Program to find all distinct words from the given file. Remove special chars. (Java).java create mode 100644 java/Basics/Program to find common elements between two arrays. (Java).java create mode 100644 java/Basics/Program to find maximum repeated words from a file. (Java).java create mode 100644 java/Basics/Program to find missing numbers in an array (Java).java create mode 100644 java/Basics/Program to find out duplicate characters in a string. (Java).java create mode 100644 java/Basics/Program to find perfect number or not. (Java).java create mode 100644 java/Basics/Program to find sum of each digit in the given number using recursion. (Java).java create mode 100644 java/Basics/Program to find the sum of the first 1000 prime numbers (Java).java create mode 100644 java/Basics/Program to find top two maximum numbers in a array. (Java).java create mode 100644 java/Basics/Program to find two lines with max characters in descending order (Java).java create mode 100644 java/Basics/Program to get a line with max word count from the given file. (Java).java create mode 100644 java/Basics/Program to get distinct word list from the given file. (Java).java create mode 100644 java/Basics/Program to implement ArrayList (Java).java create mode 100644 java/Basics/Program to implement Gregorian Calendar.java create mode 100644 java/Basics/Program to implement hashcode and equals. (Java).java create mode 100644 java/Basics/Program to remove duplicates from sorted array. (Java).java create mode 100644 java/Basics/Program to reverse a string using recursive algorithm. (Java).java create mode 100644 java/Basics/Program to sort a map by value. (Java).java create mode 100644 java/Basics/Raise Exceptions.java create mode 100644 java/Basics/Rotation.java create mode 100644 java/Basics/School Management System.java create mode 100644 java/Basics/SelectionSort (Java).java create mode 100644 java/Basics/Set the foreground and background color to the tex.java create mode 100644 java/Basics/Simple Arithmetic.java create mode 100644 java/Basics/Simple Inheritance.java create mode 100644 java/Basics/Simple Mathematical Calculations 2.java create mode 100644 java/Basics/Simple Mathematical Calculations.java create mode 100644 java/Basics/Simple Strings.java create mode 100644 java/Basics/SimpleWordCounter (Java).java create mode 100644 java/Basics/Stop watch programme.java create mode 100644 java/Basics/StringFunctions.java create mode 100644 java/Basics/SubsequenceCounter.java create mode 100644 java/Basics/Swap two numbers.java create mode 100644 java/Basics/Switch Statements.java create mode 100644 java/Basics/This is a simple text clock.java create mode 100644 java/Basics/TimeQuery.java create mode 100644 java/Basics/TimeServer.java create mode 100644 java/Basics/Timer.java create mode 100644 java/Basics/TimerClient.java create mode 100644 java/Basics/To compare two strings.java create mode 100644 java/Basics/To find all substrings of a string.java create mode 100644 java/Basics/To reverse a string.java create mode 100644 java/Basics/Transfer Account.java create mode 100644 java/Basics/Try Finally.java create mode 100644 java/Basics/Try Pie Finally.java create mode 100644 java/Basics/Type Casting.java create mode 100644 java/Basics/Use of Runtime Class.java create mode 100644 java/Basics/Using Primitive Arrays.java create mode 100644 java/Basics/While Loops.java create mode 100644 java/Basics/WordCount (Java).java create mode 100644 java/Basics/Working with static class members.java create mode 100644 java/Basics/Write a program to remove duplicates from sorted array.java create mode 100644 java/Basics/create list using an Array in java.java create mode 100644 java/Basics/distinct elements from an array by avoiding duplicate elements.java create mode 100644 java/README.md create mode 100644 js/Basic/Find the area of a triangle where lengths of the three of its sides are 5, 6, 7..js create mode 100644 js/Basic/Print the contents of the current window..js create mode 100644 js/Basic/Rotate the string 'w3resource' in right direction by periodically removing one letter from the end of the string and attaching it to the front..js create mode 100644 js/Basic/Write a JavaScript program to calculate multiplication and division of two numbers (input from user)..js create mode 100644 js/Basic/Write a JavaScript program to calculate number of days left until next Christmas..js create mode 100644 js/Basic/Write a JavaScript program to convert temperatures to and from celsius, fahrenheit..js create mode 100644 js/Basic/Write a JavaScript program to determine whether a given year is a leap year in the Gregorian calendar..js create mode 100644 js/Basic/Write a JavaScript program to display the current day and time in the following format..js create mode 100644 js/Basic/Write a JavaScript program to find which 1st January is being a Sunday between 2014 and 2050..js create mode 100644 js/Basic/Write a JavaScript program to get the current date..js create mode 100644 js/Basic/Write a JavaScript program to get the website URL (loading page)..js create mode 100644 js/Basic/Write a JavaScript program where the program takes a random integer between 1 to 10, the user is then prompted to input a guess number..js create mode 100644 js/README.md create mode 100644 perl/Basics/! $v1 && $v2.pl create mode 100644 perl/Basics/A program that uses the pre-increment operation..pl create mode 100644 perl/Basics/Adding a number and a string.pl create mode 100644 perl/Basics/After incrementing.pl create mode 100644 perl/Basics/After pre-decrement.pl create mode 100644 perl/Basics/Arithmetic Operators in action.pl create mode 100644 perl/Basics/Assign value to four variables.pl create mode 100644 perl/Basics/Assignment Operators.pl create mode 100644 perl/Basics/Assignment Statements.pl create mode 100644 perl/Basics/Autoincrement and Autodecrement Operators and Assignment.pl create mode 100644 perl/Basics/Basic Math Compound Assignment Statements.pl create mode 100644 perl/Basics/Basic Numeric Operations.pl create mode 100644 perl/Basics/Bitwise And Operators in action.pl create mode 100644 perl/Basics/Bitwise Logical Operators.pl create mode 100644 perl/Basics/Bitwise Or Operators in action.pl create mode 100644 perl/Basics/Bitwise operator.pl create mode 100644 perl/Basics/Boolean and &&.pl create mode 100644 perl/Basics/Boolean operator.pl create mode 100644 perl/Basics/Built-in Perl Arithmetic Functions.pl create mode 100644 perl/Basics/Complex Assignment.pl create mode 100644 perl/Basics/Compound Assignment Operators.pl create mode 100644 perl/Basics/Compound operator.pl create mode 100644 perl/Basics/Demonstrates the difference between pre- and postincrement.pl create mode 100644 perl/Basics/Getting Input in Perl Scripts.pl create mode 100644 perl/Basics/Increment and Decrement Operations.pl create mode 100644 perl/Basics/Logical Word Operators.pl create mode 100644 perl/Basics/Logical operators are defined.pl create mode 100644 perl/Basics/OPERATOR PURPOSENumeric operators.pl create mode 100644 perl/Basics/Operating and Assigning at Once.pl create mode 100644 perl/Basics/Post-increment operation..pl create mode 100644 perl/Basics/Precedence and Associativity.pl create mode 100644 perl/Basics/Precedence with word operators and short-circuit operators.pl create mode 100644 perl/Basics/Read user input and use if statement to check it.pl create mode 100644 perl/Basics/Remainder and power.pl create mode 100644 perl/Basics/Short-circuit operators.pl create mode 100644 perl/Basics/Square $var.pl create mode 100644 perl/Basics/Subtract 1 from $var.pl create mode 100644 perl/Basics/The assignment operators.pl create mode 100644 perl/Basics/The autoincrement operator.pl create mode 100644 perl/Basics/To set a variable, use the = operator.pl create mode 100644 perl/Basics/Use parentheses wherever possible to force precedence.pl create mode 100644 perl/Basics/Using Assignment Operators on Scalar Variables.pl create mode 100644 perl/Basics/Using auto-increment operator for a string with digits.pl create mode 100644 perl/Basics/Using auto-increment operator for a string.pl create mode 100644 perl/README.md create mode 100644 php/Basics/Add two numbers Program in PHP.php create mode 100644 php/Basics/Armstrong number Program in PHP.php create mode 100644 php/Basics/Even Odd number program in PHP.php create mode 100644 php/Basics/Factorial of a number in PHP.php create mode 100644 php/Basics/Fibonacci Series Program in PHP.php create mode 100644 php/Basics/Number Pattern Problems in PHP.php create mode 100644 php/Basics/PHP Program for Bubble sorting in PHP.php create mode 100644 php/Basics/PHP Program for finding the biggest number in an array without using any array functions.php create mode 100644 php/Basics/PHP Program for finding the smallest number in an array.php create mode 100644 php/Basics/PHP Program to find whether a year is LEAP year or not.php create mode 100644 php/Basics/PHP program to add the digits of a positive integer repeatedly until the result has a single digit..php create mode 100644 php/Basics/PHP program to check a sequence of numbers is a geometric progression or not..php create mode 100644 php/Basics/PHP program to check a sequence of numbers is an arithmetic progression or not..php create mode 100644 php/Basics/PHP program to check if a given positive integer is a power of four..php create mode 100644 php/Basics/PHP program to check if a given positive integer is a power of three..php create mode 100644 php/Basics/PHP program to check if a given positive integer is a power of two..php create mode 100644 php/Basics/PHP program to check if a given string is an anagram of another given string..php create mode 100644 php/Basics/PHP program to check if an integer is the power of another integer..php create mode 100644 php/Basics/PHP program to check whether a given number is an ugly number..php create mode 100644 php/Basics/PHP program to compute and return the square root of a given number..php create mode 100644 php/Basics/PHP program to compute the sum of the two reversed numbers and display the sum in reversed form..php create mode 100644 php/Basics/PHP program to find HCF of two numbers.php create mode 100644 php/Basics/PHP program to find a missing number(s) from an array.php create mode 100644 php/Basics/PHP program to find a single element in an array where every element appears three times except for one..php create mode 100644 php/Basics/PHP program to find a single number in an array that doesn't occur twice..php create mode 100644 php/Basics/PHP program to find factor of any number.php create mode 100644 php/Basics/PHP program to find majority element in an array..php create mode 100644 php/Basics/PHP program to find table of a number.php create mode 100644 php/Basics/PHP program to find the length of the last word in a string..php create mode 100644 php/Basics/PHP program to find the single element appears once in an array where every element appears twice except for one.php create mode 100644 php/Basics/PHP program to find the single number which occurs odd numbers and other numbers occur even number..php create mode 100644 php/Basics/PHP program to find three numbers from an array such that the sum of three consecutive numbers equal to a given number..php create mode 100644 php/Basics/PHP program to find three numbers from an array such that the sum of three consecutive numbers equal to zero.php create mode 100644 php/Basics/PHP program to find whether a number is Armstrong or not.php create mode 100644 php/Basics/PHP program to get the Hamming numbers upto a given numbers also check whether a given number is a Hamming number..php create mode 100644 php/Basics/PHP program to print Reverse of any number.php create mode 100644 php/Basics/PHP program to push all zeros to the end of an array..php create mode 100644 php/Basics/PHP program to reverse the bits of an integer (32 bits unsigned)..php create mode 100644 php/Basics/PHP program to reverse the digits of an integer..php create mode 100644 php/Basics/PHP program where you take any positive integer n, if n is even, divide it by 2 to get n (by) 2..php create mode 100644 php/Basics/Palindrome number Program in PHP.php create mode 100644 php/Basics/Pattern Problems in PHP.php create mode 100644 php/Basics/Print Table of aby number Program in PHP.php create mode 100644 php/Basics/Print an array in PHP.php create mode 100644 php/Basics/Print an array using foreach in php.php create mode 100644 php/Basics/Program to combine the array elements into a string with given delimiter..php create mode 100644 php/Basics/Program to create a Simple Calculator..php create mode 100644 php/Basics/Program to create simple Login and Logout example using sessions.php create mode 100644 php/Basics/Program to find number of elements in an array..php create mode 100644 php/Basics/Program to find prime numbers in between a Range.php create mode 100644 php/Basics/Program to find the product of elements in an array..php create mode 100644 php/Basics/Program to find the sum of elements in an array..php create mode 100644 php/Basics/Program to join the array elements into a string..php create mode 100644 php/Basics/Program to merge two arrays into a new array..php create mode 100644 php/Basics/Program to remove the duplicate values from an array..php create mode 100644 php/Basics/Program to sort elements in an array in ascending order..php create mode 100644 php/Basics/Program to sort elements in an array in descending order..php create mode 100644 php/Basics/Program to split a string into an array elements based on delimiter..php create mode 100644 php/Basics/Reverse String Program in PHP.php create mode 100644 php/Basics/Swap two number using third variable program in PHP.php create mode 100644 php/Basics/Swap two number without using third variable program in PHP.php create mode 100644 php/README.md create mode 100644 python/Basics/Accept the base and height of a triangle and compute the area.py create mode 100644 python/Basics/Access and print a URL's content to the console.py create mode 100644 python/Basics/Access environment variables.py create mode 100644 python/Basics/Calculate midpoints of a line.py create mode 100644 python/Basics/Calculate number of days between two dates.py create mode 100644 python/Basics/Calculate the hypotenuse of a right angled triangle.py create mode 100644 python/Basics/Calculate the sum of the digits in an integer.py create mode 100644 python/Basics/Calculate the sum of three given numbers, if the values are equal then return thrice of their sum.py create mode 100644 python/Basics/Check whether Python shell is executing in 32bit or 64bit mode on OS.py create mode 100644 python/Basics/Compute the distance between two points.py create mode 100644 python/Basics/Concatenate all elements in a list into a string.py create mode 100644 python/Basics/Convert all units of time into seconds.py create mode 100644 python/Basics/Convert height (in feet and inches) to centimeters.py create mode 100644 python/Basics/Convert pressure in kilopascals to pounds.py create mode 100644 python/Basics/Convert the distance in feet to inches, yards, and miles.py create mode 100644 python/Basics/Create a histogram from a given list of integers.py create mode 100644 python/Basics/Determine profiling of Python programs.py create mode 100644 python/Basics/Find out the number of CPUs using.py create mode 100644 python/Basics/Generate a list and tuple with comma-separated numbers.py create mode 100644 python/Basics/Get OS name, platform and release information.py create mode 100644 python/Basics/Get a string which is n (non-negative integer) copies of a given string.py create mode 100644 python/Basics/Get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference.py create mode 100644 python/Basics/Get the path and name of the file that is currently executing.py create mode 100644 python/Basics/Input a filename and print the extension of that.py create mode 100644 python/Basics/Input an integer (n) and computes the value of n+nn+nnn.py create mode 100644 python/Basics/Input the radius of a circle and compute the area.py create mode 100644 python/Basics/List all files in a directory in Python.py create mode 100644 python/Basics/Measure execution time.py create mode 100644 python/Basics/Print first and last name in reverse order with a space between them.py create mode 100644 python/Basics/Program to add two numbers.py create mode 100644 python/Basics/Program to calculate the square root.py create mode 100644 python/Basics/Program to generate a random number between 0 and 9.py create mode 100644 python/Basics/Python Program To Display Powers of 2 Using Anonymous Function.py create mode 100644 python/Basics/Python Program to Add Two Matrices.py create mode 100644 python/Basics/Python Program to Check Armstrong Number.py create mode 100644 python/Basics/Python Program to Check Leap Year.py create mode 100644 python/Basics/Python Program to Check Prime Number.py create mode 100644 python/Basics/Python Program to Check Whether a String is Palindrome or Not.py create mode 100644 python/Basics/Python Program to Check if a Number is Odd or Even.py create mode 100644 python/Basics/Python Program to Convert Celsius To Fahrenheit.py create mode 100644 python/Basics/Python Program to Convert Decimal to Binary Using Recursion.py create mode 100644 python/Basics/Python Program to Convert Decimal to Binary, Octal and Hexadecimal.py create mode 100644 python/Basics/Python Program to Convert Kilometers to Miles.py create mode 100644 python/Basics/Python Program to Count the Number of Each Vowel.py create mode 100644 python/Basics/Python Program to Display Calendar.py create mode 100644 python/Basics/Python Program to Display Fibonacci Sequence Using Recursion.py create mode 100644 python/Basics/Python Program to Display the multiplication Table.py create mode 100644 python/Basics/Python Program to Find ASCII Value of Character.py create mode 100644 python/Basics/Python Program to Find Armstrong Number in an Interval.py create mode 100644 python/Basics/Python Program to Find Factorial of Number Using Recursion.py create mode 100644 python/Basics/Python Program to Find Factors of Number.py create mode 100644 python/Basics/Python Program to Find HCF or GCD.py create mode 100644 python/Basics/Python Program to Find Hash of File.py create mode 100644 python/Basics/Python Program to Find LCM.py create mode 100644 python/Basics/Python Program to Find Numbers Divisible by Another Number.py create mode 100644 python/Basics/Python Program to Find Sum of Natural Numbers Using Recursion.py create mode 100644 python/Basics/Python Program to Find the Factorial of a Number.py create mode 100644 python/Basics/Python Program to Find the Largest Among Three Numbers.py create mode 100644 python/Basics/Python Program to Find the Size (Resolution) of Image.py create mode 100644 python/Basics/Python Program to Find the Size (Resolution) of a Image.py create mode 100644 python/Basics/Python Program to Find the Sum of Natural Numbers.py create mode 100644 python/Basics/Python Program to Illustrate Different Set Operations.py create mode 100644 python/Basics/Python Program to Make a Simple Calculator.py create mode 100644 python/Basics/Python Program to Merge Mails.py create mode 100644 python/Basics/Python Program to Multiply Two Matrices.py create mode 100644 python/Basics/Python Program to Print all Prime Numbers in an Interval.py create mode 100644 python/Basics/Python Program to Print the Fibonacci sequence.py create mode 100644 python/Basics/Python Program to Remove Punctuations From a String.py create mode 100644 python/Basics/Python Program to Shuffle Deck of Cards.py create mode 100644 python/Basics/Python Program to Solve the quadratic equation.py create mode 100644 python/Basics/Python Program to Sort Words in Alphabetic Order.py create mode 100644 python/Basics/Python Program to Transpose a Matrix.py create mode 100644 python/Basics/Python Program to find the area of triangle.py create mode 100644 python/Basics/Python program that accepts a comma separated sequence of words as input and prints the unique words in sorted form (alphanumerically).py create mode 100644 python/Basics/Python program to count the number of characters (character frequency) in a string.py create mode 100644 python/Basics/Python program to count the occurrences of each word in a given sentence.py create mode 100644 python/Basics/Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.py create mode 100644 python/Basics/Python program to get a string made of the first 2 and the last 2 chars from a given a string.py create mode 100644 python/Basics/Python program to get the the volume of a sphere with radius 6.py create mode 100644 python/Basics/Python program to swap two variables.py create mode 100644 python/Basics/Python script that takes input from the user and displays that input back in upper and lower cases.py create mode 100644 python/Basics/Return true if the two given int values are equal or their sum or difference is 5.py create mode 100644 python/Basics/Sort files by date.py create mode 100644 python/Basics/Sum of the first n positive integers.py create mode 100644 python/Basics/Test whether a number is within 100 of 1000 or 2000.py create mode 100644 python/Basics/Test whether a passed letter is a vowel or not.py create mode 100644 python/README.md create mode 100644 ruby/Basics/CheckForPowerOfTwo.rb create mode 100644 ruby/Basics/CheckIFEvenOrOdd.rb create mode 100644 ruby/Basics/CountSetBits.rb create mode 100644 ruby/Basics/UnsetRightmostSetBit.rb create mode 100644 ruby/Basics/auth.rb create mode 100644 ruby/Basics/basic_game.rb create mode 100644 ruby/Basics/card_deck.rb create mode 100644 ruby/Basics/dependency_inversion.rb create mode 100644 ruby/Basics/family.rb create mode 100644 ruby/Basics/fibers.rb create mode 100644 ruby/Basics/fibonacci.rb create mode 100644 ruby/Basics/fighter.rb create mode 100644 ruby/Basics/game_rankings.rb create mode 100644 ruby/Basics/gil.rb create mode 100644 ruby/Basics/inheritance robots.rb create mode 100644 ruby/Basics/interface_segregation.rb create mode 100644 ruby/Basics/liskov_substitution.rb create mode 100644 ruby/Basics/mixins.rb create mode 100644 ruby/Basics/mutex.rb create mode 100644 ruby/Basics/names.rb create mode 100644 ruby/Basics/netflix.rb create mode 100644 ruby/Basics/open_close.rb create mode 100644 ruby/Basics/order.rb create mode 100644 ruby/Basics/phones.rb create mode 100644 ruby/Basics/rails.rb create mode 100644 ruby/Basics/single_responsibility.rb create mode 100644 ruby/Basics/sites.rb create mode 100644 ruby/Basics/towers.rb create mode 100644 ruby/README.md diff --git a/assembly/README.md b/assembly/README.md new file mode 100644 index 0000000..68c685a --- /dev/null +++ b/assembly/README.md @@ -0,0 +1,3 @@ +# Assembly language + +An assembly language is an extremely low-level programming language that has a 1-to-1 correspondence to machine code — the series of binary instructions which move values in and out of registers in a CPU (or other microprocessor) \ No newline at end of file diff --git a/c++/Basic/2D Array.cpp b/c++/Basic/2D Array.cpp new file mode 100644 index 0000000..eecea09 --- /dev/null +++ b/c++/Basic/2D Array.cpp @@ -0,0 +1,43 @@ +#include +#define size 16 +using namespace std; + +int main () +{ + int m,n; + int a[size][size]; + cout<<"Enter the number of rows"<>m; + cout<<"Enter the number of columns"<>n; + cout<<"Enter the Elements in Table"<>a[i][j]; + } + } +// output each array element"s value + for ( int i = 0; i < m; i++ ) + for ( int j = 0; j < n; j++ ) + { + cout << "a[" << i << "][" << j << "]: "; + cout << a[i][j]<< endl; + } + return 0; +} + +Output: +Enter the number of rows +2 +Enter the number of columns +3 +Enter the Elements in Table +1 2 3 4 5 6 +a[0][0]: 1 +a[0][1]: 2 +a[0][2]: 3 +a[1][0]: 4 +a[1][1]: 5 +a[1][2]: 6 \ No newline at end of file diff --git a/c++/Basic/Add n numbers.cpp b/c++/Basic/Add n numbers.cpp new file mode 100644 index 0000000..7c89624 --- /dev/null +++ b/c++/Basic/Add n numbers.cpp @@ -0,0 +1,17 @@ +#include < iostream.h > + +int main() +{ + int n, sum = 0, c, value; + cout<<"Enter the number of integers you want to add\n"; + cin>>n; + cout<<"Enter"<>value; + sum = sum + value; + /*adding each no in sum*/ + } + cout<<"Sum of entered integers ="< + +int main() +{ + int first, second, add, subtract, multiply; + float divide; + cout<<"Enter two integers\n"; + cin>>first>>second; + add = first + second; + subtract = first - second; + multiply = first * second; + divide = first / (float)second; +//typecasting + cout<<"Sum = "< +int main() +{ + int n, sum = 0, remainder; + cout<<"Enter an integer\n"; + cin>>n; + while(n != 0) + { + remainder = n % 10; + /*stores unit place digit to remainder*/ + sum = sum + remainder; + n = n / 10; + /*dividing no to discard unit place digit*/ + } + cout<<"Sum of digits of entered number = "< + +int main() +{ + int m, n, c, d, first[10][10], second[10][10], sum[10][10]; + cout<<"Enter the number of rows and columns of matrix\n"; + cin>>m>>n; + cout<<"Enter the elements of first matrix\n"; + for ( c = 0 ; c < m ; c++ ) + for ( d = 0 ; d < n ; d++ ) + cin>>first[c][d]; + cout<<"Enter the elements of second matrix\n"; + for ( c = 0 ; c < m ; c++ ) + for ( d = 0 ; d < n ; d++ ) + cin>>second[c][d]; + for ( c = 0 ; c < m ; c++ ) + for ( d = 0 ; d < n ; d++ ) + sum[c][d] = first[c][d] + second[c][d]; + /* Matrix addition */ + cout<<"Sum of entered matrices:-\n"; + for ( c = 0 ; c < m ; c++ ) + { + for ( d = 0 ; d < n ; d++ ) + cout< + +void main() +{ + int height, base; + float ans;/*ans may come in fractions*/ + cout<<"Enter height and base"; + cin>>height>>base; + ans= (1/2)*height*base; + /* mathematical formula*/ + cout<<"Area if triangle is"< +#include +#include +using namespace std; + +typedef pair pii; +typedef vector > Graph; + +const int INF = INT_MAX / 3; + +bool bellmanFord(Graph &g, int s, vector &prio, vector &pred) { + int n = g.size(); + pred.assign(n, -1); + prio.assign(n, INF); + prio[s] = 0; + bool wasChanged = true; + for (int k = 0; k < n; k++) { + wasChanged = false; + for (int u = 0; u < n; u++) { + for (int i = 0; i < (int) g[u].size(); i++) { + int v = g[u][i].first; + int cost = g[u][i].second; + if (prio[v] > prio[u] + cost) { + prio[v] = prio[u] + cost; + pred[v] = u; + wasChanged = true; + } + } + } + if (!wasChanged) + break; + } + // wasChanged is true iff graph has a negative cycle + return wasChanged; +} + +vector findNegativeCycle(Graph &g) { + int n = g.size(); + vector pred(n, -1); + vector prio(n, INF); + prio[0] = 0; + int last = 0; + for (int k = 0; k < n; k++) { + last = -1; + for (int u = 0; u < n; u++) { + for (int i = 0; i < (int) g[u].size(); i++) { + int v = g[u][i].first; + int cost = g[u][i].second; + if (prio[v] > prio[u] + cost) { + prio[v] = prio[u] + cost; + pred[v] = u; + last = v; + } + } + } + if (last == -1) + return vector(); + } + + vector path(n); + vector pos(n, -1); + for (int i = 0;; i++) { + if (pos[last] != -1) + return vector(path.rend() - i, path.rend() - pos[last]); + path[i] = last; + pos[last] = i; + last = pred[last]; + } +} + +int main() { + Graph g(4); + g[0].push_back(make_pair(1, 1)); + g[1].push_back(make_pair(0, 1)); + g[1].push_back(make_pair(2, 1)); + g[2].push_back(make_pair(3, -10)); + g[3].push_back(make_pair(1, 1)); + + vector cycle = findNegativeCycle(g); + for (int i = 0; i < (int) cycle.size(); i++) + cout << cycle[i] << " "; +} diff --git a/c++/Basic/Binary Operator Overloading.cpp b/c++/Basic/Binary Operator Overloading.cpp new file mode 100644 index 0000000..5996375 --- /dev/null +++ b/c++/Basic/Binary Operator Overloading.cpp @@ -0,0 +1,73 @@ +#include < iostream.h > +using namespace std; + +class Cube +{ +public: + + void setLength( double l ) + { + length = l; + } + + void setBreadth( double b ) + { + breadth = b; + } + + void setHeight( double h ) + { + height = h; + } + double getVolume(void) + { + return length * breadth * height; + } + +// Overload + operator to add two Cube objects. + Cube operator+(const Cube& b) + { + Cube C; + C.length = this->length + b.length; + C.breadth = this->breadth + b.breadth; + C.height = this->height + b.height; + return C; + } +private: + double length; // Length of a Cube + double breadth; // Breadth of a Cube + double height; // Height of a Cube +}; +// Main function for the program +int main( ) +{ + Cube C1; // Declare C1 of type Cube + Cube C2; // Declare C2 of type Cube + Cube C3; // Declare C3 of type Cube + double volume = 0.0; // Store the volume of a Cube here +// Cube 1 specification + C1.setLength(4.0); + C1.setBreadth(6.0); + C1.setHeight(5.0); +// Cube 2 specification + C2.setLength(8.0); + C2.setBreadth(4.0); + C2.setHeight(10.0); +// volume of Cube 1 + volume = C1.getVolume(); + cout << "Volume of Cube 1 : " << volume < +int main() +{ + int a[10],i,n,m,c,l,u; + cout<<"Enter the size of an array: "; + cin>>n; + cout<<"Enter the elements of the array: " ; + for(i=0; i < n; i++) + cin>>a[i]; + cout<<"Enter the number to be search: "; + cin>>m; + l=0,u=n-1; + c=binary(a,n,m,l,u); + if(c==0) + cout<<"Number is not found."; + else + cout<<"Number is found."; + return 0; +} + +/*Binary search will search element at middle, if element is not found and if element to be searched is less than middle then it will search only in lower part and if greater then in upper part */ + +int binary(int a[],int n,int m,int l,int u) +{ + int mid,c=0; + if(l < = u) + { + mid=(l+u)/2; + if(m==a[mid]) + { + c=1; + } + else if(m < a[mid]) + { + return binary(a,n,m,l,mid-1); + } + else + return binary(a,n,m,mid+1,u); + } + else + return c; +} + +Output: + +Enter the size of an array:4 +Enter the elements of the array:5 3 6 2 +Enter the number to be search:3 +Number is found. +Number is found. \ No newline at end of file diff --git a/c++/Basic/Binary to Decimal.cpp b/c++/Basic/Binary to Decimal.cpp new file mode 100644 index 0000000..e3974d5 --- /dev/null +++ b/c++/Basic/Binary to Decimal.cpp @@ -0,0 +1,19 @@ +#include < iostream.h > + +void main() +{ + int num, binary_val, decimal_val = 0, base = 1, rem; + cout<<"Enter a binary number(1s and 0s) \n"; + cin>>amp num; + binary_val = num; + while (num > 0) + { + rem = num % 10; + decimal_val = decimal_val + rem * base; + num = num / 10 ; + num = num / 10 ; + base = base * 2; + } + cout<<"The Binary number is ="< + +int main() +{ + long int binaryval, hexadecimalval = 0, i = 1, remainder; + cout<<"Enter the binary number: "; + cin>>binaryval; + while (binaryval != 0) + { + remainder = binaryval % 10; + hexadecimalval = hexadecimalval + remainder * i; + i = i * 2; + binaryval = binaryval / 10; + } + cout<<"Equivalent hexadecimal value:"< + +int main() +{ + long int binarynum, octalnum = 0, j = 1, remainder; + cout<<"Enter the value for binary number: "; + cin>>binarynum; + while (binarynum != 0) + { + remainder = binarynum % 10; + octalnum = octalnum + remainder * j; + j = j * 2; + binarynum = binarynum / 10; + } + cout<<"Equivalent octal value:"< + +using namespace std; + +int pow(int x, int n, int MOD) { + long long y = x; + int res = 1; + for (; n > 0; n >>= 1) { + if (n & 1) + res = res * y % MOD; + y = y * y % MOD; + } + return res; +} + +int main() { + const int MOD = 1000000007; + int x = pow(2, 10, MOD); + cout << x << endl; +} diff --git a/c++/Basic/Check Positive or Negative.cpp b/c++/Basic/Check Positive or Negative.cpp new file mode 100644 index 0000000..6630240 --- /dev/null +++ b/c++/Basic/Check Positive or Negative.cpp @@ -0,0 +1,20 @@ +#include +#include + +void main() +{ + clrscr(); //clear screen + int number; + cout<< "Enter an integer: "; + cin>> number; + if ( number >= 0) + { + cout << "You entered a positive integer: "< +#include +#include +using namespace std; + +struct item { + int x, y; + bool operator<(const item &o) const { + return x < o.x || x == o.x && y < o.y; + } +}; + +struct item_cmp { + bool operator()(const item &a, const item &b) { + return a.x < b.x || a.x == b.x && a.y < b.y; + } +}; + +bool cmp(const item &a, const item &b) { + return a.x < b.x || a.x == b.x && a.y < b.y; +} + +int main() { + item a[] = { { 2, 3 }, { 1, 2 } }; + //typedef set myset; + //myset s(a, a + 2, cmp); + //typedef set myset; + typedef set myset; + myset s(a, a + 2); + for (myset::iterator it = s.begin(); it != s.end(); it++) { + cout << it->x << " " << it->y << endl; + } + + sort(a, a + 2, cmp); + sort(a, a + 2, item_cmp()); + cout << a[0].x << " " << a[0].y << endl; +} diff --git a/c++/Basic/ConvexHull.cpp b/c++/Basic/ConvexHull.cpp new file mode 100644 index 0000000..0d07e77 --- /dev/null +++ b/c++/Basic/ConvexHull.cpp @@ -0,0 +1,39 @@ +#include +#include + +using namespace std; + +typedef pair point; + +long long cross(const point &a, const point &b, const point &c) { + return (b.first - a.first) * (c.second - a.second) - (b.second - a.second) * (c.first - a.first); +} + +vector convexHull(vector points) { + if (points.size() <= 1) + return points; + sort(points.begin(), points.end()); + vector h; + for (auto p: points) { + while (h.size() >= 2 && cross(h.end()[-2], h.back(), p) >= 0) + h.pop_back(); + h.push_back(p); + } + reverse(points.begin(), points.end()); + int upper = h.size(); + for (auto p: points) { + while (h.size() > upper && cross(h.end()[-2], h.back(), p) >= 0) + h.pop_back(); + h.push_back(p); + } + h.resize(h.size() - 1 - (h[0] == h[1])); + return h; +} + +// Usage example +int main() { + vector hull1 = convexHull((vector) {point(0, 0), point(3, 0), point(0, 3), point(1, 1)}); + cout << (3 == hull1.size()) << endl; + vector hull2 = convexHull((vector) {point(0, 0), point(0, 0)}); + cout << (1 == hull2.size()) << endl; +} diff --git a/c++/Basic/Current Date.cpp b/c++/Basic/Current Date.cpp new file mode 100644 index 0000000..39b436c --- /dev/null +++ b/c++/Basic/Current Date.cpp @@ -0,0 +1,14 @@ +#include +#include +using namespace std; + +int main() +{ + time_t t = time(0); // get time now + struct tm * now = localtime( & t ); + cout << "Current Date is : " + cout << now->tm_mday << '-'<< (now->tm_mon + 1) << '-' << (now->tm_year + 1900) << endl; +} + +Output +Current Date is : 16-6-2015 \ No newline at end of file diff --git a/c++/Basic/Decimal to Binary.cpp b/c++/Basic/Decimal to Binary.cpp new file mode 100644 index 0000000..50098dd --- /dev/null +++ b/c++/Basic/Decimal to Binary.cpp @@ -0,0 +1,19 @@ +#include < iostream.h > + +int main() +{ + int n, c, k; + cout<<"Enter an integer in decimal number system\n"; + cin>>n; + cout<= 0; c--) + { + k = n >> c; + /*Right shift(Binary Divide by 2)*/ + if (k & 1)//k is logically ANDed with 1 + cout<<"1"; + else + cout<<"0"; + } + return 0; +} \ No newline at end of file diff --git a/c++/Basic/Decimal to Octal.cpp b/c++/Basic/Decimal to Octal.cpp new file mode 100644 index 0000000..1af5624 --- /dev/null +++ b/c++/Basic/Decimal to Octal.cpp @@ -0,0 +1,18 @@ +#include + +void main() +{ + long num, decimal_num, remainder, base = 1, octal = 0; + cout<<"Enter a decimal integer \n"; + cin>>amp num; + decimal_num = num; + while (num > 0) + { + remainder = num % 8; + octal = octal + remainder * base; + num = num / 8; + base = base * 10; + } + cout<<"Input number is ="< +#include < string.h > + +int check_vowel(char); + +int main() +{ + char s[100], t[100]; + int i, j = 0; + cout<<"Enter a string to delete vowels\n"; + gets(s); + /* In the program we create a new string and process entered string character by character, and if a vowel is found it is not added to new string otherwise the character is added to new string, after the string ends we copy the new string into original string*/ + for(i = 0; s[i] != '\0'; i++) + { + if(check_vowel(s[i]) == 0) + { + /* not a vowel */ + t[j] = s[i]; + j++ + ; + } + } + t[j] = '\0'; + strcpy(s, t); + /* We are changing initial string */ + cout<<"String after deleting vowels:"<< s<<"\n"; + return 0; +} +int check_vowel(char c) +{ + switch(c) + { + case 'a': + case 'A': + case 'e': + case 'E': + case 'i': + case 'I': + case 'o': + case 'O': + case 'u': + case 'U': + return 1; + default: + return 0; + } +} \ No newline at end of file diff --git a/c++/Basic/Diameter.cpp b/c++/Basic/Diameter.cpp new file mode 100644 index 0000000..63f2f99 --- /dev/null +++ b/c++/Basic/Diameter.cpp @@ -0,0 +1,67 @@ +#include +#include +#include +#include +using namespace std; + +typedef pair point; + +bool cw(const point &a, const point &b, const point &c) { + return (b.first - a.first) * (c.second - a.second) - (b.second - a.second) * (c.first - a.first) < 0; +} + +vector convexHull(vector p) { + int n = p.size(); + if (n <= 1) + return p; + int k = 0; + sort(p.begin(), p.end()); + vector q(n * 2); + for (int i = 0; i < n; q[k++] = p[i++]) + for (; k >= 2 && !cw(q[k - 2], q[k - 1], p[i]); --k) + ; + for (int i = n - 2, t = k; i >= 0; q[k++] = p[i--]) + for (; k > t && !cw(q[k - 2], q[k - 1], p[i]); --k) + ; + q.resize(k - 1 - (q[0] == q[1])); + return q; +} + +double area(const point &a, const point &b, const point &c) { + return abs((b.first - a.first) * (c.second - a.second) - (b.second - a.second) * (c.first - a.first)); +} + +double dist(const point &a, const point &b) { + return hypot(a.first - b.first, a.second - b.second); +} + +double diameter(const vector &p) { + vector h = convexHull(p); + int m = h.size(); + if (m == 1) + return 0; + if (m == 2) + return dist(h[0], h[1]); + int k = 1; + while (area(h[m - 1], h[0], h[(k + 1) % m]) > area(h[m - 1], h[0], h[k])) + ++k; + double res = 0; + for (int i = 0, j = k; i <= k && j < m; i++) { + res = max(res, dist(h[i], h[j])); + while (j < m && area(h[i], h[(i + 1) % m], h[(j + 1) % m]) > area(h[i], h[(i + 1) % m], h[j])) { + res = max(res, dist(h[i], h[(j + 1) % m])); + ++j; + } + } + return res; +} + +int main() { + vector points(4); + points[0] = point(0, 0); + points[1] = point(3, 0); + points[2] = point(0, 3); + points[3] = point(1, 1); + double d = diameter(points); + cout << d << endl; +} diff --git a/c++/Basic/Dijkstra.cpp b/c++/Basic/Dijkstra.cpp new file mode 100644 index 0000000..d59fe57 --- /dev/null +++ b/c++/Basic/Dijkstra.cpp @@ -0,0 +1,73 @@ +#include +#include +#include +#include +#include +using namespace std; + +typedef pair pii; +typedef vector > Graph; + +void dijkstra(Graph &g, int s, vector &prio, vector &pred) { + int n = g.size(); + prio.assign(n, INT_MAX); + prio[s] = 0; + pred.assign(n, -1); + priority_queue , greater > q; + q.push(make_pair(prio[s], s)); + + while (!q.empty()) { + int d = q.top().first; + int u = q.top().second; + q.pop(); + if (d != prio[u]) + continue; + for (int i = 0; i < (int) g[u].size(); i++) { + int v = g[u][i].first; + int nprio = prio[u] + g[u][i].second; + if (prio[v] > nprio) { + prio[v] = nprio; + pred[v] = u; + q.push(make_pair(nprio, v)); + } + } + } +} + +void dijkstra2(Graph &g, int s, vector &prio, vector &pred) { + int n = g.size(); + prio.assign(n, INT_MAX); + prio[s] = 0; + pred.assign(n, -1); + set q; + q.insert(make_pair(prio[s], s)); + + while (!q.empty()) { + int u = q.begin()->second; + q.erase(q.begin()); + for (int i = 0; i < (int) g[u].size(); ++i) { + int v = g[u][i].first; + int nprio = prio[u] + g[u][i].second; + if (prio[v] > nprio) { + q.erase(make_pair(prio[v], v)); + prio[v] = nprio; + pred[v] = u; + q.insert(make_pair(prio[v], v)); + } + } + } +} + +int main() { + Graph g(3); + g[0].push_back(make_pair(1, 10)); + g[1].push_back(make_pair(2, -5)); + g[0].push_back(make_pair(2, 8)); + + vector prio; + vector pred; + dijkstra(g, 0, prio, pred); + + for (int i = 0; i < prio.size(); i++) + cout << prio[i] << endl; +} diff --git a/c++/Basic/DijkstraHeap.cpp b/c++/Basic/DijkstraHeap.cpp new file mode 100644 index 0000000..be30eed --- /dev/null +++ b/c++/Basic/DijkstraHeap.cpp @@ -0,0 +1,123 @@ +#include +#include +#include +using namespace std; + +const int maxnodes = 200000; +const int maxedges = 1000000; + +// graph +int edges; +int last[maxnodes], head[maxedges], previous[maxedges], len[maxedges]; +int prio[maxnodes], pred[maxnodes]; + +void graphClear() { + fill(last, last + maxnodes, -1); + edges = 0; +} + +void addEdge(int u, int v, int length) { + head[edges] = v; + len[edges] = length; + previous[edges] = last[u]; + last[u] = edges++; +} + +// heap +int h[maxnodes]; +int pos2Id[maxnodes]; +int id2Pos[maxnodes]; +int hsize; + +void hswap(int i, int j) { + swap(h[i], h[j]); + swap(pos2Id[i], pos2Id[j]); + swap(id2Pos[pos2Id[i]], id2Pos[pos2Id[j]]); +} + +void moveUp(int pos) { + while (pos > 0) { + int parent = (pos - 1) >> 1; + if (h[pos] >= h[parent]) { + break; + } + hswap(pos, parent); + pos = parent; + } +} + +void add(int id, int prio) { + h[hsize] = prio; + pos2Id[hsize] = id; + id2Pos[id] = hsize; + moveUp(hsize++); +} + +void increasePriority(int id, int prio) { + int pos = id2Pos[id]; + h[pos] = prio; + moveUp(pos); +} + +void moveDown(int pos) { + while (pos < (hsize >> 1)) { + int child = 2 * pos + 1; + if (child + 1 < hsize && h[child + 1] < h[child]) { + ++child; + } + if (h[pos] <= h[child]) { + break; + } + hswap(pos, child); + pos = child; + } +} + +int removeMin() { + int res = pos2Id[0]; + int lastNode = h[--hsize]; + if (hsize > 0) { + h[0] = lastNode; + int id = pos2Id[hsize]; + id2Pos[id] = 0; + pos2Id[0] = id; + moveDown(0); + } + return res; +} + +void dijkstra(int s) { + fill(pred, pred + maxnodes, -1); + fill(prio, prio + maxnodes, INT_MAX); + prio[s] = 0; + hsize = 0; + add(s, prio[s]); + + while (hsize) { + int u = removeMin(); + for (int e = last[u]; e >= 0; e = previous[e]) { + int v = head[e]; + int nprio = prio[u] + len[e]; + if (prio[v] > nprio) { + if (prio[v] == INT_MAX) + add(v, nprio); + else + increasePriority(v, nprio); + prio[v] = nprio; + pred[v] = u; + } + } + } +} + +int main() { + graphClear(); + addEdge(0, 1, 10); + addEdge(1, 2, -5); + addEdge(0, 2, 8); + + dijkstra(0); + + for (int i = 0; i < 3; i++) + cout << prio[i] << endl; +} diff --git a/c++/Basic/DisjointSets.cpp b/c++/Basic/DisjointSets.cpp new file mode 100644 index 0000000..58430c2 --- /dev/null +++ b/c++/Basic/DisjointSets.cpp @@ -0,0 +1,36 @@ +#include +#include + +using namespace std; + +const int maxn = 200000; +int Rank[maxn]; +int p[maxn]; +int n; + +void init(int n) { + ::n = n; + fill(Rank, Rank + n, 0); + for (int i = 0; i < n; i++) p[i] = i; +} + +int root(int x) { + return x == p[x] ? x : (p[x] = root(p[x])); +} + +void unite(int a, int b) { + a = root(a); + b = root(b); + if (a == b) return; + if (Rank[a] < Rank[b]) swap(a, b); + if (Rank[a] == Rank[b]) ++Rank[a]; + p[b] = a; +} + +int main() { + init(3); + unite(0, 2); + cout << (0 == root(0)) << endl; + cout << (1 == root(1)) << endl; + cout << (0 == root(2)) << endl; +} diff --git a/c++/Basic/FFT.cpp b/c++/Basic/FFT.cpp new file mode 100644 index 0000000..5f8c93f --- /dev/null +++ b/c++/Basic/FFT.cpp @@ -0,0 +1,137 @@ +// https://web.stanford.edu/~liszt90/acm/notebook.html#file16 +// Fast Fourier Transform : Used in many applications(one is fast polynomial multiplication) + +#include +#include +#include + +struct cpx +{ + cpx(){} + cpx(double aa):a(aa),b(0){} + cpx(double aa, double bb):a(aa),b(bb){} + double a; + double b; + double modsq(void) const + { + return a * a + b * b; + } + cpx bar(void) const + { + return cpx(a, -b); + } +}; + +cpx operator +(cpx a, cpx b) +{ + return cpx(a.a + b.a, a.b + b.b); +} + +cpx operator *(cpx a, cpx b) +{ + return cpx(a.a * b.a - a.b * b.b, a.a * b.b + a.b * b.a); +} + +cpx operator /(cpx a, cpx b) +{ + cpx r = a * b.bar(); + return cpx(r.a / b.modsq(), r.b / b.modsq()); +} + +cpx EXP(double theta) +{ + return cpx(cos(theta),sin(theta)); +} + +const double two_pi = 4 * acos(0); + +// in: input array +// out: output array +// step: {SET TO 1} (used internally) +// size: length of the input/output {MUST BE A POWER OF 2} +// dir: either plus or minus one (direction of the FFT) +// RESULT: out[k] = \sum_{j=0}^{size - 1} in[j] * exp(dir * 2pi * i * j * k / size) +void FFT(cpx *in, cpx *out, int step, int size, int dir) +{ + if(size < 1) return; + if(size == 1) + { + out[0] = in[0]; + return; + } + FFT(in, out, step * 2, size / 2, dir); + FFT(in + step, out + size / 2, step * 2, size / 2, dir); + for(int i = 0 ; i < size / 2 ; i++) + { + cpx even = out[i]; + cpx odd = out[i + size / 2]; + out[i] = even + EXP(dir * two_pi * i / size) * odd; + out[i + size / 2] = even + EXP(dir * two_pi * (i + size / 2) / size) * odd; + } +} + +// Usage: +// f[0...N-1] and g[0..N-1] are numbers +// Want to compute the convolution h, defined by +// h[n] = sum of f[k]g[n-k] (k = 0, ..., N-1). +// Here, the index is cyclic; f[-1] = f[N-1], f[-2] = f[N-2], etc. +// Let F[0...N-1] be FFT(f), and similarly, define G and H. +// The convolution theorem says H[n] = F[n]G[n] (element-wise product). +// To compute h[] in O(N log N) time, do the following: +// 1. Compute F and G (pass dir = 1 as the argument). +// 2. Get H by element-wise multiplying F and G. +// 3. Get h by taking the inverse FFT (use dir = -1 as the argument) +// and *dividing by N*. DO NOT FORGET THIS SCALING FACTOR. + +int main(void) +{ + printf("If rows come in identical pairs, then everything works.\n"); + + cpx a[8] = {0, 1, cpx(1,3), cpx(0,5), 1, 0, 2, 0}; + cpx b[8] = {1, cpx(0,-2), cpx(0,1), 3, -1, -3, 1, -2}; + cpx A[8]; + cpx B[8]; + FFT(a, A, 1, 8, 1); + FFT(b, B, 1, 8, 1); + + for(int i = 0 ; i < 8 ; i++) + { + printf("%7.2lf%7.2lf", A[i].a, A[i].b); + } + printf("\n"); + for(int i = 0 ; i < 8 ; i++) + { + cpx Ai(0,0); + for(int j = 0 ; j < 8 ; j++) + { + Ai = Ai + a[j] * EXP(j * i * two_pi / 8); + } + printf("%7.2lf%7.2lf", Ai.a, Ai.b); + } + printf("\n"); + + cpx AB[8]; + for(int i = 0 ; i < 8 ; i++) + AB[i] = A[i] * B[i]; + cpx aconvb[8]; + FFT(AB, aconvb, 1, 8, -1); + for(int i = 0 ; i < 8 ; i++) + aconvb[i] = aconvb[i] / 8; + for(int i = 0 ; i < 8 ; i++) + { + printf("%7.2lf%7.2lf", aconvb[i].a, aconvb[i].b); + } + printf("\n"); + for(int i = 0 ; i < 8 ; i++) + { + cpx aconvbi(0,0); + for(int j = 0 ; j < 8 ; j++) + { + aconvbi = aconvbi + a[j] * b[(8 + i - j) % 8]; + } + printf("%7.2lf%7.2lf", aconvbi.a, aconvbi.b); + } + printf("\n"); + + return 0; +} \ No newline at end of file diff --git a/c++/Basic/FenwickTree.cpp b/c++/Basic/FenwickTree.cpp new file mode 100644 index 0000000..519a86f --- /dev/null +++ b/c++/Basic/FenwickTree.cpp @@ -0,0 +1,47 @@ +#include +using namespace std; + +const int maxn = 200000; +int t[maxn]; + +void add(int t[], int i, int value) { + for (; i < maxn; i |= i + 1) + t[i] += value; +} + +// sum[0,i] +int sum(int t[], int i) { + int res = 0; + for (; i >= 0; i = (i & (i + 1)) - 1) + res += t[i]; + return res; +} + +// Returns min(p|sum[0,p]>=sum) +int lower_bound(int t[], int sum) { + --sum; + int pos = -1; + for (int blockSize = 1 << 30; blockSize != 0; blockSize >>= 1) { + if (blockSize > maxn) continue; + int nextPos = pos + blockSize; + if (nextPos < maxn && sum >= t[nextPos]) { + sum -= t[nextPos]; + pos = nextPos; + } + } + return pos + 1; +} + + +// Usage example +int main() { + add(t, 0, 4); + add(t, 1, 5); + add(t, 2, 5); + add(t, 2, 5); + + cout << (4 == sum(t, 0)) << endl; + cout << (19 == sum(t, 2)) << endl; + cout << (2 == lower_bound(t, 19)) << endl; + cout << (maxn == lower_bound(t, 20)) << endl; +} diff --git a/c++/Basic/FenwickTreeOnMap.cpp b/c++/Basic/FenwickTreeOnMap.cpp new file mode 100644 index 0000000..20fab29 --- /dev/null +++ b/c++/Basic/FenwickTreeOnMap.cpp @@ -0,0 +1,31 @@ +#include +#include +using namespace std; + +const int n = 2000000000; + +void add(map &t, int i, int value) { + for (; i < n; i |= i + 1) + t[i] += value; +} + +// sum[0,i] +int sum(map &t, int i) { + int res = 0; + for (; i >= 0; i = (i & (i + 1)) - 1) + if (t.count(i)) res += t[i]; + return res; +} + +// Usage example +int main() { + map t; + add(t, 0, 4); + add(t, 1, 5); + add(t, 2, 5); + add(t, 2, 5); + + cout << (4 == sum(t, 0)) << endl; + cout << (19 == sum(t, 2)) << endl; + cout << (19 == sum(t, 1000000000)) << endl; +} diff --git a/c++/Basic/Find ASCII value of a character.cpp b/c++/Basic/Find ASCII value of a character.cpp new file mode 100644 index 0000000..aff89da --- /dev/null +++ b/c++/Basic/Find ASCII value of a character.cpp @@ -0,0 +1,12 @@ +#include +#include + +void main() +{ + clrscr(); + cout << "Size of char: " << sizeof(char) << " byte" << endl; + cout << "Size of int: " << sizeof(int) << " bytes" << endl; + cout << "Size of float: " << sizeof(float) << " bytes" << endl; + cout << "Size of double: " << sizeof(double) << " bytes" << endl; + getch(); +} \ No newline at end of file diff --git a/c++/Basic/FindIntersection.cpp b/c++/Basic/FindIntersection.cpp new file mode 100644 index 0000000..d7cdbe9 --- /dev/null +++ b/c++/Basic/FindIntersection.cpp @@ -0,0 +1,103 @@ +#include +#include +#include +using namespace std; + +typedef pair pii; + +int cross(int ax, int ay, int bx, int by, int cx, int cy) { + return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax); +} + +int cross(pii a, pii b, pii c) { + return cross(a.first, a.second, b.first, b.second, c.first, c.second); +} + +class segment { + public: + pii a, b; + int id; + segment(pii a, pii b, int id) : + a(a), b(b), id(id) { + } + bool operator<(const segment &o) const { + if (a.first < o.a.first) { + int s = cross(a, b, o.a); + return (s > 0 || s == 0 && a.second < o.a.second); + } else if (a.first > o.a.first) { + int s = cross(o.a, o.b, a); + return (s < 0 || s == 0 && a.second < o.a.second); + } + return a.second < o.a.second; + } +}; + +class event { + public: + pii p; + int id; + int type; + event(pii p, int id, int type) : + p(p), id(id), type(type) { + } + bool operator<(const event &o) const { + return p.first < o.p.first || p.first == o.p.first && (type > o.type || type == o.type && p.second < o.p.second); + } +}; + +bool intersect(segment s1, segment s2) { + int x1 = s1.a.first, y1 = s1.a.second, x2 = s1.b.first, y2 = s1.b.second; + int x3 = s2.a.first, y3 = s2.a.second, x4 = s2.b.first, y4 = s2.b.second; + if (max(x1, x2) < min(x3, x4) || max(x3, x4) < min(x1, x2) || max(y1, y2) < min(y3, y4) || max(y3, y4) < min(y1, y2)) { + return false; + } + int z1 = (x3 - x1) * (y2 - y1) - (y3 - y1) * (x2 - x1); + int z2 = (x4 - x1) * (y2 - y1) - (y4 - y1) * (x2 - x1); + if (z1 < 0 && z2 < 0 || z1 > 0 && z2 > 0) { + return false; + } + int z3 = (x1 - x3) * (y4 - y3) - (y1 - y3) * (x4 - x3); + int z4 = (x2 - x3) * (y4 - y3) - (y2 - y3) * (x4 - x3); + if (z3 < 0 && z4 < 0 || z3 > 0 && z4 > 0) { + return false; + } + return true; +} + +pii findIntersection(vector s) { + int n = s.size(); + vector e; + for (int i = 0; i < n; ++i) { + if (s[i].a > s[i].b) + swap(s[i].a, s[i].b); + e.push_back(event(s[i].a, i, 1)); + e.push_back(event(s[i].b, i, -1)); + } + sort(e.begin(), e.end()); + + set q; + + for (int i = 0; i < n * 2; ++i) { + int id = e[i].id; + if (e[i].type == 1) { + set::iterator it = q.lower_bound(s[id]); + if (it != q.end() && intersect(*it, s[id])) + return make_pair(it->id, s[id].id); + if (it != q.begin() && intersect(*--it, s[id])) + return make_pair(it->id, s[id].id); + q.insert(s[id]); + } else { + set::iterator it = q.lower_bound(s[id]), next = it, prev = it; + if (it != q.begin() && it != --q.end()) { + ++next, --prev; + if (intersect(*next, *prev)) + return make_pair(next->id, prev->id); + } + q.erase(it); + } + } + return make_pair(-1, -1); +} + +int main() { +} diff --git a/c++/Basic/Get IP Address.cpp b/c++/Basic/Get IP Address.cpp new file mode 100644 index 0000000..715508f --- /dev/null +++ b/c++/Basic/Get IP Address.cpp @@ -0,0 +1,8 @@ +#include + +int main() +{ + system("C:\\Windows\\System32\\ipconfig"); + /* ipconfig command to get ip of system */ + return 0; +} \ No newline at end of file diff --git a/c++/Basic/Hcf & Lcm.cpp b/c++/Basic/Hcf & Lcm.cpp new file mode 100644 index 0000000..effa3e5 --- /dev/null +++ b/c++/Basic/Hcf & Lcm.cpp @@ -0,0 +1,36 @@ +#include < iostream.h > + +long gcd(long, long); +int main() +{ + long x, y, hcf, lcm; + cout<<"Enter two integers\n"; + cin>>x>>y; + hcf = gcd(x, y); + lcm = (x*y)/hcf; + cout<<"Greatest common divisor of "< y) + { + x = x - y; + } + else + { + y = y - x; + } + } + return x; +} \ No newline at end of file diff --git a/c++/Basic/KdTree.cpp b/c++/Basic/KdTree.cpp new file mode 100644 index 0000000..bee5ab4 --- /dev/null +++ b/c++/Basic/KdTree.cpp @@ -0,0 +1,103 @@ +#include +#include +#include +#include +using namespace std; + +typedef pair pii; +typedef vector vpii; + +const int maxn = 100000; +int tx[maxn]; +int ty[maxn]; +bool divX[maxn]; + +bool cmpX(const pii &a, const pii &b) { + return a.first < b.first; +} + +bool cmpY(const pii &a, const pii &b) { + return a.second < b.second; +} + +void buildTree(int left, int right, pii points[]) { + if (left >= right) + return; + int mid = (left + right) >> 1; + + //sort(points + left, points + right + 1, divX ? cmpX : cmpY); + int minx = INT_MAX; + int maxx = INT_MIN; + int miny = INT_MAX; + int maxy = INT_MIN; + for (int i = left; i < right; i++) { + checkmin(minx, points[i].first); + checkmax(maxx, points[i].first); + checkmin(miny, points[i].second); + checkmax(maxy, points[i].second); + } + divX[mid] = (maxx - minx) >= (maxy - miny); + nth_element(points + left, points + mid, points + right, divX[mid] ? cmpX : cmpY); + + tx[mid] = points[mid].first; + ty[mid] = points[mid].second; + + if (left + 1 == right) + return; + buildTree(left, mid, points); + buildTree(mid + 1, right, points); +} + +long long closestDist; +int closestNode; + +void findNearestNeighbour(int left, int right, int x, int y) { + if (left >= right) + return; + int mid = (left + right) >> 1; + int dx = x - tx[mid]; + int dy = y - ty[mid]; + long long d = dx * (long long) dx + dy * (long long) dy; + if (closestDist > d && d) { + closestDist = d; + closestNode = mid; + } + if (left + 1 == right) + return; + + int delta = divX[mid] ? dx : dy; + long long delta2 = delta * (long long) delta; + int l1 = left; + int r1 = mid; + int l2 = mid + 1; + int r2 = right; + if (delta > 0) + swap(l1, l2), swap(r1, r2); + + findNearestNeighbour(l1, r1, x, y); + if (delta2 < closestDist) + findNearestNeighbour(l2, r2, x, y); +} + +int findNearestNeighbour(int n, int x, int y) { + closestDist = LLONG_MAX; + findNearestNeighbour(0, n, x, y); + return closestNode; +} + +int main() { + vpii p; + p.push_back(make_pair(0, 2)); + p.push_back(make_pair(0, 3)); + p.push_back(make_pair(-1, 0)); + + p.resize(unique(p.begin(), p.end()) - p.begin()); + + int n = p.size(); + buildTree(1, 0, n - 1, &(vpii(p)[0])); + int res = findNearestNeighbour(n, 0, 0); + + cout << p[res].first << " " << p[res].second << endl; + + return 0; +} diff --git a/c++/Basic/Manacher.cpp b/c++/Basic/Manacher.cpp new file mode 100644 index 0000000..019c57f --- /dev/null +++ b/c++/Basic/Manacher.cpp @@ -0,0 +1,65 @@ +// Linear Time algorithms for longestPalindrome in a string problem. It is one of the standard algorithms but is not very intuitive. + +#include +#include +#include +using namespace std; + + +// Transform S into T. +// For example, S = "abba", T = "^#a#b#b#a#$". +// ^ and $ signs are sentinels appended to each end to avoid bounds checking + +string preProcess(string s) { + int n = s.length(); + if (n == 0) return "^$"; + string ret = "^"; + for (int i = 0; i < n; i++) + ret += "#" + s.substr(i, 1); + + ret += "#$"; + return ret; +} + +string longestPalindrome(string s) { + string T = preProcess(s); + int n = T.length(); + int *P = new int[n]; + int C = 0, R = 0; + for (int i = 1; i < n-1; i++) { + int i_mirror = 2*C-i; // equals to i' = C - (i-C) + + P[i] = (R > i) ? min(R-i, P[i_mirror]) : 0; + + // Attempt to expand palindrome centered at i + while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) + P[i]++; + + // If palindrome centered at i expand past R, + // adjust center based on expanded palindrome. + if (i + P[i] > R) { + C = i; + R = i + P[i]; + } + } + + // Find the maximum element in P. + int maxLen = 0; + int centerIndex = 0; + for (int i = 1; i < n-1; i++) { + if (P[i] > maxLen) { + maxLen = P[i]; + centerIndex = i; + } + } + delete[] P; + + return s.substr((centerIndex - 1 - maxLen)/2, maxLen); +} + + +int main() { + string text = "babcbabcbaccba"; + std::cout << longestPalindrome(text)<< endl; + +} \ No newline at end of file diff --git a/c++/Basic/Matrix.cpp b/c++/Basic/Matrix.cpp new file mode 100644 index 0000000..af155bb --- /dev/null +++ b/c++/Basic/Matrix.cpp @@ -0,0 +1,62 @@ +#include +#include +using namespace std; + +typedef vector vi; +typedef vector vvi; + +const int mod = 1234567891; + +vvi matrixUnit(int n) { + vvi res(n, vi(n)); + for (int i = 0; i < n; i++) + res[i][i] = 1; + return res; +} + +vvi matrixAdd(const vvi &a, const vvi &b) { + int n = a.size(); + int m = a[0].size(); + vvi res(n, vi(m)); + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + res[i][j] = (a[i][j] + b[i][j]) % mod; + return res; +} + +vvi matrixMul(const vvi &a, const vvi &b) { + int n = a.size(); + int m = a[0].size(); + int k = b[0].size(); + vvi res(n, vi(k)); + for (int i = 0; i < n; i++) + for (int j = 0; j < k; j++) + for (int p = 0; p < m; p++) + res[i][j] = (res[i][j] + (long long) a[i][p] * b[p][j]) % mod; + return res; +} + +vvi matrixPow(const vvi &a, int p) { + if (p == 0) + return matrixUnit(a.size()); + if (p & 1) + return matrixMul(a, matrixPow(a, p - 1)); + return matrixPow(matrixMul(a, a), p / 2); +} + +vvi matrixPowSum(const vvi &a, int p) { + int n = a.size(); + if (p == 0) + return vvi(n, vi(n)); + if (p % 2 == 0) + return matrixMul(matrixPowSum(a, p / 2), matrixAdd(matrixUnit(n), matrixPow(a, p / 2))); + return matrixAdd(a, matrixMul(matrixPowSum(a, p - 1), a)); +} + +int main() { + vvi a(2, vi(2)); + a[0][0] = 1; + a[0][1] = 1; + a[1][0] = 1; + vvi b = matrixPow(a, 10); +} diff --git a/c++/Basic/MaxFlowDinic.cpp b/c++/Basic/MaxFlowDinic.cpp new file mode 100644 index 0000000..6d66182 --- /dev/null +++ b/c++/Basic/MaxFlowDinic.cpp @@ -0,0 +1,87 @@ +#include +#include +#include +#include +using namespace std; + +const int maxnodes = 5000; + +int nodes = maxnodes, src, dest; +int dist[maxnodes], q[maxnodes], work[maxnodes]; + +struct Edge { + int to, rev; + int f, cap; +}; + +vector g[maxnodes]; + +// Adds bidirectional edge +void addEdge(int s, int t, int cap){ + Edge a = {t, g[t].size(), 0, cap}; + Edge b = {s, g[s].size(), 0, cap}; + g[s].push_back(a); + g[t].push_back(b); +} + +bool dinic_bfs() { + fill(dist, dist + nodes, -1); + dist[src] = 0; + int qt = 0; + q[qt++] = src; + for (int qh = 0; qh < qt; qh++) { + int u = q[qh]; + for (int j = 0; j < (int) g[u].size(); j++) { + Edge &e = g[u][j]; + int v = e.to; + if (dist[v] < 0 && e.f < e.cap) { + dist[v] = dist[u] + 1; + q[qt++] = v; + } + } + } + return dist[dest] >= 0; +} + +int dinic_dfs(int u, int f) { + if (u == dest) + return f; + for (int &i = work[u]; i < (int) g[u].size(); i++) { + Edge &e = g[u][i]; + if (e.cap <= e.f) continue; + int v = e.to; + if (dist[v] == dist[u] + 1) { + int df = dinic_dfs(v, min(f, e.cap - e.f)); + if (df > 0) { + e.f += df; + g[v][e.rev].f -= df; + return df; + } + } + } + return 0; +} + +int maxFlow(int _src, int _dest) { + src = _src; + dest = _dest; + int result = 0; + while (dinic_bfs()) { + fill(work, work + nodes, 0); + while (int delta = dinic_dfs(src, INT_MAX)) + result += delta; + } + return result; +} + +int main() { + int n = 3; + nodes = n; + + int capacity[][3] = { { 0, 3, 2 }, { 0, 0, 2 }, { 0, 0, 0 } }; + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + if (capacity[i][j] != 0) + addEdge(i, j, capacity[i][j]); + cout << (4 == maxFlow(0, 2)) << endl; +} diff --git a/c++/Basic/MaxMatching.cpp b/c++/Basic/MaxMatching.cpp new file mode 100644 index 0000000..902ce0f --- /dev/null +++ b/c++/Basic/MaxMatching.cpp @@ -0,0 +1,86 @@ +#include +#include + +using namespace std; + +const int MAXN1 = 50000; +const int MAXN2 = 50000; +const int MAXM = 150000; + +int n1, n2, edges, last[MAXN1], prev[MAXM], head[MAXM]; +int matching[MAXN2], dist[MAXN1], Q[MAXN1]; +bool used[MAXN1], vis[MAXN1]; + +void init(int _n1, int _n2) { + n1 = _n1; + n2 = _n2; + edges = 0; + fill(last, last + n1, -1); +} + +void addEdge(int u, int v) { + head[edges] = v; + prev[edges] = last[u]; + last[u] = edges++; +} + +void bfs() { + fill(dist, dist + n1, -1); + int sizeQ = 0; + for (int u = 0; u < n1; ++u) { + if (!used[u]) { + Q[sizeQ++] = u; + dist[u] = 0; + } + } + for (int i = 0; i < sizeQ; i++) { + int u1 = Q[i]; + for (int e = last[u1]; e >= 0; e = prev[e]) { + int u2 = matching[head[e]]; + if (u2 >= 0 && dist[u2] < 0) { + dist[u2] = dist[u1] + 1; + Q[sizeQ++] = u2; + } + } + } +} + +bool dfs(int u1) { + vis[u1] = true; + for (int e = last[u1]; e >= 0; e = prev[e]) { + int v = head[e]; + int u2 = matching[v]; + if (u2 < 0 || !vis[u2] && dist[u2] == dist[u1] + 1 && dfs(u2)) { + matching[v] = u1; + used[u1] = true; + return true; + } + } + return false; +} + +int maxMatching() { + fill(used, used + n1, false); + fill(matching, matching + n2, -1); + for (int res = 0;;) { + bfs(); + fill(vis, vis + n1, false); + int f = 0; + for (int u = 0; u < n1; ++u) + if (!used[u] && dfs(u)) + ++f; + if (!f) + return res; + res += f; + } +} + +int main() { + init(2, 2); + + addEdge(0, 0); + addEdge(0, 1); + addEdge(1, 1); + + cout << (2 == maxMatching()) << endl; +} diff --git a/c++/Basic/MinCostFlow.cpp b/c++/Basic/MinCostFlow.cpp new file mode 100644 index 0000000..55f8ed1 --- /dev/null +++ b/c++/Basic/MinCostFlow.cpp @@ -0,0 +1,121 @@ +#include +#include +#include +#include +using namespace std; + +typedef long long ll; +typedef pair pii; + +const int maxnodes = 200000; + +int nodes = maxnodes; +int prio[maxnodes], curflow[maxnodes], prevedge[maxnodes], prevnode[maxnodes], q[maxnodes], pot[maxnodes]; +bool inqueue[maxnodes]; + +struct Edge { + int to, f, cap, cost, rev; +}; + +vector graph[maxnodes]; + +void addEdge(int s, int t, int cap, int cost) { + Edge a = {t, 0, cap, cost, graph[t].size()}; + Edge b = {s, 0, 0, -cost, graph[s].size()}; + graph[s].push_back(a); + graph[t].push_back(b); +} + +void bellmanFord(int s, int dist[]) { + fill(dist, dist + nodes, INT_MAX); + dist[s] = 0; + int qt = 0; + q[qt++] = s; + for (int qh = 0; (qh - qt) % nodes != 0; qh++) { + int u = q[qh % nodes]; + inqueue[u] = false; + for (int i = 0; i < (int) graph[u].size(); i++) { + Edge &e = graph[u][i]; + if (e.cap <= e.f) continue; + int v = e.to; + int ndist = dist[u] + e.cost; + if (dist[v] > ndist) { + dist[v] = ndist; + if (!inqueue[v]) { + inqueue[v] = true; + q[qt++ % nodes] = v; + } + } + } + } +} + +pii minCostFlow(int s, int t, int maxf) { + // bellmanFord can be safely commented if edges costs are non-negative + bellmanFord(s, pot); + int flow = 0; + int flowCost = 0; + while (flow < maxf) { + priority_queue, greater > q; + q.push(s); + fill(prio, prio + nodes, INT_MAX); + prio[s] = 0; + curflow[s] = INT_MAX; + while (!q.empty()) { + ll cur = q.top(); + int d = cur >> 32; + int u = cur; + q.pop(); + if (d != prio[u]) + continue; + for (int i = 0; i < (int) graph[u].size(); i++) { + Edge &e = graph[u][i]; + int v = e.to; + if (e.cap <= e.f) continue; + int nprio = prio[u] + e.cost + pot[u] - pot[v]; + if (prio[v] > nprio) { + prio[v] = nprio; + q.push(((ll) nprio << 32) + v); + prevnode[v] = u; + prevedge[v] = i; + curflow[v] = min(curflow[u], e.cap - e.f); + } + } + } + if (prio[t] == INT_MAX) + break; + for (int i = 0; i < nodes; i++) + pot[i] += prio[i]; + int df = min(curflow[t], maxf - flow); + flow += df; + for (int v = t; v != s; v = prevnode[v]) { + Edge &e = graph[prevnode[v]][prevedge[v]]; + e.f += df; + graph[v][e.rev].f -= df; + flowCost += df * e.cost; + } + } + return make_pair(flow, flowCost); +} + +// Usage example + +int main() { + int capacity[3][3] = { + { 0, 3, 2}, + { 0, 0, 2}, + { 0, 0, 0} + }; + nodes = 3; + for (int i = 0; i < nodes; i++) + for (int j = 0; j < nodes; j++) + if (capacity[i][j] != 0) + addEdge(i, j, capacity[i][j], 1); + int s = 0; + int t = 2; + pii res = minCostFlow(s, t, INT_MAX); + int flow = res.first; + int flowCost = res.second; + cout << (4 == flow) << endl; + cout << (6 == flowCost) << endl; +} diff --git a/c++/Basic/MinCostFlowBF.cpp b/c++/Basic/MinCostFlowBF.cpp new file mode 100644 index 0000000..14a8fb0 --- /dev/null +++ b/c++/Basic/MinCostFlowBF.cpp @@ -0,0 +1,92 @@ +#include +#include +#include +#include +using namespace std; + +typedef long long ll; +typedef pair pii; + +const int maxnodes = 200000; + +int nodes = maxnodes; +int prio[maxnodes], curflow[maxnodes], prevedge[maxnodes], prevnode[maxnodes], q[maxnodes]; +bool inqueue[maxnodes]; + +struct Edge { + int to, f, cap, cost, rev; +}; + +vector graph[maxnodes]; + +void addEdge(int s, int t, int cap, int cost){ + Edge a = {t, 0, cap, cost, graph[t].size()}; + Edge b = {s, 0, 0, -cost, graph[s].size()}; + graph[s].push_back(a); + graph[t].push_back(b); +} + +void bellmanFord(int s) { + fill(prio, prio + nodes, INT_MAX); + prio[s] = 0; + int qt = 0; + q[qt++] = s; + for (int qh = 0; (qh - qt) % nodes != 0; qh++) { + int u = q[qh % nodes]; + inqueue[u] = false; + for (int i = 0; i < (int) graph[u].size(); i++) { + Edge &e = graph[u][i]; + if(e.cap <= e.f) continue; + int v = e.to; + int ndist = prio[u] + e.cost; + if (prio[v] > ndist) { + prio[v] = ndist; + prevnode[v] = u; + prevedge[v] = i; + curflow[v] = min(curflow[u], e.cap - e.f); + if (!inqueue[v]) { + inqueue[v] = true; + q[qt++ % nodes] = v; + } + } + } + } +} + +pii minCostFlow(int s, int t, int maxf) { + int flow = 0; + int flowCost = 0; + while (flow < maxf) { + curflow[s] = INT_MAX; + bellmanFord(s); + if (prio[t] == INT_MAX) + break; + int df = min(curflow[t], maxf - flow); + flow += df; + for (int v = t; v != s; v = prevnode[v]) { + Edge &e = graph[prevnode[v]][prevedge[v]]; + e.f += df; + graph[v][e.rev].f -= df; + flowCost += df * e.cost; + } + } + return make_pair(flow, flowCost); +} + +// Usage example +int main() { + int capacity[3][3] = { { 0, 3, 2 }, { 0, 0, 2 }, { 0, 0, 0 } }; + int n = 3; + nodes = n; + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + if (capacity[i][j] != 0) + addEdge(i, j, capacity[i][j], 1); + int s = 0; + int t = 2; + pii res = minCostFlow(s, t, INT_MAX); + int flow = res.first; + int flowCost = res.second; + cout << (4 == flow) << endl; + cout << (6 == flowCost) << endl; +} diff --git a/c++/Basic/Odd or Even.cpp b/c++/Basic/Odd or Even.cpp new file mode 100644 index 0000000..b45484b --- /dev/null +++ b/c++/Basic/Odd or Even.cpp @@ -0,0 +1,19 @@ +#include +#include + +void main() +{ + clrscr(); + int n; + cout << "Enter an integer: "; + cin >> n; + if ( n%2 == 0) + { + cout << n << " is even."; + } + else + { + cout << n << " is odd."; + } + getch(); +} \ No newline at end of file diff --git a/c++/Basic/Pattern 1.cpp b/c++/Basic/Pattern 1.cpp new file mode 100644 index 0000000..14c8278 --- /dev/null +++ b/c++/Basic/Pattern 1.cpp @@ -0,0 +1,18 @@ +#include +#include +void main() +{ + clrscr(); //clears the previous screen +//Printing first pattern (Floyds triangle) + int rows,i,j,k=0; + cout<<"Enter number of rows: "; + cin>>rows; + for(i=1; i<=rows; i++) + { + for(j=1; j<=i; ++j) + cout< +#include +void main() +{ + clrscr(); //clears the previous screen +//Printing pattern + int rows,i,j,space; + cout<<"Enter number of rows: "; + cin>>rows; + for(i=rows; i>=1; --i) + { + for(space=0; space +#include +void main() +{ + clrscr(); //clears the previous screen +//Printing first pattern (Pascals triangle) + int rows,coef=1,space,i,j; + cout<<"Enter number of rows: "; + cin>>rows; + for(i=0; i +#include +void main() +{ + clrscr(); //clears the previous screen +//Printing pattern + int i,j,rows; + cout<<"Enter the number of rows: "; + cin>>rows; + for(i=1; i<=rows; ++i) + { + for(j=1; j<=i; ++j) + { + cout<<"* "; + } + cout<<"\n"; + } + getch(); // wait for input +} + +/* +* +** +*** +**** +***** +*/ \ No newline at end of file diff --git a/c++/Basic/Pattern 4.cpp b/c++/Basic/Pattern 4.cpp new file mode 100644 index 0000000..b19e5bc --- /dev/null +++ b/c++/Basic/Pattern 4.cpp @@ -0,0 +1,27 @@ +#include +#include +void main() +{ + clrscr(); //clears the previous screen +//Printing pattern + int i,j,rows; + cout<<"Enter the number of rows: "; + cin>>rows; + for(i=1; i<=rows; ++i) + { + for(j=1; j<=i; ++j) + { + cout< +#include +void main() +{ + clrscr(); //clears the previous screen +//Printing pattern + int i,j; + char input,temp='A'; + cout<<"Enter uppercase character you want in triange at last row: "; + cin>>input; + for(i=1; i<=(input-'A'+1); ++i) + { + for(j=1; j<=i; ++j) + cout< +#include +void main() +{ + clrscr(); //clears the previous screen +//Printing pattern + int i,j,rows; + cout<<"Enter the number of rows: "; + cin>>rows; + for(i=rows; i>=1; --i) + { + for(j=1; j<=i; ++j) + { + cout<<"* "; + } + cout<<"\n"; + } + getch(); // wait for input +} + +/* +***** +**** +*** +** +* +*/ \ No newline at end of file diff --git a/c++/Basic/Pattern 7.cpp b/c++/Basic/Pattern 7.cpp new file mode 100644 index 0000000..e0a3366 --- /dev/null +++ b/c++/Basic/Pattern 7.cpp @@ -0,0 +1,27 @@ +#include +#include +void main() +{ + clrscr(); //clears the previous screen +//Printing pattern + int i,j,rows; + cout<<"Enter the number of rows: "; + cin>>rows; + for(i=rows; i>=1; --i) + { + for(j=1; j<=i; ++j) + { + cout< +#include +void main() +{ + clrscr(); //clears the previous screen +//Printing pattern + int i,space,rows,k=0; + cout<<"Enter the number of rows: "; + cin>>rows; + for(i=1; i<=rows; ++i) + { + for(space=1; space<=rows-i; ++space) + { + cout<<" "; + } + while(k!=2*i-1) + { + cout<<"* "; + ++k; + } + k=0; + cout<<"\n"; + } + getch(); // wait for input +} + +/* + * + *** + ***** + ******* + ********* + + */ \ No newline at end of file diff --git a/c++/Basic/Pattern 9.cpp b/c++/Basic/Pattern 9.cpp new file mode 100644 index 0000000..b37dc7b --- /dev/null +++ b/c++/Basic/Pattern 9.cpp @@ -0,0 +1,44 @@ +#include +#include +void main() +{ + clrscr(); //clears the previous screen +//Printing pattern + int i,space,rows,k=0,count=0,count1=0; + cout<<"Enter the number of rows: "; + cin>>rows; + for(i=1; i<=rows; ++i) + { + for(space=1; space<=rows-i; ++space) + { + cout<<" "; + ++count; + } + while(k!=2*i-1) + { + if (count<=rows-1) + { + cout< +#include +#include +#include +using namespace std; + +typedef pair pii; +typedef vector > Graph; + +long long prim(Graph &g, vector &pred) { + int n = g.size(); + pred.assign(n, -1); + vector vis(n); + vector prio(n, INT_MAX); + prio[0] = 0; + priority_queue , greater > q; + q.push(make_pair(prio[0] , 0)); + long long res = 0; + + while (!q.empty()) { + int d = q.top().first; + int u = q.top().second; + q.pop(); + if (vis[u]) + continue; + vis[u] = true; + res += d; + for (int i = 0; i < (int) g[u].size(); i++) { + int v = g[u][i].first; + if (vis[v]) + continue; + int nprio = g[u][i].second; + if (prio[v] > nprio) { + prio[v] = nprio; + pred[v] = u; + q.push(make_pair(nprio, v)); + } + } + } + return res; +} + +int main() { + Graph g(3); + g[0].push_back(make_pair(1, 10)); + g[1].push_back(make_pair(0, 10)); + g[1].push_back(make_pair(2, 10)); + g[2].push_back(make_pair(1, 10)); + g[2].push_back(make_pair(0, 5)); + g[0].push_back(make_pair(2, 5)); + + vector pred; + long long res = prim(g, pred); + cout << res << endl; +} diff --git a/c++/Basic/PrimesGenerator.cpp b/c++/Basic/PrimesGenerator.cpp new file mode 100644 index 0000000..2bedb8a --- /dev/null +++ b/c++/Basic/PrimesGenerator.cpp @@ -0,0 +1,43 @@ +#include +#include +using namespace std; + +vector getPrimes(int n) { + if (n <= 1) + return vector(); + vector prime(n + 1, true); + prime[0] = prime[1] = false; + vector primes; + for (int i = 2; i * i <= n; i++) + if (prime[i]) { + for (int j = i * i; j <= n; j += i) + prime[j] = false; + primes.push_back(i); + } + return primes; +} + +bool isPrime(long long n) { + if (n <= 1) + return false; + + for (long long i = 2; i * i <= n; i++) + if (n % i == 0) + return false; + + return true; +} + +int main() { + int n = 31; + vector primes = getPrimes(n); + + for (int i = 0; i < primes.size(); i++) + cout << primes[i] << " "; + + cout << endl; + + for (int i = 0; i <= n; i++) + if (isPrime(i)) + cout << i << " "; +} diff --git a/c++/Basic/Scanner.cpp b/c++/Basic/Scanner.cpp new file mode 100644 index 0000000..b6b81ad --- /dev/null +++ b/c++/Basic/Scanner.cpp @@ -0,0 +1,53 @@ +#include +#include + +const int BUF_SIZE = 65536; +char input[BUF_SIZE]; + +struct Scanner { + char* curPos; + + Scanner() { + fread(input, 1, sizeof(input), stdin); + curPos = input; + } + + void ensureCapacity() { + int size = input + BUF_SIZE - curPos; + if (size < 100) { + memcpy(input, curPos, size); + fread(input + size, 1, BUF_SIZE - size, stdin); + curPos = input; + } + } + + int nextInt() { + ensureCapacity(); + while (*curPos <= ' ') + ++curPos; + bool sign = false; + if (*curPos == '-') { + sign = true; + ++curPos; + } + int res = 0; + while (*curPos > ' ') + res = res * 10 + (*(curPos++) & 15); + return sign ? -res : res; + } + + char nextChar() { + ensureCapacity(); + while (*curPos <= ' ') + ++curPos; + return *(curPos++); + } +}; + +int main() { + Scanner sc; + int a = sc.nextInt(); + char b = sc.nextChar(); + + printf("%d %c\n", a, b); +} diff --git a/c++/Basic/Shutdown Computer.cpp b/c++/Basic/Shutdown Computer.cpp new file mode 100644 index 0000000..2690b57 --- /dev/null +++ b/c++/Basic/Shutdown Computer.cpp @@ -0,0 +1,14 @@ +/* for windows 7 only */ +#include < iostream.h > +#include < stdlib.h > + +main() +{ + char ch; + cout<<"Do you want to shutdown your computer now (y/n)\n"; + cin>>ch; + if (ch == 'y' || ch == 'Y') + system("C:\\WINDOWS\\System32\\shutdown /s"); + /*shutdown command*/ + return 0; +} \ No newline at end of file diff --git a/c++/Basic/SuffixArrayLcp.cpp b/c++/Basic/SuffixArrayLcp.cpp new file mode 100644 index 0000000..192c60a --- /dev/null +++ b/c++/Basic/SuffixArrayLcp.cpp @@ -0,0 +1,162 @@ +#include +#include +#include +using namespace std; + +unsigned char mask[] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; +#define tget(i) ( (t[(i)/8]&mask[(i)%8]) ? 1 : 0 ) +#define tset(i, b) t[(i)/8]=(b) ? (mask[(i)%8]|t[(i)/8]) : ((~mask[(i)%8])&t[(i)/8]) +#define chr(i) (cs==sizeof(int)?((int*)s)[i]:((unsigned char *)s)[i]) +#define isLMS(i) (i>0 && tget(i) && !tget(i-1)) + +// find the start or end of each bucket +void getBuckets(unsigned char *s, int *bkt, int n, int K, int cs, bool end) { + int i, sum = 0; + for (i = 0; i <= K; i++) + bkt[i] = 0; // clear all buckets + for (i = 0; i < n; i++) + bkt[chr(i)]++; // compute the size of each bucket + for (i = 0; i <= K; i++) { + sum += bkt[i]; + bkt[i] = end ? sum : sum - bkt[i]; + } +} +// compute SAl +void induceSAl(unsigned char *t, int *SA, unsigned char *s, int *bkt, int n, int K, int cs, bool end) { + int i, j; + getBuckets(s, bkt, n, K, cs, end); // find starts of buckets + for (i = 0; i < n; i++) { + j = SA[i] - 1; + if (j >= 0 && !tget(j)) + SA[bkt[chr(j)]++] = j; + } +} +// compute SAs +void induceSAs(unsigned char *t, int *SA, unsigned char *s, int *bkt, int n, int K, int cs, bool end) { + int i, j; + getBuckets(s, bkt, n, K, cs, end); // find ends of buckets + for (i = n - 1; i >= 0; i--) { + j = SA[i] - 1; + if (j >= 0 && tget(j)) + SA[--bkt[chr(j)]] = j; + } +} + +// find the suffix array SA of s[0..n-1] in {1..K}^n +// require s[n-1]=0 (the sentinel!), n>=2 +// use a working space (excluding s and SA) of at most 2.25n+O(1) for a constant alphabet +void SA_IS(unsigned char *s, int *SA, int n, int K, int cs) { + int i, j; + unsigned char *t = (unsigned char *) malloc(n / 8 + 1); // LS-type array in bits + // Classify the type of each character + tset(n-2, 0); + tset(n-1, 1); // the sentinel must be in s1, important!!! + for (i = n - 3; i >= 0; i--) + tset(i, (chr(i) 0 && (isLMS(pos+d) || isLMS(prev+d))) + break; + if (diff) { + name++; + prev = pos; + } + pos = (pos % 2 == 0) ? pos / 2 : (pos - 1) / 2; + SA[n1 + pos] = name - 1; + } + for (i = n - 1, j = n - 1; i >= n1; i--) + if (SA[i] >= 0) + SA[j--] = SA[i]; + // stage 2: solve the reduced problem + // recurse if names are not yet unique + int *SA1 = SA, *s1 = SA + n - n1; + if (name < n1) + SA_IS((unsigned char*) s1, SA1, n1, name - 1, sizeof(int)); + else + // generate the suffix array of s1 directly + for (i = 0; i < n1; i++) + SA1[s1[i]] = i; + // stage 3: induce the result for the original problem + bkt = (int *) malloc(sizeof(int) * (K + 1)); // bucket array + // put all left-most S characters into their buckets + getBuckets(s, bkt, n, K, cs, true); // find ends of buckets + for (i = 1, j = 0; i < n; i++) + if (isLMS(i)) + s1[j++] = i; // get p1 + for (i = 0; i < n1; i++) + SA1[i] = s1[SA1[i]]; // get index in s + for (i = n1; i < n; i++) + SA[i] = -1; // init SA[n1..n-1] + for (i = n1 - 1; i >= 0; i--) { + j = SA[i]; + SA[i] = -1; + SA[--bkt[chr(j)]] = j; + } + induceSAl(t, SA, s, bkt, n, K, cs, false); + induceSAs(t, SA, s, bkt, n, K, cs, true); + free(bkt); + free(t); +} + +const int maxn = 200000; +int sa[maxn]; +int lcp[maxn]; +int Rank[maxn]; +unsigned char *s; +int n; + +void calc_lcp() { + for (int i = 0; i < n; i++) + Rank[sa[i]] = i; + for (int i = 0, h = 0; i < n; i++) { + if (Rank[i] < n - 1) { + for (int j = sa[Rank[i] + 1]; s[i + h] == s[j + h]; ++h) + ; + lcp[Rank[i]] = h; + if (h > 0) + --h; + } + } +} + +int main() { + string str = "abcab"; + n = str.size(); + s = (unsigned char*) str.c_str(); + SA_IS(s, sa, n + 1, 256, 1); + calc_lcp(); + + for (int i = 0; i < n; i++) { + cout << str.substr(sa[i + 1]); + if (i < n - 1) + cout << " " << lcp[i + 1]; + cout << endl; + } +} diff --git a/c++/Basic/TreeIsomorphism.cpp b/c++/Basic/TreeIsomorphism.cpp new file mode 100644 index 0000000..2c16596 --- /dev/null +++ b/c++/Basic/TreeIsomorphism.cpp @@ -0,0 +1,164 @@ +#include +#include +#include + +using namespace std; + +typedef vector vi; +typedef vector vvi; + +vvi children, subtreeLabels, tree, L; +vi pred, map; +int n; + +bool compare(int a, int b) { + return subtreeLabels[a] < subtreeLabels[b]; +} + +bool equals(int a, int b) { + return subtreeLabels[a] == subtreeLabels[b]; +} + +void generateMapping(int r1, int r2) { + map.resize(n); + map[r1] = r2 - n; + sort(children[r1].begin(), children[r1].end(), compare); + sort(children[r2].begin(), children[r2].end(), compare); + for (int i = 0; i < (int) children[r1].size(); i++) { + int u = children[r1][i]; + int v = children[r2][i]; + generateMapping(u, v); + } +} + +vi findCenter(int offset = 0) { + int cnt = n; + vi a; + vi deg(n); + for (int i = 0; i < n; i++) { + deg[i] = tree[i + offset].size(); + if (deg[i] <= 1) { + a.push_back(i + offset); + --cnt; + } + } + while (cnt > 0) { + vi na; + for (int i = 0; i < (int) a.size(); i++) { + int u = a[i]; + for (int j = 0; j < (int) tree[u].size(); j++) { + int v = tree[u][j]; + if (--deg[v - offset] == 1) { + na.push_back(v); + --cnt; + } + } + } + a = na; + } + return a; +} + +int dfs(int u, int p = -1, int depth = 0) { + L[depth].push_back(u); + int h = 0; + for (int i = 0; i < (int) tree[u].size(); i++) { + int v = tree[u][i]; + if (v == p) + continue; + pred[v] = u; + children[u].push_back(v); + h = max(h, dfs(v, u, depth + 1)); + } + return h + 1; +} + +bool rootedTreeIsomorphism(int r1, int r2) { + L.assign(n, vi()); + pred.assign(2 * n, -1); + children.assign(2 * n, vi()); + + int h1 = dfs(r1); + int h2 = dfs(r2); + if (h1 != h2) + return false; + + int h = h1 - 1; + vi label(2 * n); + subtreeLabels.assign(2 * n, vi()); + + for (int i = h - 1; i >= 0; i--) { + for (int j = 0; j < (int) L[i + 1].size(); j++) { + int v = L[i + 1][j]; + subtreeLabels[pred[v]].push_back(label[v]); + } + + sort(L[i].begin(), L[i].end(), compare); + + for (int j = 0, cnt = 0; j < (int) L[i].size(); j++) { + if (j && !equals(L[i][j], L[i][j - 1])) + ++cnt; + label[L[i][j]] = cnt; + } + } + + if (!equals(r1, r2)) + return false; + + generateMapping(r1, r2); + return true; +} + +bool treeIsomorphism() { + vi c1 = findCenter(); + vi c2 = findCenter(n); + if (c1.size() == c2.size()) { + if (rootedTreeIsomorphism(c1[0], c2[0])) + return true; + else if (c1.size() > 1) + return rootedTreeIsomorphism(c1[1], c2[0]); + } + return false; +} + +int main() { + n = 5; + vvi t1(n); + t1[0].push_back(1); + t1[1].push_back(0); + t1[1].push_back(2); + t1[2].push_back(1); + t1[1].push_back(3); + t1[3].push_back(1); + t1[0].push_back(4); + t1[4].push_back(0); + + vvi t2(n); + t2[0].push_back(1); + t2[1].push_back(0); + t2[0].push_back(4); + t2[4].push_back(0); + t2[4].push_back(3); + t2[3].push_back(4); + t2[4].push_back(2); + t2[2].push_back(4); + + tree.assign(2 * n, vi()); + for (int u = 0; u < n; u++) { + for (int i = 0; i < t1[u].size(); i++) { + int v = t1[u][i]; + tree[u].push_back(v); + } + for (int i = 0; i < t2[u].size(); i++) { + int v = t2[u][i]; + tree[u + n].push_back(v + n); + } + } + + bool res = treeIsomorphism(); + cout << res << endl; + + if (res) + for (int i = 0; i < n; i++) + cout << map[i] << endl; +} diff --git a/c++/Basic/bigint-full.cpp b/c++/Basic/bigint-full.cpp new file mode 100644 index 0000000..ce1798a --- /dev/null +++ b/c++/Basic/bigint-full.cpp @@ -0,0 +1,506 @@ +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +// base and base_digits must be consistent +const int base = 1000000000; +const int base_digits = 9; + +struct bigint { + vector a; + int sign; + + bigint() : + sign(1) { + } + + bigint(long long v) { + *this = v; + } + + bigint(const string &s) { + read(s); + } + + void operator=(const bigint &v) { + sign = v.sign; + a = v.a; + } + + void operator=(long long v) { + sign = 1; + if (v < 0) + sign = -1, v = -v; + a.clear(); + for (; v > 0; v = v / base) + a.push_back(v % base); + } + + bigint operator+(const bigint &v) const { + if (sign == v.sign) { + bigint res = v; + + for (int i = 0, carry = 0; i < (int) max(a.size(), v.a.size()) || carry; ++i) { + if (i == (int) res.a.size()) + res.a.push_back(0); + res.a[i] += carry + (i < (int) a.size() ? a[i] : 0); + carry = res.a[i] >= base; + if (carry) + res.a[i] -= base; + } + return res; + } + return *this - (-v); + } + + bigint operator-(const bigint &v) const { + if (sign == v.sign) { + if (abs() >= v.abs()) { + bigint res = *this; + for (int i = 0, carry = 0; i < (int) v.a.size() || carry; ++i) { + res.a[i] -= carry + (i < (int) v.a.size() ? v.a[i] : 0); + carry = res.a[i] < 0; + if (carry) + res.a[i] += base; + } + res.trim(); + return res; + } + return -(v - *this); + } + return *this + (-v); + } + + void operator*=(int v) { + if (v < 0) + sign = -sign, v = -v; + for (int i = 0, carry = 0; i < (int) a.size() || carry; ++i) { + if (i == (int) a.size()) + a.push_back(0); + long long cur = a[i] * (long long) v + carry; + carry = (int) (cur / base); + a[i] = (int) (cur % base); + //asm("divl %%ecx" : "=a"(carry), "=d"(a[i]) : "A"(cur), "c"(base)); + /* + int val; + __asm { + lea esi, cur + mov eax, [esi] + mov edx, [esi+4] + mov ecx, base + div ecx + mov carry, eax + mov val, edx; + } + a[i] = val; + */ + } + trim(); + } + + bigint operator*(int v) const { + bigint res = *this; + res *= v; + return res; + } + + friend pair divmod(const bigint &a1, const bigint &b1) { + int norm = base / (b1.a.back() + 1); + bigint a = a1.abs() * norm; + bigint b = b1.abs() * norm; + bigint q, r; + q.a.resize(a.a.size()); + + for (int i = a.a.size() - 1; i >= 0; i--) { + r *= base; + r += a.a[i]; + int s1 = r.a.size() <= b.a.size() ? 0 : r.a[b.a.size()]; + int s2 = r.a.size() <= b.a.size() - 1 ? 0 : r.a[b.a.size() - 1]; + int d = ((long long) base * s1 + s2) / b.a.back(); + r -= b * d; + while (r < 0) + r += b, --d; + q.a[i] = d; + } + + q.sign = a1.sign * b1.sign; + r.sign = a1.sign; + q.trim(); + r.trim(); + return make_pair(q, r / norm); + } + + bigint operator/(const bigint &v) const { + return divmod(*this, v).first; + } + + bigint operator%(const bigint &v) const { + return divmod(*this, v).second; + } + + void operator/=(int v) { + if (v < 0) + sign = -sign, v = -v; + for (int i = (int) a.size() - 1, rem = 0; i >= 0; --i) { + long long cur = a[i] + rem * (long long) base; + a[i] = (int) (cur / v); + rem = (int) (cur % v); + } + trim(); + } + + bigint operator/(int v) const { + bigint res = *this; + res /= v; + return res; + } + + int operator%(int v) const { + if (v < 0) + v = -v; + int m = 0; + for (int i = a.size() - 1; i >= 0; --i) + m = (a[i] + m * (long long) base) % v; + return m * sign; + } + + void operator+=(const bigint &v) { + *this = *this + v; + } + void operator-=(const bigint &v) { + *this = *this - v; + } + void operator*=(const bigint &v) { + *this = *this * v; + } + void operator/=(const bigint &v) { + *this = *this / v; + } + + bool operator<(const bigint &v) const { + if (sign != v.sign) + return sign < v.sign; + if (a.size() != v.a.size()) + return a.size() * sign < v.a.size() * v.sign; + for (int i = a.size() - 1; i >= 0; i--) + if (a[i] != v.a[i]) + return a[i] * sign < v.a[i] * sign; + return false; + } + + bool operator>(const bigint &v) const { + return v < *this; + } + bool operator<=(const bigint &v) const { + return !(v < *this); + } + bool operator>=(const bigint &v) const { + return !(*this < v); + } + bool operator==(const bigint &v) const { + return !(*this < v) && !(v < *this); + } + bool operator!=(const bigint &v) const { + return *this < v || v < *this; + } + + void trim() { + while (!a.empty() && a.back() == 0) + a.pop_back(); + if (a.empty()) + sign = 1; + } + + bool isZero() const { + return a.empty() || (a.size() == 1 && !a[0]); + } + + bigint operator-() const { + bigint res = *this; + res.sign = -sign; + return res; + } + + bigint abs() const { + bigint res = *this; + res.sign *= res.sign; + return res; + } + + long long longValue() const { + long long res = 0; + for (int i = a.size() - 1; i >= 0; i--) + res = res * base + a[i]; + return res * sign; + } + + friend bigint gcd(const bigint &a, const bigint &b) { + return b.isZero() ? a : gcd(b, a % b); + } + friend bigint lcm(const bigint &a, const bigint &b) { + return a / gcd(a, b) * b; + } + + void read(const string &s) { + sign = 1; + a.clear(); + int pos = 0; + while (pos < (int) s.size() && (s[pos] == '-' || s[pos] == '+')) { + if (s[pos] == '-') + sign = -sign; + ++pos; + } + for (int i = s.size() - 1; i >= pos; i -= base_digits) { + int x = 0; + for (int j = max(pos, i - base_digits + 1); j <= i; j++) + x = x * 10 + s[j] - '0'; + a.push_back(x); + } + trim(); + } + + friend istream& operator>>(istream &stream, bigint &v) { + string s; + stream >> s; + v.read(s); + return stream; + } + + friend ostream& operator<<(ostream &stream, const bigint &v) { + if (v.sign == -1) + stream << '-'; + stream << (v.a.empty() ? 0 : v.a.back()); + for (int i = (int) v.a.size() - 2; i >= 0; --i) + stream << setw(base_digits) << setfill('0') << v.a[i]; + return stream; + } + + static vector convert_base(const vector &a, int old_digits, int new_digits) { + vector p(max(old_digits, new_digits) + 1); + p[0] = 1; + for (int i = 1; i < (int) p.size(); i++) + p[i] = p[i - 1] * 10; + vector res; + long long cur = 0; + int cur_digits = 0; + for (int i = 0; i < (int) a.size(); i++) { + cur += a[i] * p[cur_digits]; + cur_digits += old_digits; + while (cur_digits >= new_digits) { + res.push_back(int(cur % p[new_digits])); + cur /= p[new_digits]; + cur_digits -= new_digits; + } + } + res.push_back((int) cur); + while (!res.empty() && res.back() == 0) + res.pop_back(); + return res; + } + + void fft(vector > & a, bool invert) const { + int n = (int) a.size(); + + for (int i = 1, j = 0; i < n; ++i) { + int bit = n >> 1; + for (; j >= bit; bit >>= 1) + j -= bit; + j += bit; + if (i < j) + swap(a[i], a[j]); + } + + for (int len = 2; len <= n; len <<= 1) { + double ang = 2 * 3.14159265358979323846 / len * (invert ? -1 : 1); + complex wlen(cos(ang), sin(ang)); + for (int i = 0; i < n; i += len) { + complex w(1); + for (int j = 0; j < len / 2; ++j) { + complex u = a[i + j]; + complex v = a[i + j + len / 2] * w; + a[i + j] = u + v; + a[i + j + len / 2] = u - v; + w *= wlen; + } + } + } + if (invert) + for (int i = 0; i < n; ++i) + a[i] /= n; + } + + void multiply_fft(const vector &a, const vector &b, vector &res) const { + vector > fa(a.begin(), a.end()); + vector > fb(b.begin(), b.end()); + int n = 1; + while (n < (int) max(a.size(), b.size())) + n <<= 1; + n <<= 1; + fa.resize(n); + fb.resize(n); + + fft(fa, false); + fft(fb, false); + for (int i = 0; i < n; ++i) + fa[i] *= fb[i]; + fft(fa, true); + + res.resize(n); + for (int i = 0, carry = 0; i < n; ++i) { + res[i] = int(fa[i].real() + 0.5) + carry; + carry = res[i] / 1000; + res[i] %= 1000; + } + } + + bigint operator*(const bigint &v) const { + bigint res; + res.sign = sign * v.sign; + multiply_fft(convert_base(a, base_digits, 3), convert_base(v.a, base_digits, 3), res.a); + res.a = convert_base(res.a, 3, base_digits); + res.trim(); + return res; + } + + bigint mul_simple(const bigint &v) const { + bigint res; + res.sign = sign * v.sign; + res.a.resize(a.size() + v.a.size()); + for (int i = 0; i < (int) a.size(); ++i) + if (a[i]) + for (int j = 0, carry = 0; j < (int) v.a.size() || carry; ++j) { + long long cur = res.a[i + j] + (long long) a[i] * (j < (int) v.a.size() ? v.a[j] : 0) + carry; + carry = (int) (cur / base); + res.a[i + j] = (int) (cur % base); + } + res.trim(); + return res; + } + + typedef vector vll; + + static vll karatsubaMultiply(const vll &a, const vll &b) { + int n = a.size(); + vll res(n + n); + if (n <= 32) { + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + res[i + j] += a[i] * b[j]; + return res; + } + + int k = n >> 1; + vll a1(a.begin(), a.begin() + k); + vll a2(a.begin() + k, a.end()); + vll b1(b.begin(), b.begin() + k); + vll b2(b.begin() + k, b.end()); + + vll a1b1 = karatsubaMultiply(a1, b1); + vll a2b2 = karatsubaMultiply(a2, b2); + + for (int i = 0; i < k; i++) + a2[i] += a1[i]; + for (int i = 0; i < k; i++) + b2[i] += b1[i]; + + vll r = karatsubaMultiply(a2, b2); + for (int i = 0; i < (int) a1b1.size(); i++) + r[i] -= a1b1[i]; + for (int i = 0; i < (int) a2b2.size(); i++) + r[i] -= a2b2[i]; + + for (int i = 0; i < (int) r.size(); i++) + res[i + k] += r[i]; + for (int i = 0; i < (int) a1b1.size(); i++) + res[i] += a1b1[i]; + for (int i = 0; i < (int) a2b2.size(); i++) + res[i + n] += a2b2[i]; + return res; + } + + bigint mul_karatsuba(const bigint &v) const { + vector a6 = convert_base(this->a, base_digits, 6); + vector b6 = convert_base(v.a, base_digits, 6); + vll a(a6.begin(), a6.end()); + vll b(b6.begin(), b6.end()); + while (a.size() < b.size()) + a.push_back(0); + while (b.size() < a.size()) + b.push_back(0); + while (a.size() & (a.size() - 1)) + a.push_back(0), b.push_back(0); + vll c = karatsubaMultiply(a, b); + bigint res; + res.sign = sign * v.sign; + for (int i = 0, carry = 0; i < (int) c.size(); i++) { + long long cur = c[i] + carry; + res.a.push_back((int) (cur % 1000000)); + carry = (int) (cur / 1000000); + } + res.a = convert_base(res.a, 6, base_digits); + res.trim(); + return res; + } +}; + +bigint getRandomBigint(int len) { + string s; + for (int i = 0; i < len; i++) + s += rand() % 10 + '0'; + return bigint(s); +} + +int main() { + srand(1); + bigint a("99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"); + bigint b("19999999999999999999999999999999999999999999999999999999999999999999999999999999999999998"); + cout << a * b << endl; + cout << a.mul_karatsuba(b) << endl; + cout << a / b << endl; + + for (int step = 0; step < 100; step++) { + bigint a = getRandomBigint(1000); + bigint b = getRandomBigint(1000); + + bigint x = a * b; + bigint y = a.mul_simple(b); + bigint z = a.mul_karatsuba(b); + + if (x != y || x != z) { + cout << a << " " << b << " " << x << " " << y << " " << z << endl; + } + } + + int steps = 1; + vector x(steps), y(steps); + for (int i = 0; i < steps; i++) { + x[i] = getRandomBigint(60000); + y[i] = getRandomBigint(60000); + } + + clock_t start = clock(); + for (int i = 0; i < steps; i++) + bigint z = x[i] * y[i]; + fprintf(stderr, "time=%.3lfsec\n", 0.001 * (clock() - start)); + + start = clock(); + for (int i = 0; i < steps; i++) + bigint z = x[i].mul_karatsuba(y[i]); + fprintf(stderr, "time=%.3lfsec\n", 0.001 * (clock() - start)); + + a = getRandomBigint(10000); + b = getRandomBigint(2000); + start = clock(); + bigint c = a / b; + fprintf(stderr, "time=%.3lfsec\n", 0.001 * (clock() - start)); + + bigint z = 5; + z = 6; + cout << z << endl; +} diff --git a/c++/Basic/bigint.cpp b/c++/Basic/bigint.cpp new file mode 100644 index 0000000..4eaed78 --- /dev/null +++ b/c++/Basic/bigint.cpp @@ -0,0 +1,446 @@ +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +// base and base_digits must be consistent +const int base = 1000000000; +const int base_digits = 9; + +struct bigint { + vector z; + int sign; + + bigint() : + sign(1) { + } + + bigint(long long v) { + *this = v; + } + + bigint(const string &s) { + read(s); + } + + void operator=(const bigint &v) { + sign = v.sign; + z = v.z; + } + + void operator=(long long v) { + sign = 1; + if (v < 0) + sign = -1, v = -v; + z.clear(); + for (; v > 0; v = v / base) + z.push_back(v % base); + } + + bigint operator+(const bigint &v) const { + if (sign == v.sign) { + bigint res = v; + + for (int i = 0, carry = 0; i < (int) max(z.size(), v.z.size()) || carry; ++i) { + if (i == (int) res.z.size()) + res.z.push_back(0); + res.z[i] += carry + (i < (int) z.size() ? z[i] : 0); + carry = res.z[i] >= base; + if (carry) + res.z[i] -= base; + } + return res; + } + return *this - (-v); + } + + bigint operator-(const bigint &v) const { + if (sign == v.sign) { + if (abs() >= v.abs()) { + bigint res = *this; + for (int i = 0, carry = 0; i < (int) v.z.size() || carry; ++i) { + res.z[i] -= carry + (i < (int) v.z.size() ? v.z[i] : 0); + carry = res.z[i] < 0; + if (carry) + res.z[i] += base; + } + res.trim(); + return res; + } + return -(v - *this); + } + return *this + (-v); + } + + void operator*=(int v) { + if (v < 0) + sign = -sign, v = -v; + for (int i = 0, carry = 0; i < (int) z.size() || carry; ++i) { + if (i == (int) z.size()) + z.push_back(0); + long long cur = z[i] * (long long) v + carry; + carry = (int) (cur / base); + z[i] = (int) (cur % base); + //asm("divl %%ecx" : "=a"(carry), "=d"(a[i]) : "A"(cur), "c"(base)); + } + trim(); + } + + bigint operator*(int v) const { + bigint res = *this; + res *= v; + return res; + } + + friend pair divmod(const bigint &a1, const bigint &b1) { + int norm = base / (b1.z.back() + 1); + bigint a = a1.abs() * norm; + bigint b = b1.abs() * norm; + bigint q, r; + q.z.resize(a.z.size()); + + for (int i = a.z.size() - 1; i >= 0; i--) { + r *= base; + r += a.z[i]; + int s1 = b.z.size() < r.z.size() ? r.z[b.z.size()] : 0; + int s2 = b.z.size() - 1 < r.z.size() ? r.z[b.z.size() - 1] : 0; + int d = ((long long) s1 * base + s2) / b.z.back(); + r -= b * d; + while (r < 0) + r += b, --d; + q.z[i] = d; + } + + q.sign = a1.sign * b1.sign; + r.sign = a1.sign; + q.trim(); + r.trim(); + return make_pair(q, r / norm); + } + + friend bigint sqrt(const bigint &a1) { + bigint a = a1; + while (a.z.empty() || a.z.size() % 2 == 1) + a.z.push_back(0); + + int n = a.z.size(); + + int firstDigit = (int) sqrt((double) a.z[n - 1] * base + a.z[n - 2]); + int norm = base / (firstDigit + 1); + a *= norm; + a *= norm; + while (a.z.empty() || a.z.size() % 2 == 1) + a.z.push_back(0); + + bigint r = (long long) a.z[n - 1] * base + a.z[n - 2]; + firstDigit = (int) sqrt((double) a.z[n - 1] * base + a.z[n - 2]); + int q = firstDigit; + bigint res; + + for(int j = n / 2 - 1; j >= 0; j--) { + for(; ; --q) { + bigint r1 = (r - (res * 2 * base + q) * q) * base * base + (j > 0 ? (long long) a.z[2 * j - 1] * base + a.z[2 * j - 2] : 0); + if (r1 >= 0) { + r = r1; + break; + } + } + res *= base; + res += q; + + if (j > 0) { + int d1 = res.z.size() + 2 < r.z.size() ? r.z[res.z.size() + 2] : 0; + int d2 = res.z.size() + 1 < r.z.size() ? r.z[res.z.size() + 1] : 0; + int d3 = res.z.size() < r.z.size() ? r.z[res.z.size()] : 0; + q = ((long long) d1 * base * base + (long long) d2 * base + d3) / (firstDigit * 2); + } + } + + res.trim(); + return res / norm; + } + + bigint operator/(const bigint &v) const { + return divmod(*this, v).first; + } + + bigint operator%(const bigint &v) const { + return divmod(*this, v).second; + } + + void operator/=(int v) { + if (v < 0) + sign = -sign, v = -v; + for (int i = (int) z.size() - 1, rem = 0; i >= 0; --i) { + long long cur = z[i] + rem * (long long) base; + z[i] = (int) (cur / v); + rem = (int) (cur % v); + } + trim(); + } + + bigint operator/(int v) const { + bigint res = *this; + res /= v; + return res; + } + + int operator%(int v) const { + if (v < 0) + v = -v; + int m = 0; + for (int i = z.size() - 1; i >= 0; --i) + m = (z[i] + m * (long long) base) % v; + return m * sign; + } + + void operator+=(const bigint &v) { + *this = *this + v; + } + void operator-=(const bigint &v) { + *this = *this - v; + } + void operator*=(const bigint &v) { + *this = *this * v; + } + void operator/=(const bigint &v) { + *this = *this / v; + } + + bool operator<(const bigint &v) const { + if (sign != v.sign) + return sign < v.sign; + if (z.size() != v.z.size()) + return z.size() * sign < v.z.size() * v.sign; + for (int i = z.size() - 1; i >= 0; i--) + if (z[i] != v.z[i]) + return z[i] * sign < v.z[i] * sign; + return false; + } + + bool operator>(const bigint &v) const { + return v < *this; + } + bool operator<=(const bigint &v) const { + return !(v < *this); + } + bool operator>=(const bigint &v) const { + return !(*this < v); + } + bool operator==(const bigint &v) const { + return !(*this < v) && !(v < *this); + } + bool operator!=(const bigint &v) const { + return *this < v || v < *this; + } + + void trim() { + while (!z.empty() && z.back() == 0) + z.pop_back(); + if (z.empty()) + sign = 1; + } + + bool isZero() const { + return z.empty() || (z.size() == 1 && !z[0]); + } + + bigint operator-() const { + bigint res = *this; + res.sign = -sign; + return res; + } + + bigint abs() const { + bigint res = *this; + res.sign *= res.sign; + return res; + } + + long long longValue() const { + long long res = 0; + for (int i = z.size() - 1; i >= 0; i--) + res = res * base + z[i]; + return res * sign; + } + + friend bigint gcd(const bigint &a, const bigint &b) { + return b.isZero() ? a : gcd(b, a % b); + } + friend bigint lcm(const bigint &a, const bigint &b) { + return a / gcd(a, b) * b; + } + + void read(const string &s) { + sign = 1; + z.clear(); + int pos = 0; + while (pos < (int) s.size() && (s[pos] == '-' || s[pos] == '+')) { + if (s[pos] == '-') + sign = -sign; + ++pos; + } + for (int i = s.size() - 1; i >= pos; i -= base_digits) { + int x = 0; + for (int j = max(pos, i - base_digits + 1); j <= i; j++) + x = x * 10 + s[j] - '0'; + z.push_back(x); + } + trim(); + } + + friend istream& operator>>(istream &stream, bigint &v) { + string s; + stream >> s; + v.read(s); + return stream; + } + + friend ostream& operator<<(ostream &stream, const bigint &v) { + if (v.sign == -1) + stream << '-'; + stream << (v.z.empty() ? 0 : v.z.back()); + for (int i = (int) v.z.size() - 2; i >= 0; --i) + stream << setw(base_digits) << setfill('0') << v.z[i]; + return stream; + } + + static vector convert_base(const vector &a, int old_digits, int new_digits) { + vector p(max(old_digits, new_digits) + 1); + p[0] = 1; + for (int i = 1; i < (int) p.size(); i++) + p[i] = p[i - 1] * 10; + vector res; + long long cur = 0; + int cur_digits = 0; + for (int i = 0; i < (int) a.size(); i++) { + cur += a[i] * p[cur_digits]; + cur_digits += old_digits; + while (cur_digits >= new_digits) { + res.push_back(int(cur % p[new_digits])); + cur /= p[new_digits]; + cur_digits -= new_digits; + } + } + res.push_back((int) cur); + while (!res.empty() && res.back() == 0) + res.pop_back(); + return res; + } + + typedef vector vll; + + static vll karatsubaMultiply(const vll &a, const vll &b) { + int n = a.size(); + vll res(n + n); + if (n <= 32) { + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + res[i + j] += a[i] * b[j]; + return res; + } + + int k = n >> 1; + vll a1(a.begin(), a.begin() + k); + vll a2(a.begin() + k, a.end()); + vll b1(b.begin(), b.begin() + k); + vll b2(b.begin() + k, b.end()); + + vll a1b1 = karatsubaMultiply(a1, b1); + vll a2b2 = karatsubaMultiply(a2, b2); + + for (int i = 0; i < k; i++) + a2[i] += a1[i]; + for (int i = 0; i < k; i++) + b2[i] += b1[i]; + + vll r = karatsubaMultiply(a2, b2); + for (int i = 0; i < (int) a1b1.size(); i++) + r[i] -= a1b1[i]; + for (int i = 0; i < (int) a2b2.size(); i++) + r[i] -= a2b2[i]; + + for (int i = 0; i < (int) r.size(); i++) + res[i + k] += r[i]; + for (int i = 0; i < (int) a1b1.size(); i++) + res[i] += a1b1[i]; + for (int i = 0; i < (int) a2b2.size(); i++) + res[i + n] += a2b2[i]; + return res; + } + + bigint operator*(const bigint &v) const { + vector a6 = convert_base(this->z, base_digits, 6); + vector b6 = convert_base(v.z, base_digits, 6); + vll a(a6.begin(), a6.end()); + vll b(b6.begin(), b6.end()); + while (a.size() < b.size()) + a.push_back(0); + while (b.size() < a.size()) + b.push_back(0); + while (a.size() & (a.size() - 1)) + a.push_back(0), b.push_back(0); + vll c = karatsubaMultiply(a, b); + bigint res; + res.sign = sign * v.sign; + for (int i = 0, carry = 0; i < (int) c.size(); i++) { + long long cur = c[i] + carry; + res.z.push_back((int) (cur % 1000000)); + carry = (int) (cur / 1000000); + } + res.z = convert_base(res.z, 6, base_digits); + res.trim(); + return res; + } +}; + +bigint random_bigint(int n) { + string s; + for (int i = 0; i < n; i++) { + s += rand() % 10 + '0'; + } + return bigint(s); +} + +// random tests +int main() { + for(int i = 0; i < 1000; i++) { + cout << i << endl; + int n = rand() % 100 + 1; + bigint a = random_bigint(n); + bigint res = sqrt(a); + bigint xx = res * res; + bigint yy = (res + 1) * (res + 1); + + if (xx > a || yy <= a) { + cout << a << " " << res << endl; + break; + } + + int m = rand() % n + 1; + bigint b = random_bigint(m) + 1; + res = a / b; + xx = res * b; + yy = b * (res + 1); + + if (xx > a || yy <= a) { + cout << a << " " << b << " " << res << endl; + break; + } + } + + bigint a = random_bigint(10000); + bigint b = random_bigint(2000); + clock_t start = clock(); + bigint c = a / b; + fprintf(stdout, "time=%.3lfsec\n", 0.001 * (clock() - start)); + + bigint x = 5; + x = 6; + cout << x << endl; +} diff --git a/c++/Basic/nCr & nPr.cpp b/c++/Basic/nCr & nPr.cpp new file mode 100644 index 0000000..63754e3 --- /dev/null +++ b/c++/Basic/nCr & nPr.cpp @@ -0,0 +1,41 @@ +#include < iostream.h > + +long factorial(int); +long find_ncr(int, int); +long find_npr(int, int); + +main() +{ + int n, r; + long ncr, npr; + cout<<"Enter the value of n and r\n"; + cin>>n>>r; + ncr = find_ncr(n, r); + npr = find_npr(n, r); + cout< +#include +#include +#include +using namespace std; + +typedef complex cdouble; +typedef vector poly; + +pair horner(const poly &a, cdouble x0) { + int n = a.size(); + poly b = poly(max(1, n - 1)); + + for(int i = n - 1; i > 0; i--) + b[i - 1] = a[i] + (i < n - 1 ? b[i] * x0 : 0); + return make_pair(b, a[0] + b[0] * x0); +} + +cdouble eval(const poly &p, cdouble x) { + return horner(p, x).second; +} + +poly derivative(const poly &p) { + int n = p.size(); + poly r = poly(max(1, n - 1)); + for(int i = 1; i < n; i++) + r[i - 1] = p[i] * cdouble(i); + return r; +} + +const double EPS = 1e-9; + +int cmp(cdouble x, cdouble y) { + double diff = abs(x) - abs(y); + return diff < -EPS ? -1 : (diff > EPS ? 1 : 0); +} + +cdouble find_one_root(const poly &p0, cdouble x) { + int n = p0.size() - 1; + poly p1 = derivative(p0); + poly p2 = derivative(p1); + for (int step = 0; step < 10000; step++) { + cdouble y0 = eval(p0, x); + if (cmp(y0, 0) == 0) break; + cdouble G = eval(p1, x) / y0; + cdouble H = G * G - eval(p2, x) - y0; + cdouble R = sqrt(cdouble(n - 1) * (H * cdouble(n) - G * G)); + cdouble D1 = G + R; + cdouble D2 = G - R; + cdouble a = cdouble(n) / (cmp(D1, D2) > 0 ? D1 : D2); + x -= a; + if (cmp(a, 0) == 0) break; + } + return x; +} + +vector find_all_roots(const poly &p) { + vector res; + poly q = p; + while (q.size() > 2) { + cdouble z(rand() / double(RAND_MAX), rand() / double(RAND_MAX)); + z = find_one_root(q, z); + z = find_one_root(p, z); + q = horner(q, z).first; + res.push_back(z); + } + res.push_back(-q[0] / q[1]); + return res; +} + +int main( int argc, char* argv[] ) { + poly p; + // x^3 - 8x^2 - 13x + 140 = (x+4)(x-5)(x-7) + p.push_back(140); + p.push_back(-13); + p.push_back(-8); + p.push_back(1); + + vector roots = find_all_roots(p); + + for(size_t i = 0; i < roots.size(); i++) { + if (abs(roots[i].real()) < EPS) roots[i] -= cdouble(roots[i].real(), 0); + if (abs(roots[i].imag()) < EPS) roots[i] -= cdouble(0, roots[i].imag()); + cout << setprecision(3) << roots[i] << endl; + } + + return 0; +} diff --git a/c++/Numerical_Problems/C++ Perform to a 2D FFT Inplace Given a Complex 2D Array.cpp b/c++/Numerical_Problems/C++ Perform to a 2D FFT Inplace Given a Complex 2D Array.cpp new file mode 100644 index 0000000..deba0a7 --- /dev/null +++ b/c++/Numerical_Problems/C++ Perform to a 2D FFT Inplace Given a Complex 2D Array.cpp @@ -0,0 +1,70 @@ +/*This is a C++ Program to perform 2D FFT. A fast Fourier transform (FFT) is an algorithm to compute the discrete Fourier transform (DFT) and its inverse. Fourier analysis converts time (or space) to frequency and vice versa; an FFT rapidly computes such transformations by factorizing the DFT matrix into a product of sparse (mostly zero) factors.*/ + +#include +#include + +using namespace std; + +#define PI 3.14159265 +int n; + +int main(int argc, char **argv) +{ + cout << "Enter the size: "; + cin >> n; + double inputData[n][n]; + cout << "Enter the 2D elements "; + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + cin >> inputData[i][j]; + double realOut[n][n]; + double imagOut[n][n]; + double amplitudeOut[n][n]; + int height = n; + int width = n; + // Two outer loops iterate on output data. + for (int yWave = 0; yWave < height; yWave++) + { + for (int xWave = 0; xWave < width; xWave++) + { + // Two inner loops iterate on input data. + for (int ySpace = 0; ySpace < height; ySpace++) + { + for (int xSpace = 0; xSpace < width; xSpace++) + { + // Compute real, imag, and ampltude. + realOut[yWave][xWave] += (inputData[ySpace][xSpace] * cos( + 2 * PI * ((1.0 * xWave * xSpace / width) + (1.0 + * yWave * ySpace / height)))) / sqrt( + width * height); + imagOut[yWave][xWave] -= (inputData[ySpace][xSpace] * sin( + 2 * PI * ((1.0 * xWave * xSpace / width) + (1.0 + * yWave * ySpace / height)))) / sqrt( + width * height); + amplitudeOut[yWave][xWave] = sqrt( + realOut[yWave][xWave] * realOut[yWave][xWave] + + imagOut[yWave][xWave] + * imagOut[yWave][xWave]); + } + cout << realOut[yWave][xWave] << " + " << imagOut[yWave][xWave] + << " i (" << amplitudeOut[yWave][xWave] << ")\n"; + } + } + } +} + +/* +Enter the size: +2 +Enter the 2D elements +2 3 +4 2 + +2.5 + 0.0 i +5.5 + 0.0 i +-0.5 + -1.8369701987210297E-16 i +0.5 + -3.0616169978683826E-16 i +2.5 + 0.0 i +-0.5 + -3.6739403974420594E-16 i +-0.5 + -1.8369701987210297E-16 i +-1.5 + -1.8369701987210297E-16 i \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Check Multiplicability of Two Matrices.cpp b/c++/Numerical_Problems/C++ Program to Check Multiplicability of Two Matrices.cpp new file mode 100644 index 0000000..e0ca7bf --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Check Multiplicability of Two Matrices.cpp @@ -0,0 +1,40 @@ +#include +#include +#include + +using namespace std; + +int main(int argc, char **argv) +{ + cout<<"Enter the dimension of the matrix:\n "; + int rowA; + cin>>rowA; + int colA; + cin>>colA; + cout<<"Enter the dimension of the other matrix:\n "; + int rowB; + cin>>rowB; + int colB; + cin>>colB; + if(colA == rowB) + { + cout<<"Matrices are multipilcable"; + } + else + { + cout<<"Matrices are not multipilcable"; + } +} + +/* +Enter the dimension of the matrix: + 2 4 +Enter the dimension of the other matrix: + 2 5 +Matrices are not multipilcable + +Enter the dimension of the matrix: + 4 5 +Enter the dimension of the other matrix: + 5 6 +Matrices are multipilcable \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Check if a Matrix is Invertible.cpp b/c++/Numerical_Problems/C++ Program to Check if a Matrix is Invertible.cpp new file mode 100644 index 0000000..516edbd --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Check if a Matrix is Invertible.cpp @@ -0,0 +1,76 @@ +#include +#include +#include + +using namespace std; +double d = 0; +double det(int n, double mat[10][10]); +double det(int n, double mat[10][10]) +{ + double submat[10][10]; + if (n == 2) + return ((mat[0][0] * mat[1][1]) - (mat[1][0] * mat[0][1])); + else + { + for (int c = 0; c < n; c++) + { + int subi = 0; //submatrix's i value + for (int i = 1; i < n; i++) + { + int subj = 0; + for (int j = 0; j < n; j++) + { + if (j == c) + continue; + submat[subi][subj] = mat[i][j]; + subj++; + } + subi++; + } + d = d + (pow(-1, c) * mat[0][c] * det(n - 1, submat)); + } + } + return d; +} +int main(int argc, char **argv) +{ + cout << "Enter the dimension of the matrix:\n"; + int n; + cin >> n; + double mat[10][10]; + cout << "Enter the elements of the matrix:\n"; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cin >> mat[j][i]; + } + } + if (det(n, mat) != 0) + { + cout << "The given matrix is invertible"; + } + else + { + cout << "The given matrix is not invertible"; + } +} + +/* +Enter the dimension of the matrix: +3 +Enter the elements of the matrix: +1 2 3 +4 5 6 +7 8 9 +The given matrix is not invertible + +Enter the dimension of the matrix: +5 +Enter the elements of the matrix: +1 2 3 4 5 +6 7 8 9 0 +0 9 8 7 6 +5 4 3 2 1 +1 3 5 7 9 +The given matrix is invertible \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Check if it is a Sparse Matrix.cpp b/c++/Numerical_Problems/C++ Program to Check if it is a Sparse Matrix.cpp new file mode 100644 index 0000000..75dada5 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Check if it is a Sparse Matrix.cpp @@ -0,0 +1,54 @@ +#include +#include + +using namespace std; +int main(int argc, char **argv) +{ + cout<<"Enter the dimensions of the matrix: "; + int m, n; + cin>>m>>n; + double mat[m][n]; + int zeros = 0; + cout<<"Enter the elements of the matrix: "; + for(int i=0; i>mat[i][j]; + if(mat[i][j] == 0) + { + zeros++; + } + } + } + if(zeros > (m*n)/2) + { + cout<<"The matrix is a sparse matrix"; + } + else + { + cout<<"The matrix is not a sparse matrix"; + } +} + +/* +Enter the dimensions of the matrix: +3 3 + +Enter the elements of the matrix: +1 2 3 +4 5 6 +0 0 0 + +The matrix is not a sparse matrix + + +Enter the dimensions of the matrix: +3 3 + +Enter the elements of the matrix: +1 1 0 +0 0 1 +1 0 0 + +The matrix is a sparse matrix \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Compute DFT Coefficients Directly.cpp b/c++/Numerical_Problems/C++ Program to Compute DFT Coefficients Directly.cpp new file mode 100644 index 0000000..97ea26e --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Compute DFT Coefficients Directly.cpp @@ -0,0 +1,65 @@ +/*This is a C++ Program to compute the coefficients of the DFT (Discrete Fourier Transform) directly. In mathematics, the discrete Fourier transform (DFT) converts a finite list of equally spaced samples of a function into the list of coefficients of a finite combination of complex sinusoids, ordered by their frequencies, that has those same sample values. It can be said to convert the sampled function from its original domain (often time or position along a line) to the frequency domain.*/ + +#include +#include + +using namespace std; + +#define PI 3.14159265 + +class DFT_Coefficient +{ +public: + double real, img; + DFT_Coefficient() + { + real = 0.0; + img = 0.0; + } +}; +int main(int argc, char **argv) +{ + int N = 10; + cout << "Calculation DFT Coefficients\n"; + cout << "Enter the coefficient of simple linear function:\n"; + cout << "ax + by = c\n"; + double a, b, c; + cin >> a >> b >> c; + double function[N]; + for (int i = 0; i < N; i++) + { + function[i] = (((a * (double) i) + (b * (double) i)) - c); + //System.out.print( " "+function[i] + " "); + } + cout << "Enter the max K value: "; + int k; + cin >> k; + double cosine[N]; + double sine[N]; + for (int i = 0; i < N; i++) + { + cosine[i] = cos((2 * i * k * PI) / N); + sine[i] = sin((2 * i * k * PI) / N); + } + DFT_Coefficient dft_val; + cout << "The coefficients are: "; + for (int i = 0; i < N; i++) + { + dft_val.real += function[i] * cosine[i]; + dft_val.img += function[i] * sine[i]; + } + cout << "(" << dft_val.real << ") - " << "(" << dft_val.img << " i)"; +} + +/* +Calculation DFT Coefficients +Enter the coefficient of simple linear funtion: +ax + by = c +1 2 3 +Enter the max K value: +2 +The coefficients are: (-15) - (-20.6457 i) + +------------------ +(program exited with code: 0) +Press return to continue \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Compute Determinant of a Matrix.cpp b/c++/Numerical_Problems/C++ Program to Compute Determinant of a Matrix.cpp new file mode 100644 index 0000000..9ed3484 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Compute Determinant of a Matrix.cpp @@ -0,0 +1,69 @@ +#include +#include +#include + +using namespace std; +double d = 0; +double det(int n, double mat[10][10]); +double det(int n, double mat[10][10]) +{ + double submat[10][10]; + if (n == 2) + return ((mat[0][0] * mat[1][1]) - (mat[1][0] * mat[0][1])); + else + { + for (int c = 0; c < n; c++) + { + int subi = 0; //submatrix's i value + for (int i = 1; i < n; i++) + { + int subj = 0; + for (int j = 0; j < n; j++) + { + if (j == c) + continue; + submat[subi][subj] = mat[i][j]; + subj++; + } + subi++; + } + d = d + (pow(-1, c) * mat[0][c] * det(n - 1, submat)); + } + } + return d; +} +int main(int argc, char **argv) +{ + cout << "Enter the dimension of the matrix:\n"; + int n; + cin >> n; + double mat[10][10]; + cout << "Enter the elements of the matrix:\n"; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cin >> mat[j][i]; + } + } + cout << "The determinant of the given matrix is: " << det(n, mat); + return 0; +} + +/* +Enter the dimension of the matrix: +3 +Enter the elements of the matrix: +3 5 2 +8 4 8 +2 4 7 +The determinant of the given matrix is: -164 + +Enter the dimension of the matrix: +4 +Enter the elements of the matrix: +9 5 2 5 +9 5 3 7 +6 5 4 8 +1 5 3 7 +The determinant of the given matrix is: 0 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Compute Discrete Fourier Transform Using Naive Approach.cpp b/c++/Numerical_Problems/C++ Program to Compute Discrete Fourier Transform Using Naive Approach.cpp new file mode 100644 index 0000000..809a995 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Compute Discrete Fourier Transform Using Naive Approach.cpp @@ -0,0 +1,84 @@ +/*This is a C++ Program to perform Discrete Fourier Transform using Naive approach. In mathematics, the discrete Fourier transform (DFT) converts a finite list of equally spaced samples of a function into the list of coefficients of a finite combination of complex sinusoids, ordered by their frequencies, that has those same sample values. It can be said to convert the sampled function from its original domain (often time or position along a line) to the frequency domain.*/ + +#include +#include + +using namespace std; + +#define PI 3.14159265 + +class DFT_Coefficient +{ +public: + double real, img; + DFT_Coefficient() + { + real = 0.0; + img = 0.0; + } +}; +int main(int argc, char **argv) +{ + int N = 10; + cout << "Discrete Fourier Transform using naive method\n"; + cout << "Enter the coefficient of simple linear function:\n"; + cout << "ax + by = c\n"; + double a, b, c; + cin >> a >> b >> c; + double function[N]; + for (int i = 0; i < N; i++) + { + function[i] = (((a * (double) i) + (b * (double) i)) - c); + //System.out.print( " "+function[i] + " "); + } + cout << "Enter the max K value: "; + int k; + cin >> k; + double cosine[N]; + double sine[N]; + for (int i = 0; i < N; i++) + { + cosine[i] = cos((2 * i * k * PI) / N); + sine[i] = sin((2 * i * k * PI) / N); + } + DFT_Coefficient dft_val[k]; + cout << "The coefficients are: "; + for (int j = 0; j < k; j++) + { + for (int i = 0; i < N; i++) + { + dft_val[j].real += function[i] * cosine[i]; + dft_val[j].img += function[i] * sine[i]; + } + cout << "(" << dft_val[j].real << ") - " << "(" << dft_val[j].img << " i)\n"; + } +} + +/* + +Discrete Fourier Transform using naive method +Enter the coefficient of simple linear function: +ax + by = c +1 2 3 +Enter the max K value: 20 +The coefficients are: +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) +(105) - (-1.03386e-005 i) \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach.cpp b/c++/Numerical_Problems/C++ Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach.cpp new file mode 100644 index 0000000..49830c2 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach.cpp @@ -0,0 +1,73 @@ +/*This is a C++ Program to perform Fast Fourier Transform. A fast Fourier transform (FFT) is an algorithm to compute the discrete Fourier transform (DFT) and its inverse. Fourier analysis converts time (or space) to frequency and vice versa; an FFT rapidly computes such transformations by factorizing the DFT matrix into a product of sparse (mostly zero) factors.*/ + +#include +#include +#include +#include +using namespace std; + +unsigned int bitReverse(unsigned int x, int log2n) + +{ + int n = 0; + int mask = 0x1; + for (int i = 0; i < log2n; i++) + { + n <<= 1; + n |= (x & 1); + x >>= 1; + } + return n; +} +const double PI = 3.1415926536; +template +void fft(Iter_T a, Iter_T b, int log2n) +{ + typedef typename iterator_traits::value_type complex; + const complex J(0, 1); + int n = 1 << log2n; + for (unsigned int i = 0; i < n; ++i) + { + b[bitReverse(i, log2n)] = a[i]; + } + for (int s = 1; s <= log2n; ++s) + { + int m = 1 << s; + int m2 = m >> 1; + complex w(1, 0); + complex wm = exp(-J * (PI / m2)); + for (int j = 0; j < m2; ++j) + { + for (int k = j; k < n; k += m) + { + complex t = w * b[k + m2]; + complex u = b[k]; + b[k] = u + t; + b[k + m2] = u - t; + } + w *= wm; + } + } +} +int main(int argc, char **argv) +{ + typedef complex cx; + cx a[] = { cx(0, 0), cx(1, 1), cx(3, 3), cx(4, 4), cx(4, 4), cx(3, 3), cx( + 1, 1), cx(0, 0) + }; + cx b[8]; + fft(a, b, 3); + for (int i = 0; i < 8; ++i) + cout << b[i] << "\n"; +} + +/* + +(16,16) +(-4.82843,-11.6569) +(0,0) +(-0.343146,0.828427) +(0,0) +(0.828427,-0.343146) +(0,0) +(-11.6569,-4.82843) \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Emulate N Dice Roller.cpp b/c++/Numerical_Problems/C++ Program to Emulate N Dice Roller.cpp new file mode 100644 index 0000000..bbbb506 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Emulate N Dice Roller.cpp @@ -0,0 +1,25 @@ +#include +#include + +using namespace std; + +int main(int argc, char **argv) +{ + cout << "Enter the number of dice: "; + int n; + cin >> n; + cout << "The values on dice are: ( "; + for (int i = 0; i < n; i++) + cout << (rand() % 6) + 1<<" "; + cout<<")"; +} + +/* +Enter the number of dice: 5 +The values on dice are: ( 6 6 5 5 6 ) + +Enter the number of dice: 1 +The values on dice are: ( 6 ) + +Enter the number of dice: 3 +The values on dice are: ( 6 6 5 ) \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Find Basis and Dimension of a Matrix.cpp b/c++/Numerical_Problems/C++ Program to Find Basis and Dimension of a Matrix.cpp new file mode 100644 index 0000000..183fa0c --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Find Basis and Dimension of a Matrix.cpp @@ -0,0 +1,74 @@ +#include +#include +#include + +using namespace std; +double d = 0; +double det(int n, double mat[10][10]); +double det(int n, double mat[10][10]) +{ + double submat[10][10]; + if (n == 2) + return ((mat[0][0] * mat[1][1]) - (mat[1][0] * mat[0][1])); + else + { + for (int c = 0; c < n; c++) + { + int subi = 0; //submatrix's i value + for (int i = 1; i < n; i++) + { + int subj = 0; + for (int j = 0; j < n; j++) + { + if (j == c) + continue; + submat[subi][subj] = mat[i][j]; + subj++; + } + subi++; + } + d = d + (pow(-1, c) * mat[0][c] * det(n - 1, submat)); + } + } + return d; +} +int main(int argc, char **argv) +{ + cout << "Enter the number of vectors:\n"; + int n; + cin >> n; + double mat[10][10]; + cout << "Enter the vectors one by one:\n"; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cin >> mat[j][i]; + } + } + d = det(n, mat); + if (d != 0) + cout << "The vectors forms the basis of R" << n + << " as the determinant is non-zero"; + else + cout << "The vectors doesn't form the basis of R" << n + << " as the determinant is zero"; +} + +/* +Enter the number of vectors: +3 +Enter the vectors one by one: +1 2 3 +2 3 4 +3 4 5 +The vectors doesn't form the basis of R3 as the determinant is zero + +Enter the number of vectors: +4 +Enter the vectors one by one: +2 3 5 8 +1 6 2 9 +3 4 2 7 +2 5 3 9 +The vectors forms the basis of R4 as the determinant is non-zero \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Find Closest Pair of Points in an Array.cpp b/c++/Numerical_Problems/C++ Program to Find Closest Pair of Points in an Array.cpp new file mode 100644 index 0000000..5f7a36a --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Find Closest Pair of Points in an Array.cpp @@ -0,0 +1,137 @@ +/* + * C++ Program to Find Closest Pair of Points in an Array + */ +#include +#include +#include +#include +using namespace std; + +/* + * Point Declaration + */ +struct Point +{ + int x, y; +}; + +/* + * sort array of points according to X coordinate + */ +int compareX(const void* a, const void* b) +{ + Point *p1 = (Point *)a, *p2 = (Point *)b; + return (p1->x - p2->x); +} +/* + * sort array of points according to Y coordinate + */ +int compareY(const void* a, const void* b) +{ + Point *p1 = (Point *)a, *p2 = (Point *)b; + return (p1->y - p2->y); +} +/* + * find the distance between two points + */ +float dist(Point p1, Point p2) +{ + return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)); +} +/* + * return the smallest distance between two points + */ +float small_dist(Point P[], int n) +{ + float min = FLT_MAX; + for (int i = 0; i < n; ++i) + { + for (int j = i + 1; j < n; ++j) + { + if (dist(P[i], P[j]) < min) + min = dist(P[i], P[j]); + } + } + return min; +} +/* + * find the distance beween the closest points of strip of given size + */ +float stripClosest(Point strip[], int size, float d) +{ + float min = d; + for (int i = 0; i < size; ++i) + { + for (int j = i + 1; j < size && (strip[j].y - strip[i].y) < min; ++j) + { + if (dist(strip[i],strip[j]) < min) + min = dist(strip[i], strip[j]); + } + } + return min; +} +/* + * find the smallest distance. + */ +float closestUtil(Point Px[], Point Py[], int n) +{ + if (n <= 3) + return small_dist(Px, n); + int mid = n / 2; + Point midPoint = Px[mid]; + Point Pyl[mid + 1]; + Point Pyr[n - mid - 1]; + int li = 0, ri = 0; + for (int i = 0; i < n; i++) + { + if (Py[i].x <= midPoint.x) + Pyl[li++] = Py[i]; + else + Pyr[ri++] = Py[i]; + } + float dl = closestUtil(Px, Pyl, mid); + float dr = closestUtil(Px + mid, Pyr, n-mid); + float d = min(dl, dr); + Point strip[n]; + int j = 0; + for (int i = 0; i < n; i++) + { + if (abs(Py[i].x - midPoint.x) < d) + strip[j] = Py[i], j++; + } + return min(d, stripClosest(strip, j, d)); +} +/* + * finds the smallest distance + */ +float closest(Point P[], int n) +{ + Point Px[n]; + Point Py[n]; + for (int i = 0; i < n; i++) + { + Px[i] = P[i]; + Py[i] = P[i]; + } + qsort(Px, n, sizeof(Point), compareX); + qsort(Py, n, sizeof(Point), compareY); + return closestUtil(Px, Py, n); +} + +/* + * Main + */ +int main() +{ + Point P[] = {{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}}; + int n = sizeof(P) / sizeof(P[0]); + cout << "The smallest distance is " << closest(P, n); + return 0; +} + +/* +The smallest distance is 1.41421 + +------------------ +(program exited with code: 1) +Press return to continue \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Find Factoial of Large Numbers.cpp b/c++/Numerical_Problems/C++ Program to Find Factoial of Large Numbers.cpp new file mode 100644 index 0000000..1eb4c2f --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Find Factoial of Large Numbers.cpp @@ -0,0 +1,83 @@ +/* + * C++ Program to Find Factorial of Large Numbers + */ +#include +#include +#include +#define ll long long +using namespace std; + +int fact[101][200] = {0}; + +/* + * Find Factorial of Large Numbers + * fact[i][0] is used to store the number of digits + */ +void fact_large(int n) +{ + int i; + fact[1][0] = 1; + fact[1][1] = 1; + if (fact[n][0] == 0) + { + for (i = n - 1; i > 0 ; i--) + { + if (fact[i][0] != 0) + break; + } + for ( ; i < n; i++) + { + int j = 1; + int carry = 0; + int len = fact[i][0]; + while (len--) + { + int temp = (i + 1) * fact[i][j] + carry; + fact[i + 1][j] = temp % 10; + carry = temp / 10; + j++; + } + while (carry > 0) + { + fact[i + 1][j] = carry % 10; + carry /= 10; + j++; + } + fact[i + 1][0] = j - 1; + } + } + for (i = fact[n][0]; i > 0; i--) + { + cout << fact[n][i]; + } + cout<>n; + if (n == 0) + break; + fact_large(n); + } + return 0; +} + +/* +Enter interger to compute factorial(0 to exit): 100 +93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 +Enter interger to compute factorial(0 to exit): 50 +30414093201713378043612608166064768844377641568960512000000000000 +Enter interger to compute factorial(0 to exit): 72 +61234458376886086861524070385274672740778091784697328983823014963978384987221689274204160000000000000000 +Enter interger to compute factorial(0 to exit): 0 + +------------------ +(program exited with code: 1) +Press return to continue \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Find Factoial of a Number using Dynamic Programming.cpp b/c++/Numerical_Problems/C++ Program to Find Factoial of a Number using Dynamic Programming.cpp new file mode 100644 index 0000000..546adb9 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Find Factoial of a Number using Dynamic Programming.cpp @@ -0,0 +1,55 @@ +/* + * C++ Program to Find Factorial of a Number using Dynamic Programming + */ +#include +#include +#include +#define ll long long +using namespace std; + +int result[1000] = {0}; +/* + * Find Factorial of a Number using Dynamic Programming + */ +ll fact_dp(int n) +{ + if (n >= 0) + { + result[0] = 1; + for (int i = 1; i <= n; ++i) + { + result[i] = i * result[i - 1]; + } + return result[n]; + } +} +/* + * Main + */ +int main() +{ + int n; + while (1) + { + cout<<"Enter interger to compute factorial(0 to exit): "; + cin>>n; + if (n == 0) + break; + cout< +#include +#include +#define ll long long +using namespace std; +/* + * Find Factorial of a Number using Iteration + */ +ll fact_iter(int n) +{ + ll result = 1; + for (int i = 1; i <= n; i++) + { + result *= i; + } + return result; +} +/* + * Main + */ +int main() +{ + int n; + while (1) + { + cout<<"Enter interger to compute factorial(0 to exit): "; + cin>>n; + if (n == 0) + break; + cout< +#include +#include +#define ll long long +using namespace std; +/* + * Find Factorial of a Number using Recursion + */ +ll fact_recur(int n) +{ + if (n == 0 || n == 1) + return 1; + else + return n * fact_recur(n - 1); +} +/* + * Main + */ +int main() +{ + int n; + while (1) + { + cout<<"Enter interger to compute factorial(0 to exit): "; + cin>>n; + if (n == 0) + break; + cout< +#include +#include +#define ll long long +using namespace std; + +ll fib[1000] = {0}; +/* + * Fibonacci Numbers using Dp + */ +ll fibo_dp(int n) +{ + fib[1] = 1; + fib[2] = 1; + if (fib[n] == 0) + { + for (int j = 3; j <= n; ++j) + { + if (fib[n] == 0) + fib[j] = fib[j - 1] + fib[j - 2]; + else + continue; + } + } + return fib[n]; +} + +/* + * Main + */ +int main() +{ + int n; + while (1) + { + cout<<"Enter the integer n to find nth fibonnaci no.(0 to exit): "; + cin>>n; + if (n == 0) + break; + cout< +#include +#include +#define ll long long +using namespace std; + +/* + * Iterative function to find Fibonacci Numbers + */ +ll fibo_iter(int n) +{ + int previous = 1; + int current = 1; + int next = 1; + for (int i = 3; i <= n; ++i) + { + next = current + previous; + previous = current; + current = next; + } + return next; +} +/* + * Main + */ +int main() +{ + int n; + while (1) + { + cout<<"Enter the integer n to find nth fibonnaci no.(0 to exit): "; + cin>>n; + if (n == 0) + break; + cout< +#include +#include +#define ll long long +using namespace std; + +/* + * function to multiply two matrices + */ +void multiply(ll F[2][2], ll M[2][2]) +{ + ll x = F[0][0] * M[0][0] + F[0][1] * M[1][0]; + ll y = F[0][0] * M[0][1] + F[0][1] * M[1][1]; + ll z = F[1][0] * M[0][0] + F[1][1] * M[1][0]; + ll w = F[1][0] * M[0][1] + F[1][1] * M[1][1]; + F[0][0] = x; + F[0][1] = y; + F[1][0] = z; + F[1][1] = w; +} + +/* + * function to calculate power of a matrix + */ +void power(ll F[2][2], int n) +{ + if (n == 0 || n == 1) + return; + ll M[2][2] = {{1,1},{1,0}}; + power(F, n / 2); + multiply(F, F); + if (n % 2 != 0) + multiply(F, M); +} + +/* + * function that returns nth Fibonacci number + */ +ll fibo_matrix(ll n) +{ + ll F[2][2] = {{1,1},{1,0}}; + if (n == 0) + return 0; + power(F, n - 1); + return F[0][0]; +} +/* + * Main + */ +int main() +{ + int n; + while (1) + { + cout<<"Enter the integer n to find nth fibonnaci no.(0 to exit): "; + cin>>n; + if (n == 0) + break; + cout< +#include +#include +#define ll long long +using namespace std; + +/* + * Recursive function to find Fibonnaci Numbers + */ +ll fibo_recur(int n) +{ + if (n == 1 || n == 2) + return 1; + else + return fibo_recur(n - 1) + fibo_recur(n - 2);; +} +/* + * Main + */ +int main() +{ + int n; + while (1) + { + cout<<"Enter the integer n to find nth fibonnaci no.(0 to exit): "; + cin>>n; + if (n == 0) + break; + cout< +#include +#include + +using namespace std; +int gcd(int u, int v) +{ + return (v != 0) ? gcd(v, u % v) : u; +} + +int main(void) +{ + int num1, num2, result; + cout << "Enter two numbers to find GCD using Euclidean algorithm: "; + cin >> num1 >> num2; + result = gcd(num1, num2); + if (gcd) + cout << "\nThe GCD of " << num1 << " and " << num2 << " is: " << result + << endl; + else + cout << "\nInvalid input!!!\n"; + return 0; +} + +/* +Enter two numbers to find GCD using Euclidean algorithm: 12 30 +The GCD of 12 and 30 is: 6 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Find Inverse of a Matrix.cpp b/c++/Numerical_Problems/C++ Program to Find Inverse of a Matrix.cpp new file mode 100644 index 0000000..35a02c6 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Find Inverse of a Matrix.cpp @@ -0,0 +1,565 @@ +#if !defined(MATRIX_H) +#define MATRIX_H +#include +#include +#include +#include +#include +class CMatrix +{ +private: + int m_rows; + int m_cols; + char m_name[128]; + CMatrix(); +public: + double **m_pData; + CMatrix(const char *name, int rows, int cols) : + m_rows(rows), m_cols(cols) + { + strcpy(m_name, name); + m_pData = new double*[m_rows]; + for (int i = 0; i < m_rows; i++) + m_pData[i] = new double[m_cols]; + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + m_pData[i][j] = 0.0; + } + } + } + CMatrix(const CMatrix &other) + { + strcpy(m_name, other.m_name); + m_rows = other.m_rows; + m_cols = other.m_cols; + m_pData = new double*[m_rows]; + for (int i = 0; i < m_rows; i++) + m_pData[i] = new double[m_cols]; + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + m_pData[i][j] = other.m_pData[i][j]; + } + } + } + ~CMatrix() + { + for (int i = 0; i < m_rows; i++) + delete[] m_pData[i]; + delete[] m_pData; + m_rows = m_cols = 0; + } + void SetName(const char *name) + { + strcpy(m_name, name); + } + const char* GetName() const + { + return m_name; + } + void GetInput() + { + std::cin >> *this; + } + void FillSimulatedInput() + { + static int factor1 = 1, factor2 = 2; + std::cout << "\n\nEnter Input For Matrix : " << m_name << " Rows: " + << m_rows << " Cols: " << m_cols << "\n"; + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + std::cout << "Input For Row: " << i + 1 << " Col: " << j + + 1 << " = "; + int data = ((i + 1) * factor1) + (j + 1) * factor2; + m_pData[i][j] = data / 10.2; + std::cout << m_pData[i][j] << "\n"; + factor1 += (rand() % 4); + factor2 += (rand() % 3); + } + std::cout << "\n"; + } + std::cout << "\n"; + } + double Determinant() + { + double det = 0; + double **pd = m_pData; + switch (m_rows) + { + case 2: + { + det = pd[0][0] * pd[1][1] - pd[0][1] * pd[1][0]; + return det; + } + break; + case 3: + { + /*** + a b c + d e f + g h i + + a b c a b c + d e f d e f + g h i g h i + + // det (A) = aei + bfg + cdh - afh - bdi - ceg. + ***/ + double a = pd[0][0]; + double b = pd[0][1]; + double c = pd[0][2]; + double d = pd[1][0]; + double e = pd[1][1]; + double f = pd[1][2]; + double g = pd[2][0]; + double h = pd[2][1]; + double i = pd[2][2]; + double det = (a * e * i + b * f * g + c * d * h); + det = det - a * f * h; + det = det - b * d * i; + det = det - c * e * g; + return det; + } + break; + case 4: + { + CMatrix *temp[4]; + for (int i = 0; i < 4; i++) + temp[i] = new CMatrix("", 3, 3); + for (int k = 0; k < 4; k++) + { + for (int i = 1; i < 4; i++) + { + int j1 = 0; + for (int j = 0; j < 4; j++) + { + if (k == j) + continue; + temp[k]->m_pData[i - 1][j1++] + = this->m_pData[i][j]; + } + } + } + double det = this->m_pData[0][0] * temp[0]->Determinant() + - this->m_pData[0][1] * temp[1]->Determinant() + + this->m_pData[0][2] * temp[2]->Determinant() + - this->m_pData[0][3] * temp[3]->Determinant(); + return det; + } + break; + case 5: + { + CMatrix *temp[5]; + for (int i = 0; i < 5; i++) + temp[i] = new CMatrix("", 4, 4); + for (int k = 0; k < 5; k++) + { + for (int i = 1; i < 5; i++) + { + int j1 = 0; + for (int j = 0; j < 5; j++) + { + if (k == j) + continue; + temp[k]->m_pData[i - 1][j1++] + = this->m_pData[i][j]; + } + } + } + double det = this->m_pData[0][0] * temp[0]->Determinant() + - this->m_pData[0][1] * temp[1]->Determinant() + + this->m_pData[0][2] * temp[2]->Determinant() + - this->m_pData[0][3] * temp[3]->Determinant() + + this->m_pData[0][4] * temp[4]->Determinant(); + return det; + } + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + default: + { + int DIM = m_rows; + CMatrix **temp = new CMatrix*[DIM]; + for (int i = 0; i < DIM; i++) + temp[i] = new CMatrix("", DIM - 1, DIM - 1); + for (int k = 0; k < DIM; k++) + { + for (int i = 1; i < DIM; i++) + { + int j1 = 0; + for (int j = 0; j < DIM; j++) + { + if (k == j) + continue; + temp[k]->m_pData[i - 1][j1++] + = this->m_pData[i][j]; + } + } + } + double det = 0; + for (int k = 0; k < DIM; k++) + { + if ((k % 2) == 0) + det = det + (this->m_pData[0][k] + * temp[k]->Determinant()); + else + det = det - (this->m_pData[0][k] + * temp[k]->Determinant()); + } + for (int i = 0; i < DIM; i++) + delete temp[i]; + delete[] temp; + return det; + } + break; + } + } + CMatrix& operator =(const CMatrix &other) + { + if (this->m_rows != other.m_rows || this->m_cols != other.m_cols) + { + std::cout + << "WARNING: Assignment is taking place with by changing the number of rows and columns of the matrix"; + } + for (int i = 0; i < m_rows; i++) + delete[] m_pData[i]; + delete[] m_pData; + m_rows = m_cols = 0; + strcpy(m_name, other.m_name); + m_rows = other.m_rows; + m_cols = other.m_cols; + m_pData = new double*[m_rows]; + for (int i = 0; i < m_rows; i++) + m_pData[i] = new double[m_cols]; + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + m_pData[i][j] = other.m_pData[i][j]; + } + } + return *this; + } + CMatrix CoFactor() + { + CMatrix cofactor("COF", m_rows, m_cols); + if (m_rows != m_cols) + return cofactor; + if (m_rows < 2) + return cofactor; + else if (m_rows == 2) + { + cofactor.m_pData[0][0] = m_pData[1][1]; + cofactor.m_pData[0][1] = -m_pData[1][0]; + cofactor.m_pData[1][0] = -m_pData[0][1]; + cofactor.m_pData[1][1] = m_pData[0][0]; + return cofactor; + } + else if (m_rows >= 3) + { + int DIM = m_rows; + CMatrix ***temp = new CMatrix**[DIM]; + for (int i = 0; i < DIM; i++) + temp[i] = new CMatrix*[DIM]; + for (int i = 0; i < DIM; i++) + for (int j = 0; j < DIM; j++) + temp[i][j] = new CMatrix("", DIM - 1, DIM - 1); + for (int k1 = 0; k1 < DIM; k1++) + { + for (int k2 = 0; k2 < DIM; k2++) + { + int i1 = 0; + for (int i = 0; i < DIM; i++) + { + int j1 = 0; + for (int j = 0; j < DIM; j++) + { + if (k1 == i || k2 == j) + continue; + temp[k1][k2]->m_pData[i1][j1++] + = this->m_pData[i][j]; + } + if (k1 != i) + i1++; + } + } + } + bool flagPositive = true; + for (int k1 = 0; k1 < DIM; k1++) + { + flagPositive = ((k1 % 2) == 0); + for (int k2 = 0; k2 < DIM; k2++) + { + if (flagPositive == true) + { + cofactor.m_pData[k1][k2] + = temp[k1][k2]->Determinant(); + flagPositive = false; + } + else + { + cofactor.m_pData[k1][k2] + = -temp[k1][k2]->Determinant(); + flagPositive = true; + } + } + } + for (int i = 0; i < DIM; i++) + for (int j = 0; j < DIM; j++) + delete temp[i][j]; + for (int i = 0; i < DIM; i++) + delete[] temp[i]; + delete[] temp; + } + return cofactor; + } + CMatrix Adjoint() + { + CMatrix cofactor("COF", m_rows, m_cols); + CMatrix adj("ADJ", m_rows, m_cols); + if (m_rows != m_cols) + return adj; + cofactor = this->CoFactor(); + // adjoint is transpose of a cofactor of a matrix + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + adj.m_pData[j][i] = cofactor.m_pData[i][j]; + } + } + return adj; + } + CMatrix Transpose() + { + CMatrix trans("TR", m_cols, m_rows); + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + trans.m_pData[j][i] = m_pData[i][j]; + } + } + return trans; + } + CMatrix Inverse() + { + CMatrix cofactor("COF", m_rows, m_cols); + CMatrix inv("INV", m_rows, m_cols); + if (m_rows != m_cols) + return inv; + // to find out Determinant + double det = Determinant(); + cofactor = this->CoFactor(); + // inv = transpose of cofactor / Determinant + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + inv.m_pData[j][i] = cofactor.m_pData[i][j] / det; + } + } + return inv; + } + CMatrix operator +(const CMatrix &other) + { + if (this->m_rows != other.m_rows || this->m_cols != other.m_cols) + { + std::cout + << "Addition could not take place because number of rows and columns are different between the two matrices"; + return *this; + } + CMatrix result("", m_rows, m_cols); + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + result.m_pData[i][j] = this->m_pData[i][j] + + other.m_pData[i][j]; + } + } + return result; + } + CMatrix operator -(const CMatrix &other) + { + if (this->m_rows != other.m_rows || this->m_cols != other.m_cols) + { + std::cout + << "Subtraction could not take place because number of rows and columns are different between the two matrices"; + return *this; + } + CMatrix result("", m_rows, m_cols); + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + result.m_pData[i][j] = this->m_pData[i][j] + - other.m_pData[i][j]; + } + } + return result; + } + CMatrix operator *(const CMatrix &other) + { + if (this->m_cols != other.m_rows) + { + std::cout + << "Multiplication could not take place because number of columns of 1st Matrix and number of rows in 2nd Matrix are different"; + return *this; + } + CMatrix result("", this->m_rows, other.m_cols); + for (int i = 0; i < this->m_rows; i++) + { + for (int j = 0; j < other.m_cols; j++) + { + for (int k = 0; k < this->m_cols; k++) + { + result.m_pData[i][j] += this->m_pData[i][k] + * other.m_pData[k][j]; + } + } + } + return result; + } + bool operator ==(const CMatrix &other) + { + if (this->m_rows != other.m_rows || this->m_cols != other.m_cols) + { + std::cout + << "Comparision could not take place because number of rows and columns are different between the two matrices"; + return false; + } + CMatrix result("", m_rows, m_cols); + bool bEqual = true; + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + if (this->m_pData[i][j] != other.m_pData[i][j]) + bEqual = false; + } + } + return bEqual; + } + friend std::istream& operator >>(std::istream &is, CMatrix &m); + friend std::ostream& operator <<(std::ostream &os, const CMatrix &m); +}; +std::istream& operator >>(std::istream &is, CMatrix &m) +{ + std::cout << "\n\nEnter Input For Matrix : " << m.m_name << " Rows: " + << m.m_rows << " Cols: " << m.m_cols << "\n"; + for (int i = 0; i < m.m_rows; i++) + { + for (int j = 0; j < m.m_cols; j++) + { + std::cout << "Input For Row: " << i + 1 << " Col: " << j + 1 + << " = "; + is >> m.m_pData[i][j]; + } + std::cout << "\n"; + } + std::cout << "\n"; + return is; +} +std::ostream& operator <<(std::ostream &os, const CMatrix &m) +{ + os << "\n\nMatrix : " << m.m_name << " Rows: " << m.m_rows << " Cols: " + << m.m_cols << "\n\n"; + for (int i = 0; i < m.m_rows; i++) + { + os << " | "; + for (int j = 0; j < m.m_cols; j++) + { + char buf[32]; + double data = m.m_pData[i][j]; + if (m.m_pData[i][j] > -0.00001 && m.m_pData[i][j] < 0.00001) + data = 0; + sprintf(buf, "%10.2lf ", data); + os << buf; + } + os << "|\n"; + } + os << "\n\n"; + return os; +} +#endif +int main() +{ + CMatrix a("A", 5, 5); + //std::cin >> a; + a.FillSimulatedInput(); + CMatrix aadj = a.Inverse(); + std::cout << a; + std::cout << aadj; + CMatrix unit = (a * aadj); + unit.SetName("A * A-Inv"); + std::cout << unit; +} + +/* + +Enter Input For Matrix : +A Rows: 5 +Cols: 5 +Input For Row: 1 Col: 1 = 0.294118 +Input For Row: 1 Col: 2 = 0.980392 +Input For Row: 1 Col: 3 = 1.86275 +Input For Row: 1 Col: 4 = 2.84314 +Input For Row: 1 Col: 5 = 3.62745 + +Input For Row: 2 Col: 1 = 2.54902 +Input For Row: 2 Col: 2 = 3.92157 +Input For Row: 2 Col: 3 = 5.09804 +Input For Row: 2 Col: 4 = 7.05882 +Input For Row: 2 Col: 5 = 9.80392 + +Input For Row: 3 Col: 1 = 6.66667 +Input For Row: 3 Col: 2 = 8.92157 +Input For Row: 3 Col: 3 = 10.8824 +Input For Row: 3 Col: 4 = 12.6471 +Input For Row: 3 Col: 5 = 15.3922 + +Input For Row: 4 Col: 1 = 12.0588 +Input For Row: 4 Col: 2 = 15.098 +Input For Row: 4 Col: 3 = 18.1373 +Input For Row: 4 Col: 4 = 20.7843 +Input For Row: 4 Col: 5 = 24.4118 + +Input For Row: 5 Col: 1 = 21.1765 +Input For Row: 5 Col: 2 = 24.7059 +Input For Row: 5 Col: 3 = 27.7451 +Input For Row: 5 Col: 4 = 31.0784 +Input For Row: 5 Col: 5 = 34.3137 + +Matrix : A Rows: 5 Cols: 5 + + | 0.29 0.98 1.86 2.84 3.63 | + | 2.55 3.92 5.10 7.06 9.80 | + | 6.67 8.92 10.88 12.65 15.39 | + | 12.06 15.10 18.14 20.78 24.41 | + | 21.18 24.71 27.75 31.08 34.31 | + +Matrix : INV Rows: 5 Cols: 5 + + | -0.93 0.80 -3.74 2.86 -0.49 | + | 0.37 -0.32 5.35 -4.91 1.14 | + | -0.78 -0.93 -1.46 2.96 -1.10 | + | 2.37 -0.10 0.25 -1.65 0.84 | + | -1.21 0.57 -0.58 0.87 -0.36 | + +Matrix : A * A-Inv Rows: 5 Cols: 5 + + | 1.00 0.00 0.00 0.00 0.00 | + | 0.00 1.00 0.00 0.00 0.00 | + | 0.00 0.00 1.00 0.00 0.00 | + | 0.00 0.00 0.00 1.00 0.00 | + | 0.00 0.00 0.00 0.00 1.00 | \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Find Path Between Two Nodes in a Graph.cpp b/c++/Numerical_Problems/C++ Program to Find Path Between Two Nodes in a Graph.cpp new file mode 100644 index 0000000..9808b2a --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Find Path Between Two Nodes in a Graph.cpp @@ -0,0 +1,109 @@ +#include +#include + +using namespace std; + +// This class represents a directed graph using adjacency list representation +class Graph +{ + int V; // No. of vertices + list *adj; // Pointer to an array containing adjacency lists +public: + Graph(int V); // Constructor + void addEdge(int v, int w); // function to add an edge to graph + bool isReachable(int s, int d); // returns true if there is a path from s to d +}; + +Graph::Graph(int V) +{ + this->V = V; + adj = new list [V]; +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +// A BFS based function to check whether d is reachable from s. +bool Graph::isReachable(int s, int d) +{ + // Base case + if (s == d) + return true; + // Mark all the vertices as not visited + bool *visited = new bool[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + // Create a queue for BFS + list queue; + // Mark the current node as visited and enqueue it + visited[s] = true; + queue.push_back(s); + // it will be used to get all adjacent vertices of a vertex + list::iterator i; + while (!queue.empty()) + { + // Dequeue a vertex from queue and print it + s = queue.front(); + queue.pop_front(); + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it visited + // and enqueue it + for (i = adj[s].begin(); i != adj[s].end(); ++i) + { + // If this adjacent node is the destination node, then return true + if (*i == d) + return true; + // Else, continue to do BFS + if (!visited[*i]) + { + visited[*i] = true; + queue.push_back(*i); + } + } + } + return false; +} + +// Driver program to test methods of graph class +int main() +{ + // Create a graph given in the above diagram + Graph g(4); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + cout << "Enter the source and destination vertices: (0-3)"; + int u, v; + cin >> u >> v; + if (g.isReachable(u, v)) + cout << "\nThere is a path from " << u << " to " << v; + else + cout << "\nThere is no path from " << u << " to " << v; + int temp; + temp = u; + u = v; + v = temp; + if (g.isReachable(u, v)) + cout << "\nThere is a path from " << u << " to " << v; + else + cout << "\nThere is no path from " << u << " to " << v; + return 0; +} + +/* +Enter the source and destination vertices: (0-3) +1 3 + +There is a path from 1 to 3 +There is no path from 3 to 1 + +Enter the source and destination vertices: (0-3) +2 3 + +There is a path from 2 to 3 +There is no path from 3 to 2 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Find the GCD and LCM of n Numbers.cpp b/c++/Numerical_Problems/C++ Program to Find the GCD and LCM of n Numbers.cpp new file mode 100644 index 0000000..6d40571 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Find the GCD and LCM of n Numbers.cpp @@ -0,0 +1,57 @@ +#include +#include +#include + +using namespace std; + +int gcd(int x, int y) +{ + int r = 0, a, b; + a = (x > y) ? x : y; // a is greater number + b = (x < y) ? x : y; // b is smaller number + r = b; + while (a % b != 0) + { + r = a % b; + a = b; + b = r; + } + return r; +} + +int lcm(int x, int y) +{ + int a; + a = (x > y) ? x : y; // a is greater number + while (true) + { + if (a % x == 0 && a % y == 0) + return a; + ++a; + } +} + +int main(int argc, char **argv) +{ + cout << "Enter the two numbers: "; + int x, y; + cin >> x >> y; + cout << "The GCD of two numbers is: " << gcd(x, y) << endl; + ; + cout << "The LCM of two numbers is: " << lcm(x, y) << endl; + ; + return 0; +} + +/* +Enter the two numbers: +5 +8 +The GCD of two numbers is: 1 +The LCM of two numbers is: 40 + +Enter the two numbers: +100 +50 +The GCD of two numbers is: 50 +The LCM of two numbers is: 100 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Generate N Number of Passwords of Length M Each.cpp b/c++/Numerical_Problems/C++ Program to Generate N Number of Passwords of Length M Each.cpp new file mode 100644 index 0000000..7dafe6f --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Generate N Number of Passwords of Length M Each.cpp @@ -0,0 +1,179 @@ +#include +#include +#include + +using namespace std; + +void permute(int *a, int k, int size) +{ + if (k == size) + { + for (int i = 0; i < size; i++) + { + cout << *(a + i); + } + cout << endl; + } + else + { + for (int i = k; i < size; i++) + { + int temp = a[k]; + a[k] = a[i]; + a[i] = temp; + permute(a, k + 1, size); + temp = a[k]; + a[k] = a[i]; + a[i] = temp; + } + } +} +int main(int argc, char **argv) +{ + cout << "Enter the length of the password: "; + int m; + cin >> m; + int a[m]; + for (int i = 0; i < m; i++) + { + /*generates random number between 1 and 10*/ + a[i] = rand() % 10; + } + for (int i = 0; i < m; i++) + { + cout << a[i] << ", "; + } + cout << "The Passwords are: "; + permute(a, 0, m); +} + +/* +Enter the length of the password: 3 +1, 7, 4, The Passwords are: 174 +147 +714 +741 +471 +417 + +Enter the length of the password: 5 +1, 7, 4, 0, 9, The Passwords are: 17409 +17490 +17049 +17094 +17904 +17940 +14709 +14790 +14079 +14097 +14907 +14970 +10479 +10497 +10749 +10794 +10974 +10947 +19407 +19470 +19047 +19074 +19704 +19740 +71409 +71490 +71049 +71094 +71904 +71940 +74109 +74190 +74019 +74091 +74901 +74910 +70419 +70491 +70149 +70194 +70914 +70941 +79401 +79410 +79041 +79014 +79104 +79140 +47109 +47190 +47019 +47091 +47901 +47910 +41709 +41790 +41079 +41097 +41907 +41970 +40179 +40197 +40719 +40791 +40971 +40917 +49107 +49170 +49017 +49071 +49701 +49710 +07419 +07491 +07149 +07194 +07914 +07941 +04719 +04791 +04179 +04197 +04917 +04971 +01479 +01497 +01749 +01794 +01974 +01947 +09417 +09471 +09147 +09174 +09714 +09741 +97401 +97410 +97041 +97014 +97104 +97140 +94701 +94710 +94071 +94017 +94107 +94170 +90471 +90417 +90741 +90714 +90174 +90147 +91407 +91470 +91047 +91074 +91704 +91740 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Generate Prime Numbers Between a Given Range Using the Sieve of Sundaram.cpp b/c++/Numerical_Problems/C++ Program to Generate Prime Numbers Between a Given Range Using the Sieve of Sundaram.cpp new file mode 100644 index 0000000..b1658ac --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Generate Prime Numbers Between a Given Range Using the Sieve of Sundaram.cpp @@ -0,0 +1,72 @@ +#include + +using namespace std; + +int main() +{ + cout << "Welcome to the Sieve of Sundaram\n" << endl; + int arraySize; + int numberPrimes = 0; + cout << "Input a positive integer to find all the prime numbers up to and " + << "\nincluding that number: "; + cin >> arraySize; + int n = arraySize / 2; + /* array to start off with that will eventually get + all the composite numbers removed and the remaining + ones output to the screen */ + int isPrime[arraySize + 1]; + for (int i = 0; i < n; ++i) + { + isPrime[i] = i; + } + for (int i = 1; i < n; i++) + { + for (int j = i; j <= (n - i) / (2 * i + 1); j++) + { + isPrime[i + j + 2 * i * j] = 0;/*From this list, remove all + numbers of the form i + j + 2ij */ + } + } + int TheseArePrime = 0; + if (arraySize > 2) + { + isPrime[TheseArePrime++] = 2;/*this IF statement adds 2 to the output */ + } + for (int i = 1; i < n; i++) + { + if (isPrime[i] != 0) + { + isPrime[TheseArePrime++] = i * 2 + 1; + } + } + int size = sizeof isPrime / sizeof(int);//total size of array/size of array data type + for (int x = 0; x <= size; x++) + { + if (isPrime[x] != 0) + { + cout << isPrime[x] << "\t";//outputs all prime numbers found + numberPrimes++;// the counter of the number of primes found + } + else + { + break; + } + } + cout << "\nNumber of Primes: " << numberPrimes << endl; + return 0; +} + +/* +Welcome to the Sieve of Sundaram + +Input a positive integer to find all the prime numbers up to and +including that number: 10 +2 3 5 7 +Number of Primes: 4 + +Welcome to the Sieve of Sundaram + +Input a positive integer to find all the prime numbers up to and +including that number: 100 +2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 +Number of Primes: 25 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Generate Random Hexadecimal Bytes.cpp b/c++/Numerical_Problems/C++ Program to Generate Random Hexadecimal Bytes.cpp new file mode 100644 index 0000000..3e5d8fe --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Generate Random Hexadecimal Bytes.cpp @@ -0,0 +1,18 @@ +#include +#include +#include + +using namespace std; + +int main(int argc, char **argv) +{ + int val = rand(); + char Hex[33]; + itoa(val, Hex, 16); + cout<< "Random Decimal Byte:" << val; + cout << "\nEquivalent Hex Byte: " << Hex; +} + +/* +Random Decimal Byte:41 +Equivalent Hex Byte: 29 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Generate Random Numbers Using Middle Square Method.cpp b/c++/Numerical_Problems/C++ Program to Generate Random Numbers Using Middle Square Method.cpp new file mode 100644 index 0000000..7c86fb8 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Generate Random Numbers Using Middle Square Method.cpp @@ -0,0 +1,45 @@ +/*This is a C++ Program to generate random numbers using Middle Square method. In mathematics, the middle-square method is a method of generating pseudorandom numbers. In practice it is not a good method, since its period is usually very short and it has some severe weaknesses, such as the output sequence almost always converging to zero.*/ + +#include +#include +#include + +using namespace std; + +int a[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 }; +int middleSquareNumber(int numb, int dig) +{ + int sqn = numb * numb, next_num = 0; + int trim = (dig / 2); + sqn = sqn / a[trim]; + for (int i = 0; i < dig; i++) + { + next_num += (sqn % (a[trim])) * (a[i]); + sqn = sqn / 10; + } + return next_num; +} + +int main(int argc, char **argv) +{ + cout << "Enter the #-digit random numbers you want: "; + int n; + cin >> n; + int start = 1, end = 1; + start = a[n - 1]; + end = a[n]; + int number = ((rand()) % (end - start)) + start; + cout << "The random numbers are:\n" << number << ", "; + for (int i = 1; i < n; i++) + { + number = middleSquareNumber(number, n); + cout << number << ", "; + } + cout << "..."; +} + +/* + +Enter the #-digit random numbers you want: 5 +The random numbers are: +10041, 16426, 796264, -276041, -115546, ... \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Generate Random Numbers Using Multiply with Carry Method.cpp b/c++/Numerical_Problems/C++ Program to Generate Random Numbers Using Multiply with Carry Method.cpp new file mode 100644 index 0000000..e343a7f --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Generate Random Numbers Using Multiply with Carry Method.cpp @@ -0,0 +1,31 @@ +/*This is a C++ Program to generate random numbers using Multiply with Carry method. In computer science, multiply-with-carry (MWC) is a method invented by George Marsaglia for generating sequences of random integers based on an initial set from two to many thousands of randomly chosen seed values. The main advantages of the MWC method are that it invokes simple computer integer arithmetic and leads to very fast generation of sequences of random numbers with immense periods, ranging from around 260 to 22000000.*/ + +#include +#include +#include + +using namespace std; + +int main(int argc, char **argv) +{ + int max_Sequence_Elements = 10; + int base_b = 2000; + int multiplier_a = rand() % base_b; + int r = 1; + int c[max_Sequence_Elements]; + int x[max_Sequence_Elements]; + c[0] = rand() % multiplier_a; + x[0] = rand() % base_b; + cout << "The random number sequence is: " << x[0]; + //generating sequence + for (int i = 1; i < max_Sequence_Elements; i++) + { + x[i] = (multiplier_a * x[i - r] + c[i - 1]) % base_b; + c[i] = (multiplier_a * x[i - r] + c[i - 1]) / base_b; + cout << " " << x[i]; + } + cout << "..."; +} + +/* +The random number sequence is: 334 1711 157 472 1355 1564 151 223 1146 990... \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Generate Random Numbers Using Probability Distribution Function.cpp b/c++/Numerical_Problems/C++ Program to Generate Random Numbers Using Probability Distribution Function.cpp new file mode 100644 index 0000000..c26e7ba --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Generate Random Numbers Using Probability Distribution Function.cpp @@ -0,0 +1,34 @@ +/*This is a C++ Program to generate random numbers using Probability Distribution Function. Probability distribution is based on probability density function. a probability density function (pdf), or density of a continuous random variable, is a function that describes the relative likelihood for this random variable to take on a given value. The probability of the random variable falling within a particular range of values is given by the integral of this variable’s density over that range—that is, it is given by the area under the density function but above the horizontal axis and between the lowest and greatest values of the range.*/ + +//pdf(x) = 1 if x>360 +// = 0 if x<0 +// = x/360 otherwise +#include +#include +#include + +using namespace std; + +//This is a sample program to generate a random numbers based on probability desity function of spiner +//pdf(x) = 1 if x>360 +// = 0 if x<0 +// = x/360 otherwise +int N = 10; +int main(int argc, char **argv) +{ + int p = 0; + for (int i = 0; i < N; i++) + { + p = rand() % 400; + if (p > 360) + cout << 0 << " "; + else if (p < 0) + cout << 0 << " "; + else + cout << p * 0.1 / 360 << " "; + } + cout << "..."; +} + +/* +0.0113889 0.0186111 0.0927778 0.0277778 0 0.0344444 0.0772222 0.0438889 0.045 0.0177778 ... \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Generate Randomized Sequence of Given Range of Numbers.cpp b/c++/Numerical_Problems/C++ Program to Generate Randomized Sequence of Given Range of Numbers.cpp new file mode 100644 index 0000000..8d9a98c --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Generate Randomized Sequence of Given Range of Numbers.cpp @@ -0,0 +1,26 @@ +#include +#include +#include + +const int LOW = 1; +const int HIGH = 32000; + +using namespace std; + +int main() +{ + int randomNumber; + time_t seconds; + time(&seconds); + srand((unsigned int) seconds); + for (int i = 0; i < 10; i++) + { + randomNumber = rand() % (HIGH - LOW + 1) + LOW; + cout << randomNumber << " "; + } + cout << "..."; + return 0; +} + +/* +312 7423 23444 16008 31816 1823 29315 17424 11753 18384 ... \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Implement Booth’s Multiplication Algorithm for Multiplication of 2 signed Numbers.cpp b/c++/Numerical_Problems/C++ Program to Implement Booth’s Multiplication Algorithm for Multiplication of 2 signed Numbers.cpp new file mode 100644 index 0000000..a80bf8a --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Implement Booth’s Multiplication Algorithm for Multiplication of 2 signed Numbers.cpp @@ -0,0 +1,141 @@ +/*This is a C++ Program to multiply two signed numbers using booth’s algorithm. Booth’s multiplication algorithm is a multiplication algorithm that multiplies two signed binary numbers in two’s complement notation. Booth used desk calculators that were faster at shifting than adding and created the algorithm to increase their speed. Booth’s algorithm is of interest in the study of computer architecture.*/ + +#include +#include + +using namespace std; + +void add(int a[], int x[], int qrn); +void complement(int a[], int n) +{ + int i; + int x[8] = { NULL }; + x[0] = 1; + for (i = 0; i < n; i++) + { + a[i] = (a[i] + 1) % 2; + } + add(a, x, n); +} + +void add(int ac[], int x[], int qrn) +{ + int i, c = 0; + for (i = 0; i < qrn; i++) + { + ac[i] = ac[i] + x[i] + c; + if (ac[i] > 1) + { + ac[i] = ac[i] % 2; + c = 1; + } + else + c = 0; + } +} + +void ashr(int ac[], int qr[], int &qn, int qrn) +{ + int temp, i; + temp = ac[0]; + qn = qr[0]; + cout << "\t\tashr\t\t"; + for (i = 0; i < qrn - 1; i++) + { + ac[i] = ac[i + 1]; + qr[i] = qr[i + 1]; + } + qr[qrn - 1] = temp; +} + +void display(int ac[], int qr[], int qrn) +{ + int i; + for (i = qrn - 1; i >= 0; i--) + cout << ac[i]; + cout << " "; + for (i = qrn - 1; i >= 0; i--) + cout << qr[i]; +} + +int main(int argc, char **argv) +{ + int mt[10], br[10], qr[10], sc, ac[10] = { 0 }; + int brn, qrn, i, qn, temp; + cout + << "\n--Enter the multiplicand and multipier in signed 2's complement form if negative--"; + cout << "\n Number of multiplicand bit="; + cin >> brn; + cout << "\nmultiplicand="; + for (i = brn - 1; i >= 0; i--) + cin >> br[i]; //multiplicand + for (i = brn - 1; i >= 0; i--) + mt[i] = br[i]; // copy multipier to temp array mt[] + complement(mt, brn); + cout << "\nNo. of multiplier bit="; + cin >> qrn; + sc = qrn; //sequence counter + cout << "Multiplier="; + for (i = qrn - 1; i >= 0; i--) + cin >> qr[i]; //multiplier + qn = 0; + temp = 0; + cout << "qn\tq[n+1]\t\tBR\t\tAC\tQR\t\tsc\n"; + cout << "\t\t\tinitial\t\t"; + display(ac, qr, qrn); + cout << "\t\t" << sc << "\n"; + while (sc != 0) + { + cout << qr[0] << "\t" << qn; + if ((qn + qr[0]) == 1) + { + if (temp == 0) + { + add(ac, mt, qrn); + cout << "\t\tsubtracting BR\t"; + for (i = qrn - 1; i >= 0; i--) + cout << ac[i]; + temp = 1; + } + else if (temp == 1) + { + add(ac, br, qrn); + cout << "\t\tadding BR\t"; + for (i = qrn - 1; i >= 0; i--) + cout << ac[i]; + temp = 0; + } + cout << "\n\t"; + ashr(ac, qr, qn, qrn); + } + else if (qn - qr[0] == 0) + ashr(ac, qr, qn, qrn); + display(ac, qr, qrn); + cout << "\t"; + sc--; + cout << "\t" << sc << "\n"; + } + cout << "Result="; + display(ac, qr, qrn); +} + +/* +--Enter the multiplicand and multipier in signed 2's complement form if negative-- +Number of multiplicand bit=5 +Multiplicand=1 0 1 1 1 + +Number of multiplier bit=5 +Multiplier=1 0 0 1 1 + +qn q[n+1] BR AC QR sc + initial 00000 10011 5 +1 0 subtracting BR 01001 + ashr 00100 11001 4 +1 1 ashr 00010 01100 3 +0 1 adding BR 11001 + ashr 11100 10110 2 +0 0 ashr 11110 01011 1 +1 0 subtracting BR 00111 + ashr 00011 10101 0 + +Result=00011 10101 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Implement Coppersmith Freivald’s Algorithm.cpp b/c++/Numerical_Problems/C++ Program to Implement Coppersmith Freivald’s Algorithm.cpp new file mode 100644 index 0000000..b5fe347 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Implement Coppersmith Freivald’s Algorithm.cpp @@ -0,0 +1,129 @@ +#include +#include +#include + +using namespace std; + +int main(int argc, char **argv) +{ + cout << "Enter the dimension of the matrices: "; + int n; + cin >> n; + cout << "Enter the 1st matrix: "; + double a[n][n]; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cin >> a[i][j]; + } + } + cout << "Enter the 2nd matrix: "; + double b[n][n]; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cin >> b[i][j]; + } + } + cout << "Enter the result matrix: "; + double c[n][n]; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cin >> c[i][j]; + } + } + //random generation of the r vector containing only 0/1 as its elements + double r[n][1]; + for (int i = 0; i < n; i++) + { + r[i][0] = rand() % 2; + cout << r[i][0] << " "; + } + //test A * (b*r) - (C*) = 0 + double br[n][1]; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < 1; j++) + { + for (int k = 0; k < n; k++) + { + br[i][j] = br[i][j] + b[i][k] * r[k][j]; + } + } + } + double cr[n][1]; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < 1; j++) + { + for (int k = 0; k < n; k++) + { + cr[i][j] = cr[i][j] + c[i][k] * r[k][j]; + } + } + } + double abr[n][1]; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < 1; j++) + { + for (int k = 0; k < n; k++) + { + abr[i][j] = abr[i][j] + a[i][k] * br[k][j]; + } + } + } + // br = multiplyVector(b, r, n); + // cr = multiplyVector(c, r, n); + // abr = multiplyVector(a, br, n); + //abr-cr + for (int i = 0; i < n; i++) + { + abr[i][0] -= cr[i][0]; + } + bool flag = true; + for (int i = 0; i < n; i++) + { + if (abr[i][0] == 0) + continue; + else + flag = false; + } + if (flag == true) + cout << "Yes"; + else + cout << "No"; +} + +/* + +Enter the dimension of the matrices: 2 +Enter the 1st matrix: +1 2 +2 3 +Enter the 2nd matrix: +1 3 +3 4 +Enter the result matrix: +9 9 +14 15 + +Yes + +Enter the dimesion of the matrices: +2 +Enter the 1st matrix: +2 3 +3 4 +Enter the 2st matrix: +1 0 +1 2 +Enter the result matrix: +6 5 +8 7 + +Yes \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Implement Euler Theorem.cpp b/c++/Numerical_Problems/C++ Program to Implement Euler Theorem.cpp new file mode 100644 index 0000000..a9d5d16 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Implement Euler Theorem.cpp @@ -0,0 +1,37 @@ +/* + * C++ Program to Implement Euler Theorem + */ +#include +#include +using namespace std; + +vector inverseArray(int n, int m) +{ + vector modInverse(n + 1, 0); + modInverse[1] = 1; + for (int i = 2; i <= n; i++) + { + modInverse[i] = (-(m / i) * modInverse[m % i]) % m + m; + } + return modInverse; +} +//Main +int main() +{ + vector::iterator it; + int a, m; + cout<<"Enter number to find modular multiplicative inverse: "; + cin>>a; + cout<<"Enter Modular Value: "; + cin>>m; + cout< +#include + +using namespace std; +/* return the gcd of a and b followed by the pair x and y of + equation ax + by = gcd(a,b) +*/ +pair > extendedEuclid(int a, int b) +{ + int x = 1, y = 0; + int xLast = 0, yLast = 1; + int q, r, m, n; + while (a != 0) + { + q = b / a; + r = b % a; + m = xLast - q * x; + n = yLast - q * y; + xLast = x; + yLast = y; + x = m; + y = n; + b = a; + a = r; + } + return make_pair(b, make_pair(xLast, yLast)); +} + +int modInverse(int a, int m) +{ + return (extendedEuclid(a, m).second.first + m) % m; +} + +//Main +int main() +{ + int a, m; + cout<<"Enter number to find modular multiplicative inverse: "; + cin>>a; + cout<<"Enter Modular Value: "; + cin>>m; + cout< +#include +#include +#define ll long long +using namespace std; +/* + * modular exponentiation + */ +ll modulo(ll base, ll exponent, ll mod) +{ + ll x = 1; + ll y = base; + while (exponent > 0) + { + if (exponent % 2 == 1) + x = (x * y) % mod; + y = (y * y) % mod; + exponent = exponent / 2; + } + return x % mod; +} + +/* + * Fermat's test for checking primality + */ +bool Fermat(ll p, int iterations) +{ + if (p == 1) + { + return false; + } + for (int i = 0; i < iterations; i++) + { + ll a = rand() % (p - 1) + 1; + if (modulo(a, p - 1, p) != 1) + { + return false; + } + } + return true; +} +/* + * Main + */ +int main() +{ + int iteration = 50; + ll num; + cout<<"Enter integer to test primality: "; + cin>>num; + if (Fermat(num, iteration)) + cout< +using namespace std; + +/* calculates (a^b)%MOD */ +int pow(int a, int b, int MOD) +{ + int x = 1, y = a; + while (b > 0) + { + if (b % 2 == 1) + { + x = (x * y); + if (x > MOD) + x %= MOD; + } + y = (y * y); + if (y > MOD) + y %= MOD; + b /= 2; + } + return x; +} + +int modInverse(int a, int m) +{ + return pow(a, m - 2, m); +} +//Main +int main() +{ + int a, m; + cout<<"Enter number to find modular multiplicative inverse: "; + cin>>a; + cout<<"Enter Modular Value: "; + cin>>m; + cout< +#include + +using namespace std; + +void fisherYatesShuffling(int *arr, int n) +{ + int a[n]; + int ind[n]; + for (int i = 0; i < n; i++) + ind[i] = 0; + int index; + for (int i = 0; i < n; i++) + { + do + { + index = rand() % n; + } + while (ind[index] != 0); + ind[index] = 1; + a[i] = *(arr + index); + } + for (int i = 0; i < n; i++) + { + cout << a[i] << " "; + } +} + +int main(int argc, char **argv) +{ + cout << "Enter the array size: "; + int n; + cin >> n; + cout << "Enter the array elements: "; + int a[n]; + for (int i = 0; i < n; i++) + { + cin >> a[i]; + } + fisherYatesShuffling(a, n); +} + +/* +Enter the array size: 7 +Enter the array elements: 12 23 34 45 56 67 78 +78 23 67 45 34 12 56 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Implement Gauss Seidel Method.cpp b/c++/Numerical_Problems/C++ Program to Implement Gauss Seidel Method.cpp new file mode 100644 index 0000000..8ca7766 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Implement Gauss Seidel Method.cpp @@ -0,0 +1,80 @@ +#include +#include + +using namespace std; + +int main(void) +{ + float a[10][10], b[10], x[10], y[10]; + int n = 0, m = 0, i = 0, j = 0; + cout << "Enter size of 2d array(Square matrix) : "; + cin >> n; + for (i = 0; i < n; i++) + { + for (j = 0; j < n; j++) + { + cout << "Enter values no :(" << i << ", " << j << ") "; + cin >> a[i][j]; + } + } + cout << "\nEnter Values to the right side of equation\n"; + for (i = 0; i < n; i++) + { + cout << "Enter values no :(" << i << ", " << j << ") "; + cin >> b[i]; + } + cout << "Enter initial values of x\n"; + for (i = 0; i < n; i++) + { + cout << "Enter values no. :(" << i<<"):"; + cin >> x[i]; + } + cout << "\nEnter the no. of iteration : "; + cin >> m; + while (m > 0) + { + for (i = 0; i < n; i++) + { + y[i] = (b[i] / a[i][i]); + for (j = 0; j < n; j++) + { + if (j == i) + continue; + y[i] = y[i] - ((a[i][j] / a[i][i]) * x[j]); + x[i] = y[i]; + } + printf("x%d = %f ", i + 1, y[i]); + } + cout << "\n"; + m--; + } + return 0; +} + +/* +Enter size of 2d array(Square matrix) : 3 +Enter values no :(0, 0) 2 +Enter values no :(0, 1) 3 +Enter values no :(0, 2) 1 +Enter values no :(1, 0) 5 +Enter values no :(1, 1) 4 +Enter values no :(1, 2) 6 +Enter values no :(2, 0) 8 +Enter values no :(2, 1) 7 +Enter values no :(2, 2) 9 + +Enter Values to the right side of equation +Enter values no :(0, 3) 2 +Enter values no :(1, 3) 3 +Enter values no :(2, 3) 4 + +Enter initial values of x +Enter values no. :(0): 0 +Enter values no. :(1): 0 +Enter values no. :(2): 0 + +Enter the no. of iteration : 4 +x1 = 1.000000 x2 = -0.500000 x3 = -0.055556 +x1 = 1.777778 x2 = -1.388889 x3 = -0.055556 +x1 = 3.111111 x2 = -3.055555 x3 = 0.055555 +x1 = 5.555555 x2 = -6.277777 x3 = 0.388889 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Implement Miller Rabin Primality Test.cpp b/c++/Numerical_Problems/C++ Program to Implement Miller Rabin Primality Test.cpp new file mode 100644 index 0000000..c361a53 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Implement Miller Rabin Primality Test.cpp @@ -0,0 +1,98 @@ +/* + * C++ Program to Implement Miller Rabin Primality Test + */ +#include +#include +#include +#define ll long long +using namespace std; + +/* + * calculates (a * b) % c taking into account that a * b might overflow + */ +ll mulmod(ll a, ll b, ll mod) +{ + ll x = 0,y = a % mod; + while (b > 0) + { + if (b % 2 == 1) + { + x = (x + y) % mod; + } + y = (y * 2) % mod; + b /= 2; + } + return x % mod; +} +/* + * modular exponentiation + */ +ll modulo(ll base, ll exponent, ll mod) +{ + ll x = 1; + ll y = base; + while (exponent > 0) + { + if (exponent % 2 == 1) + x = (x * y) % mod; + y = (y * y) % mod; + exponent = exponent / 2; + } + return x % mod; +} + +/* + * Miller-Rabin primality test, iteration signifies the accuracy + */ +bool Miller(ll p,int iteration) +{ + if (p < 2) + { + return false; + } + if (p != 2 && p % 2==0) + { + return false; + } + ll s = p - 1; + while (s % 2 == 0) + { + s /= 2; + } + for (int i = 0; i < iteration; i++) + { + ll a = rand() % (p - 1) + 1, temp = s; + ll mod = modulo(a, temp, p); + while (temp != p - 1 && mod != 1 && mod != p - 1) + { + mod = mulmod(mod, mod, p); + temp *= 2; + } + if (mod != p - 1 && temp % 2 == 0) + { + return false; + } + } + return true; +} +//Main +int main() +{ + int iteration = 5; + ll num; + cout<<"Enter integer to test primality: "; + cin>>num; + if (Miller(num, iteration)) + cout< +#define ll long long +using namespace std; + +/* + * Function to calculate modulus of x raised to the power y + */ +ll modular_pow(ll base, ll exponent, int modulus) +{ + ll result = 1; + while (exponent > 0) + { + if (exponent % 2 == 1) + result = (result * base) % modulus; + exponent = exponent >> 1; + base = (base * base) % modulus; + } + return result; +} +/* + * Main + */ +int main() +{ + ll x, y; + int mod; + cout<<"Enter Base Value: "; + cin>>x; + cout<<"Enter Exponent: "; + cin>>y; + cout<<"Enter Modular Value: "; + cin>>mod; + cout< +#include +#include + +using namespace std; + +int main(int argc, char **argv) +{ + int p = 7, l = 3, g = 2, n = 4, x; + int a[] = { 1, 2, 2, 1 }; + int bin[4]; + cout << "The Random numbers are: "; + for (int i = 0; i < 10; i++) + { + x = rand() % 16; + for (int j = 3; j >= 0; j--) + { + bin[j] = x % 2; + x /= 2; + } + int mul = 1; + for (int k = 0; k < 4; k++) + mul *= pow(a[k], bin[k]); + cout << pow(g, mul)<<" "; + } +} + +/* +The Random numbers are: +2 4 16 4 2 4 16 16 4 2 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Implement Park-Miller Random Number Generation Algorithm.cpp b/c++/Numerical_Problems/C++ Program to Implement Park-Miller Random Number Generation Algorithm.cpp new file mode 100644 index 0000000..ba16b82 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Implement Park-Miller Random Number Generation Algorithm.cpp @@ -0,0 +1,51 @@ +/*This is a C++ Program to generate random numbers using Park-Miller algorithm. A general formula of a random number generator (RNG) of this type is: +X_{k+1} = g X(k) mod n +where the modulus n is a prime number or a power of a prime number, the multiplier g is an element of high multiplicative order modulo n (e.g., a primitive root modulo n), and the seed X0 is co-prime to n.*/ + +#include +#include +#include + +using namespace std; + +const long m = 2147483647L; +const long a = 48271L; +const long q = 44488L; +const long r = 3399L; + +static long r_seed = 12345678L; + +double uniform() +{ + long hi = r_seed / q; + long lo = r_seed - q * hi; + long t = a * lo - r * hi; + if (t > 0) + r_seed = t; + else + r_seed = t + m; + return r_seed; +} + +int main(int argc, char **argv) +{ + double A[10]; + for (int i = 0; i < 10; i++) + A[i] = uniform(); + cout<<"Random numbers are:\n"; + for (int i = 0; i < 10; i++) + cout << A[i]< +using namespace std; +/* + * multiply two numbers using Russian Peasant method + */ +unsigned int russianPeasant(unsigned int a, unsigned int b) +{ + int res = 0; + while (b > 0) + { + if (b & 1) + res = res + a; + a = a << 1; + b = b >> 1; + } + return res; +} + +/* + * Main + */ +int main() +{ + cout << russianPeasant(15, 5) << endl; + cout << russianPeasant(13, 6) << endl; + return 0; +} + +/* +75 +78 + +------------------ +(program exited with code: 1) +Press return to continue \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Implement Segmented Sieve.cpp b/c++/Numerical_Problems/C++ Program to Implement Segmented Sieve.cpp new file mode 100644 index 0000000..8b7d84c --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Implement Segmented Sieve.cpp @@ -0,0 +1,91 @@ +/* + * C++ Program to Implement Segmented Sieve + */ +#include +#include +#define MAX 46656 +#define LMT 216 +#define LEN 4830 +#define RNG 100032 +#define sq(x) ((x)*(x)) +#define mset(x,v) memset(x, v , sizeof(x)) +#define chkC(x,n) (x[n >> 6] & (1 << ((n >> 1) & 31))) +#define setC(x,n) (x[n >> 6] |= (1 << ((n >> 1) & 31))) +using namespace std; +unsigned base[MAX/64], segment[RNG/64], primes[LEN]; + +/* + * Generates all the necessary prime numbers and marks them in base[] + */ +void sieve() +{ + unsigned i, j, k; + for (i = 3; i < LMT; i += 2) + { + if (!chkC(base, i)) + { + for (j = i * i, k = i << 1; j < MAX; j += k) + setC(base, j); + } + } + for (i = 3, j = 0; i < MAX; i += 2) + { + if (!chkC(base, i)) + primes[j++] = i; + } +} + +/* + * Returns the prime-count within range [a,b] and marks them in segment[] + */ +int segmented_sieve(int a, int b) +{ + unsigned i, j, k, cnt = (a <= 2 && 2 <=b )? 1 : 0; + if (b < 2) + return 0; + if (a < 3) + a = 3; + if (a % 2 == 0) + a++; + mset (segment, 0); + for (i = 0; sq(primes[i]) <= b; i++) + { + j = primes[i] * ((a + primes[i] - 1) / primes[i]); + if (j % 2 == 0) j += primes[i]; + for (k = primes[i] << 1; j <= b; j += k) + { + if (j != primes[i]) + setC(segment, (j - a)); + } + } + for (i = 0; i <= b - a; i += 2) + { + if (!chkC(segment, i)) + cnt++; + } + return cnt; +} +/* + * Main + */ +int main() +{ + sieve(); + int a, b; + cout<<"Enter Lower Bound: "; + cin>>a; + cout<<"Enter Upper Bound: "; + cin>>b; + cout<<"Number of primes between "< +#include +#include +#define ll long long + +using namespace std; + +/* + * Sieve of Atkins + */ +void sieve_atkins(ll int n) +{ + vector is_prime(n + 1); + is_prime[2] = true; + is_prime[3] = true; + for (ll int i = 5; i <= n; i++) + { + is_prime[i] = false; + } + ll int lim = ceil(sqrt(n)); + for (ll int x = 1; x <= lim; x++) + { + for (ll int y = 1; y <= lim; y++) + { + ll int num = (4 * x * x + y * y); + if (num <= n && (num % 12 == 1 || num % 12 == 5)) + { + is_prime[num] = true; + } + num = (3 * x * x + y * y); + if (num <= n && (num % 12 == 7)) + { + is_prime[num] = true; + } + if (x > y) + { + num = (3 * x * x - y * y); + if (num <= n && (num % 12 == 11)) + { + is_prime[num] = true; + } + } + } + } + for (ll int i = 5; i <= lim; i++) + { + if (is_prime[i]) + { + for (ll int j = i * i; j <= n; j += i) + { + is_prime[j] = false; + } + } + } + for (ll int i = 2; i <= n; i++) + { + if (is_prime[i]) + { + cout< +const int len = 100; + +int main() +{ + int arr[100] = {0}; + for (int i = 2; i < 100; i++) + { + for (int j = i * i; j < 100; j+=i) + { + arr[j - 1] = 1; + } + } + for (int i = 1; i < 100; i++) + { + if (arr[i - 1] == 0) + std::cout << i << "\t"; + } +} + +/* +1 2 3 5 7 11 13 17 19 23 +29 31 37 41 43 47 53 59 61 67 +71 73 79 83 89 97 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Implement Solovay-Strassen Primality Test.cpp b/c++/Numerical_Problems/C++ Program to Implement Solovay-Strassen Primality Test.cpp new file mode 100644 index 0000000..bbcefb2 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Implement Solovay-Strassen Primality Test.cpp @@ -0,0 +1,110 @@ +/* + * C++ Program to Implement Solovay-Strassen Primality Test + */ +#include +#include +#include +#define ll long long +using namespace std; +/* + * modular exponentiation + */ +ll modulo(ll base, ll exponent, ll mod) +{ + ll x = 1; + ll y = base; + while (exponent > 0) + { + if (exponent % 2 == 1) + x = (x * y) % mod; + y = (y * y) % mod; + exponent = exponent / 2; + } + return x % mod; +} +/* + * calculates Jacobian(a/n) n>0 and n is odd + */ +int calculateJacobian(ll a,ll n) +{ + if (!a) + return 0; + int ans = 1; + ll temp; + if (a < 0) + { + a = -a; + if (n % 4 == 3) + ans=-ans; + } + if (a == 1) + return ans; + while (a) + { + if (a < 0) + { + a = -a; + if (n % 4 == 3) + ans = -ans; + } + while (a % 2 == 0) + { + a = a / 2; + if (n % 8 == 3 || n % 8 == 5) + ans = -ans; + } + swap(a, n); + if (a % 4 == 3 && n % 4 == 3) + ans = -ans; + a = a % n; + if (a > n / 2) + a = a - n; + } + if (n == 1) + return ans; + return 0; +} + +/* + * Solovay-Strassen Primality Test + * Iterations determine the accuracy of the test + */ +bool Solovoy(ll p, int iteration) +{ + if (p < 2) + return false; + if (p != 2 && p % 2 == 0) + return false; + for (int i = 0; i < iteration; i++) + { + ll a = rand() % (p - 1) + 1; + ll jacobian = (p + calculateJacobian(a, p)) % p; + ll mod = modulo(a, (p - 1) / 2, p); + if (!jacobian || mod != jacobian) + { + return false; + } + } + return true; +} +//Main +int main() +{ + int iteration = 50; + ll num; + cout<<"Enter integr to test primality: "; + cin>>num; + if (Solovoy(num, iteration)) + cout< +#include +#include +#include + +#define M 2 +#define N (1<rb = rm; // top rows + else + b->ra = rm; // bot rows + if (j == 0) + b->cb = cm; // left cols + else + b->ca = cm; // right cols +} + +// Multiply: A[a] * B[b] => C[c], recursively. +void mul(mat A, mat B, mat C, corners a, corners b, corners c) +{ + corners aii[2][2], bii[2][2], cii[2][2], p; + mat P[7], S, T; + int i, j, m, n, k; + // Check: A[m n] * B[n k] = C[m k] + m = a.rb - a.ra; + assert(m==(c.rb-c.ra)); + n = a.cb - a.ca; + assert(n==(b.rb-b.ra)); + k = b.cb - b.ca; + assert(k==(c.cb-c.ca)); + assert(m>0); + if (n == 1) + { + C[c.ra][c.ca] += A[a.ra][a.ca] * B[b.ra][b.ca]; + return; + } + // Create the 12 smaller matrix indexes: + // A00 A01 B00 B01 C00 C01 + // A10 A11 B10 B11 C10 C11 + for (i = 0; i < 2; i++) + { + for (j = 0; j < 2; j++) + { + find_corner(a, i, j, &aii[i][j]); + find_corner(b, i, j, &bii[i][j]); + find_corner(c, i, j, &cii[i][j]); + } + } + p.ra = p.ca = 0; + p.rb = p.cb = m / 2; +#define LEN(A) (sizeof(A)/sizeof(A[0])) + for (i = 0; i < LEN(P); i++) + set(P[i], p, 0); +#define ST0 set(S,p,0); set(T,p,0) + // (A00 + A11) * (B00+B11) = S * T = P0 + ST0; + add(A, A, S, aii[0][0], aii[1][1], p); + add(B, B, T, bii[0][0], bii[1][1], p); + mul(S, T, P[0], p, p, p); + // (A10 + A11) * B00 = S * B00 = P1 + ST0; + add(A, A, S, aii[1][0], aii[1][1], p); + mul(S, B, P[1], p, bii[0][0], p); + // A00 * (B01 - B11) = A00 * T = P2 + ST0; + sub(B, B, T, bii[0][1], bii[1][1], p); + mul(A, T, P[2], aii[0][0], p, p); + // A11 * (B10 - B00) = A11 * T = P3 + ST0; + sub(B, B, T, bii[1][0], bii[0][0], p); + mul(A, T, P[3], aii[1][1], p, p); + // (A00 + A01) * B11 = S * B11 = P4 + ST0; + add(A, A, S, aii[0][0], aii[0][1], p); + mul(S, B, P[4], p, bii[1][1], p); + // (A10 - A00) * (B00 + B01) = S * T = P5 + ST0; + sub(A, A, S, aii[1][0], aii[0][0], p); + add(B, B, T, bii[0][0], bii[0][1], p); + mul(S, T, P[5], p, p, p); + // (A01 - A11) * (B10 + B11) = S * T = P6 + ST0; + sub(A, A, S, aii[0][1], aii[1][1], p); + add(B, B, T, bii[1][0], bii[1][1], p); + mul(S, T, P[6], p, p, p); + // P0 + P3 - P4 + P6 = S - P4 + P6 = T + P6 = C00 + add(P[0], P[3], S, p, p, p); + sub(S, P[4], T, p, p, p); + add(T, P[6], C, p, p, cii[0][0]); + // P2 + P4 = C01 + add(P[2], P[4], C, p, p, cii[0][1]); + // P1 + P3 = C10 + add(P[1], P[3], C, p, p, cii[1][0]); + // P0 + P2 - P1 + P5 = S - P1 + P5 = T + P5 = C11 + add(P[0], P[2], S, p, p, p); + sub(S, P[1], T, p, p, p); + add(T, P[5], C, p, p, cii[1][1]); +} +int main() +{ + mat A, B, C; + corners ai = { 0, N, 0, N }; + corners bi = { 0, N, 0, N }; + corners ci = { 0, N, 0, N }; + srand(time(0)); + // identity(A,bi); identity(B,bi); + // set(A,ai,2); set(B,bi,2); + randk(A, ai, 0, 2); + randk(B, bi, 0, 2); + print(A, ai, "A"); + print(B, bi, "B"); + set(C, ci, 0); + // add(A,B,C, ai, bi, ci); + mul(A, B, C, ai, bi, ci); + print(C, ci, "C"); + return 0; +} + +/* + +A = { + 1.2, 0.83, 0.39, 0.41, + 1.8, 1.9, 0.49, 0.23, +0.38, 0.72, 1.8, 1.9, +0.13, 1.8, 0.48, 0.82, +} +B = { + 1.2, 1.6, 1.4, 1.6, +0.27, 0.63, 0.3, 0.79, +0.58, 1.2, 1.1, 0.07, + 2, 1.9, 0.47, 0.47, +} +C = { + 2.7, 3.7, 2.6, 2.9, + 3.4, 5, 3.7, 4.5, + 5.3, 6.7, 3.6, 2.2, + 2.5, 3.5, 1.6, 2.1, +} \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Implement the Bin Packing Algorithm.cpp b/c++/Numerical_Problems/C++ Program to Implement the Bin Packing Algorithm.cpp new file mode 100644 index 0000000..f95ab57 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Implement the Bin Packing Algorithm.cpp @@ -0,0 +1,52 @@ +/*This is a C++ Program to implement Bin packing algorithm. This is a sample program to illustrate the Bin-Packing algorithm using next fit heuristics. In the bin packing problem, objects of different volumes must be packed into a finite number of bins or containers each of volume V in a way that minimizes the number of bins used. In computational complexity theory, it is a combinatorial NP-hard problem. +There are many variations of this problem, such as 2D packing, linear packing, packing by weight, packing by cost, and so on. They have many applications, such as filling up containers, loading trucks with weight capacity constraints, creating file backups in media and technology mapping in Field-programmable gate array semiconductor chip design. + +The bin packing problem can also be seen as a special case of the cutting stock problem. When the number of bins is restricted to 1 and each item is characterised by both a volume and a value, the problem of maximising the value of items that can fit in the bin is known as the knapsack problem.*/ + +#include + +using namespace std; + +void binPacking(int *a, int size, int n) +{ + int binCount = 1; + int s = size; + for (int i = 0; i < n; i++) + { + if (s - *(a + i) > 0) + { + s -= *(a + i); + continue; + } + else + { + binCount++; + s = size; + i--; + } + } + cout << "Number of bins required: " << binCount; +} + +int main(int argc, char **argv) +{ + cout << "BIN - PACKING Algorithm\n"; + cout << "Enter the number of items in Set: "; + int n; + cin >> n; + cout << "Enter " << n << " items:"; + int a[n]; + for (int i = 0; i < n; i++) + cin >> a[i]; + cout << "Enter the bin size: "; + int size; + cin >> size; + binPacking(a, size, n); +} + +/* +BIN - PACKING Algorithm +Enter the number of items in Set: 5 +Enter 5 items:12 23 34 45 56 +Enter the bin size: 70 +Number of bins required: 3 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers.cpp b/c++/Numerical_Problems/C++ Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers.cpp new file mode 100644 index 0000000..cfe517d --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers.cpp @@ -0,0 +1,62 @@ +#include + +using namespace std; + +int noOfDigit(long a) +{ + int n = 0; + while (a > 0) + { + a /= 10; + n++; + } + return n; +} +void schonhageStrassenMultiplication(long x, long y, int n, int m) +{ + int linearConvolution[n + m - 1]; + for (int i = 0; i < (n + m - 1); i++) + linearConvolution[i] = 0; + long p = x; + for (int i = 0; i < m; i++) + { + x = p; + for (int j = 0; j < n; j++) + { + linearConvolution[i + j] += (y % 10) * (x % 10); + x /= 10; + } + y /= 10; + } + cout << "The Linear Convolution is: ( "; + for (int i = (n + m - 2); i >= 0; i--) + { + cout << linearConvolution[i] << " "; + } + cout << ")"; + long product = 0; + int nextCarry = 0, base = 1; + ; + for (int i = 0; i < n + m - 1; i++) + { + linearConvolution[i] += nextCarry; + product = product + (base * (linearConvolution[i] % 10)); + nextCarry = linearConvolution[i] / 10; + base *= 10; + } + cout << "\nThe Product of the numbers is: " << product; +} +int main(int argc, char **argv) +{ + cout << "Enter the numbers:"; + long a, b; + cin >> a >> b; + int n = noOfDigit(a); + int m = noOfDigit(b); + schonhageStrassenMultiplication(a, b, n, m); +} + +/* +Enter the numbers:3452 1245 +The Linear Convolution is: ( 3 10 25 43 44 33 10 ) + Product of the numbers is: 4297740 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Implement the linear congruential generator for Pseudo Random Number Generation.cpp b/c++/Numerical_Problems/C++ Program to Implement the linear congruential generator for Pseudo Random Number Generation.cpp new file mode 100644 index 0000000..a422fd1 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Implement the linear congruential generator for Pseudo Random Number Generation.cpp @@ -0,0 +1,95 @@ +/*This is a C++ Program to generate random numbers using Linear Congruential Generator. A linear congruential generator (LCG) is an algorithm that yields a sequence of pseudo-randomized numbers calculated with a discontinuous piecewise linear equation. The method represents one of the oldest and best-known pseudorandom number generator algorithms. The theory behind them is relatively easy to understand, and they are easily implemented and fast, especially on computer hardware which can provide modulo arithmetic by storage-bit truncation.*/ + +#include + +using namespace std; + +class mRND +{ +public: + void seed(unsigned int s) + { + _seed = s; + } + +protected: + mRND() : + _seed(0), _a(0), _c(0), _m(2147483648) + { + } + int rnd() + { + return (_seed = (_a * _seed + _c) % _m); + } + + int _a, _c; + unsigned int _m, _seed; +}; + +class MS_RND: public mRND +{ +public: + MS_RND() + { + _a = 214013; + _c = 2531011; + } + int rnd() + { + return mRND::rnd() >> 16; + } +}; + +class BSD_RND: public mRND +{ +public: + BSD_RND() + { + _a = 1103515245; + _c = 12345; + } + int rnd() + { + return mRND::rnd(); + } +}; + +int main(int argc, char* argv[]) +{ + BSD_RND bsd_rnd; + MS_RND ms_rnd; + cout << "MS RAND:" << endl << "========" << endl; + for (int x = 0; x < 10; x++) + cout << ms_rnd.rnd() << endl; + cout << endl << "BSD RAND:" << endl << "=========" << endl; + for (int x = 0; x < 10; x++) + cout << bsd_rnd.rnd() << endl; + return 0; +} + +/* +MS RAND: +======== +38 +7719 +21238 +2437 +8855 +11797 +8365 +32285 +10450 +30612 + +BSD RAND: +========= +12345 +1406932606 +654583775 +1449466924 +229283573 +1109335178 +1051550459 +1293799192 +794471793 +551188310 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range.cpp b/c++/Numerical_Problems/C++ Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range.cpp new file mode 100644 index 0000000..dd68031 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range.cpp @@ -0,0 +1,84 @@ +/*This is a C++ Program to find prime number between a given range using Wheel Seive method. Wheel factorization is a graphical method for manually performing a preliminary to the Sieve of Eratosthenes that separates prime numbers from composites. Start by writing the natural numbers around circles as shown below. Prime numbers in the innermost circle have their multiples in similar positions as themselves in the other circles, forming spokes of primes and their multiples. Multiples of the prime numbers in the innermost circle form spokes of composite numbers in the outer circles.*/ + +#include +#include +#include + +using namespace std; + +#define MAX_NUM 50 +// array will be initialized to 0 being global +int primes[MAX_NUM]; + +void gen_sieve_primes(void) +{ + for (int p = 2; p < MAX_NUM; p++) // for all elements in array + { + if (primes[p] == 0) // it is not multiple of any other prime + primes[p] = 1; // mark it as prime + // mark all multiples of prime selected above as non primes + int c = 2; + int mul = p * c; + for (; mul < MAX_NUM;) + { + primes[mul] = -1; + c++; + mul = p * c; + } + } +} + +void print_all_primes() +{ + int c = 0; + for (int i = 0; i < MAX_NUM; i++) + { + if (primes[i] == 1) + { + c++; + if (c < 4) + { + switch (c) + { + case 1: + cout << c << "st prime is: " << i << endl; + break; + case 2: + cout << c << "nd prime is: " << i << endl; + break; + case 3: + cout << c << "rd prime is: " << i << endl; + break; + default: + break; + } + } + else + cout << c << "th prime is: " << i << endl; + } + } +} + +int main() +{ + gen_sieve_primes(); + print_all_primes(); + return 0; +} + +/* +1st prime is: 2 +2nd prime is: 3 +3rd prime is: 5 +4th prime is: 7 +5th prime is: 11 +6th prime is: 13 +7th prime is: 17 +8th prime is: 19 +9th prime is: 23 +10th prime is: 29 +11th prime is: 31 +12th prime is: 37 +13th prime is: 41 +14th prime is: 43 +15th prime is: 47 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Optimize Wire Length in Electrical Circuit.cpp b/c++/Numerical_Problems/C++ Program to Optimize Wire Length in Electrical Circuit.cpp new file mode 100644 index 0000000..56b3fc9 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Optimize Wire Length in Electrical Circuit.cpp @@ -0,0 +1,113 @@ +#include +#include +#include + +using namespace std; + +// Number of components in the graph +#define V 9 + +// A utility function to find the component with minimum distance value, from +// the set of components not yet included in shortest path tree +int minDistance(int dist[], bool sptSet[]) +{ + // Initialize min value + int min = INT_MAX, min_index; + for (int v = 0; v < V; v++) + if (sptSet[v] == false && dist[v] <= min) + min = dist[v], min_index = v; + return min_index; +} + +// A utility function to print the constructed distance array +void printSolution(int dist[], int n) +{ + cout << "Component\tDistance from other component\n"; + for (int i = 0; i < V; i++) + printf("%d\t\t%d\n", i, dist[i]); +} + +// Funtion that implements Dijkstra's single source shortest path algorithm +// for a graph represented using adjacency matrix representation +void optimizeLength(int graph[V][V], int src) +{ + int dist[V]; // The output array. dist[i] will hold the shortest + // distance from src to i + bool sptSet[V]; // sptSet[i] will true if component i is included in shortest + // path tree or shortest distance from src to i is finalized + // Initialize all distances as INFINITE and stpSet[] as false + for (int i = 0; i < V; i++) + dist[i] = INT_MAX, sptSet[i] = false; + // Distance of source component from itself is always 0 + dist[src] = 0; + // Find shortest path for all components + for (int count = 0; count < V - 1; count++) + { + // Pick the minimum distance component from the set of components not + // yet processed. u is always equal to src in first iteration. + int u = minDistance(dist, sptSet); + // Mark the picked component as processed + sptSet[u] = true; + // Update dist value of the adjacent components of the picked component. + for (int v = 0; v < V; v++) + // Update dist[v] only if is not in sptSet, there is an edge from + // u to v, and total weight of path from src to v through u is + // smaller than current value of dist[v] + if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + + graph[u][v] < dist[v]) + dist[v] = dist[u] + graph[u][v]; + } + // print the constructed distance array + printSolution(dist, V); +} + +// driver program to test above function +int main() +{ + /* Let us create the example graph discussed above */ + int graph[V][V] = + { + { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { + 0, 8, 0, 7, 0, 4, 0, 0, 2 + }, + { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { + 0, 0, 0, 9, 0, 10, 0, 0, + 0 + }, { 0, 0, 4, 0, 10, 0, 2, 0, 0 }, { + 0, 0, 0, 14, + 0, 2, 0, 1, 6 + }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { + 0, 0, 2, 0, 0, 0, 6, 7, 0 + } + }; + cout << "Enter the starting component: "; + int s; + cin >> s; + optimizeLength(graph, s); + return 0; +} + +/* +Enter the starting component: 1 +Component Distance from other component +0 4 +1 0 +2 8 +3 15 +4 22 +5 12 +6 12 +7 11 +8 10 + +Enter the starting component: 6 +Component Distance from other component +0 9 +1 12 +2 6 +3 13 +4 12 +5 2 +6 0 +7 1 +8 6 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Perform Addition Operation Using Bitwise Operators.cpp b/c++/Numerical_Problems/C++ Program to Perform Addition Operation Using Bitwise Operators.cpp new file mode 100644 index 0000000..fbd98e7 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Perform Addition Operation Using Bitwise Operators.cpp @@ -0,0 +1,27 @@ +#include +#include +#include + +using namespace std; +int add(int x, int y) +{ + int carry; + while (y != 0) + { + carry = x & y; + x = x ^ y; + y = carry << 1; + } + return x; +} +int main(int argc, char **argv) +{ + cout << "Enter the numbers to be added:"; + int x, y; + cin >> x >> y; + cout << "The Summation is: " << add(x, y); +} + +/* +Enter the numbers to be added:23 24 +The Summation is: 47 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Perform Encoding of a Message Using Matrix Multiplication.cpp b/c++/Numerical_Problems/C++ Program to Perform Encoding of a Message Using Matrix Multiplication.cpp new file mode 100644 index 0000000..8ea6a37 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Perform Encoding of a Message Using Matrix Multiplication.cpp @@ -0,0 +1,77 @@ +#include +#include +using namespace std; +int main() +{ + int a[10][10], b[10][10], c[10][10]; + int x, y, i, j; + cout << "\nEnter the number of rows and columns for Message Matrix:\n\n"; + cin >> x >> y; + // x denotes number rows in matrix A + // y denotes number columns in matrix A + cout << "\n\nEnter elements for Matrix :::\n\n"; + for (i = 0; i < x; i++) + { + for (j = 0; j < y; j++) + { + cin >> a[i][j]; + } + cout << "\n"; + } + cout << "\n\nMatrix :\n\n"; + for (i = 0; i < x; i++) + { + for (j = 0; j < y; j++) + { + cout << "\t" << a[i][j]; + } + cout << "\n\n"; + } + for (i = 0; i < y; i++) + { + for (j = 0; j < x; j++) + { + b[i][j]=x+y; + } + cout << "\n"; + } + for (i = 0; i < x; i++) + { + for (j = 0; j < x; j++) + { + c[i][j] = 0; + for (int k = 0; k < y; k++) + { + c[i][j] = c[i][j] + a[i][k] * b[k][j]; + } + } + } + cout + << "\n-----------------------------------------------------------\n"; + cout << "\n\nEncoded Matrix :\n\n"; + for (i = 0; i < x; i++) + { + for (j = 0; j < x; j++) + { + cout << "\t" << c[i][j]; + } + cout << "\n\n"; + } + getch(); + return 0; +} + +/* +Enter the number of rows and columns for Message Matrix: +2 2 + +Enter elements for Matrix ::: +1 2 +3 4 +Matrix : + 1 2 + 3 4 +----------------------------------------------------------- +Encoded Matrix : + 12 12 + 28 28 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Perform LU Decomposition of any Matrix.cpp b/c++/Numerical_Problems/C++ Program to Perform LU Decomposition of any Matrix.cpp new file mode 100644 index 0000000..1b64da6 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Perform LU Decomposition of any Matrix.cpp @@ -0,0 +1,103 @@ +/* +This is a C++ Program to perform LU Decomposition of any matrix. In numerical analysis, LU decomposition (where ‘LU’ stands for ‘Lower Upper’, and also called LU factorization) factors a matrix as the product of a lower triangular matrix and an upper triangular matrix. The product sometimes includes a permutation matrix as well. The LU decomposition can be viewed as the matrix form of Gaussian elimination. Computers usually solve square systems of linear equations using the LU decomposition, and it is also a key step when inverting a matrix, or computing the determinant of a matrix +*/ + +#include +#include + +using namespace std; + +int main(int argc, char **argv) +{ + void lu(float[][10], float[][10], float[][10], int n); + void output(float[][10], int); + float a[10][10], l[10][10], u[10][10]; + int n = 0, i = 0, j = 0; + cout << "Enter size of 2d array(Square matrix) : "; + cin >> n; + for (i = 0; i < n; i++) + { + for (j = 0; j < n; j++) + { + cout << "Enter values no:" << i << ", " << j << ": "; + cin >> a[i][j]; + } + } + lu(a, l, u, n); + cout << "\nL Decomposition\n\n"; + output(l, n); + cout << "\nU Decomposition\n\n"; + output(u, n); + return 0; +} +void lu(float a[][10], float l[][10], float u[][10], int n) +{ + int i = 0, j = 0, k = 0; + for (i = 0; i < n; i++) + { + for (j = 0; j < n; j++) + { + if (j < i) + l[j][i] = 0; + else + { + l[j][i] = a[j][i]; + for (k = 0; k < i; k++) + { + l[j][i] = l[j][i] - l[j][k] * u[k][i]; + } + } + } + for (j = 0; j < n; j++) + { + if (j < i) + u[i][j] = 0; + else if (j == i) + u[i][j] = 1; + else + { + u[i][j] = a[i][j] / l[i][i]; + for (k = 0; k < i; k++) + { + u[i][j] = u[i][j] - ((l[i][k] * u[k][j]) / l[i][i]); + } + } + } + } +} +void output(float x[][10], int n) +{ + int i = 0, j = 0; + for (i = 0; i < n; i++) + { + for (j = 0; j < n; j++) + { + printf("%f ", x[i][j]); + } + cout << "\n"; + } +} + +/* +Enter size of 2d array(Square matrix) : 3 +Enter values no:0, 0: 1 +Enter values no:0, 1: 1 +Enter values no:0, 2: -1 +Enter values no:1, 0: 2 +Enter values no:1, 1: -1 +Enter values no:1, 2: 3 +Enter values no:2, 0: 3 +Enter values no:2, 1: 1 +Enter values no:2, 2: -1 + +L Decomposition + +1.000000 0.000000 0.000000 +2.000000 -3.000000 0.000000 +3.000000 -2.000000 -1.333333 + +U Decomposition + +1.000000 1.000000 -1.000000 +0.000000 1.000000 -1.666667 +0.000000 0.000000 1.000000 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Perform Matrix Multiplication.cpp b/c++/Numerical_Problems/C++ Program to Perform Matrix Multiplication.cpp new file mode 100644 index 0000000..91767f7 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Perform Matrix Multiplication.cpp @@ -0,0 +1,112 @@ +#include +#include +using namespace std; +int main() +{ + int a[10][10], b[10][10], c[10][10]; + int x, y, i, j, m, n; + cout << "\nEnter the number of rows and columns for Matrix A:::\n\n"; + cin >> x >> y; + // x denotes number rows in matrix A + // y denotes number columns in matrix A + cout << "\n\nEnter elements for Matrix A :::\n\n"; + for (i = 0; i < x; i++) + { + for (j = 0; j < y; j++) + { + cin >> a[i][j]; + } + cout << "\n"; + } + cout << "\n\nMatrix A :\n\n"; + for (i = 0; i < x; i++) + { + for (j = 0; j < y; j++) + { + cout << "\t" << a[i][j]; + } + cout << "\n\n"; + } + cout << "\n-----------------------------------------------------------\n"; + cout << "\nEnter the number of rows and columns for Matrix B:::\n\n"; + cin >> m >> n; + // m denotes number rows in matrix B + // n denotes number columns in matrix B + cout << "\n\nEnter elements for Matrix B :::\n\n"; + for (i = 0; i < m; i++) + { + for (j = 0; j < n; j++) + { + cin >> b[i][j]; + } + cout << "\n"; + } + cout << "\n\nMatrix B :\n\n"; + for (i = 0; i < m; i++) + { + for (j = 0; j < n; j++) + { + cout << "\t" << b[i][j]; + } + cout << "\n\n"; + } + if (y == m) + { + for (i = 0; i < x; i++) + { + for (j = 0; j < n; j++) + { + c[i][j] = 0; + for (int k = 0; k < m; k++) + { + c[i][j] = c[i][j] + a[i][k] * b[k][j]; + } + } + } + cout + << "\n-----------------------------------------------------------\n"; + cout << "\n\nMultiplication of Matrix A and Matrix B :\n\n"; + for (i = 0; i < x; i++) + { + for (j = 0; j < n; j++) + { + cout << "\t" << c[i][j]; + } + cout << "\n\n"; + } + } + else + { + cout << "\n\nMultiplication is not possible"; + } + getch(); + return 0; +} + +/* +Enter the number of rows and columns for Matrix A::: +2 2 + +Enter elements for Matrix A ::: +1 2 +3 4 + +Matrix A : + 1 2 + 3 4 +----------------------------------------------------------- +Enter the number of rows and columns for Matrix B::: +2 2 + +Enter elements for Matrix B ::: +4 5 +6 7 + +Matrix B : + 4 5 + 6 7 +----------------------------------------------------------- + +Multiplication of Matrix A and Matrix B : + 16 19 + 36 43 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Perform Optimal Paranthesization Using Dynamic Programming.cpp b/c++/Numerical_Problems/C++ Program to Perform Optimal Paranthesization Using Dynamic Programming.cpp new file mode 100644 index 0000000..52ff259 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Perform Optimal Paranthesization Using Dynamic Programming.cpp @@ -0,0 +1,65 @@ +#include +#include +#include + +using namespace std; + +// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n + +int MatrixChainOrder(int p[], int n) +{ + /* For simplicity of the program, one extra row and one extra column are + allocated in m[][]. 0th row and 0th column of m[][] are not used */ + int m[n][n]; + int s[n][n]; + int i, j, k, L, q; + /* m[i,j] = Minimum number of scalar multiplications needed to compute + the matrix A[i]A[i+1]...A[j] = A[i..j] where dimention of A[i] is + p[i-1] x p[i] */ + // cost is zero when multiplying one matrix. + for (i = 1; i < n; i++) + m[i][i] = 0; + // L is chain length. + for (L = 2; L < n; L++) + { + for (i = 1; i <= n - L + 1; i++) + { + j = i + L - 1; + m[i][j] = INT_MAX; + for (k = i; k <= j - 1; k++) + { + // q = cost/scalar multiplications + q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; + if (q < m[i][j]) + { + m[i][j] = q; + s[i][j] = k; + } + } + } + } + return m[1][n - 1]; +} +int main() +{ + cout + << "Enter the array p[], which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]"; + cout << "Enter the total length:"; + int n; + cin >> n; + int array[n]; + cout << "Enter the dimensions: "; + for (int var = 0; var < n; ++var) + { + cin >> array[var]; + } + cout << "Minimum number of multiplications is: " << MatrixChainOrder(array, + n); + return 0; +} + +/* + +Enter the array p[], which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]Enter the total length:4 +Enter the dimensions: 2 4 3 5 +Minimum number of multiplications is: 54 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Perform Partition of an Integer in All Possible Ways.cpp b/c++/Numerical_Problems/C++ Program to Perform Partition of an Integer in All Possible Ways.cpp new file mode 100644 index 0000000..bcb04bb --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Perform Partition of an Integer in All Possible Ways.cpp @@ -0,0 +1,80 @@ +#include +using namespace std; + +// A utility function to print an array p[] of size 'n' +void printArray(int p[], int n) +{ + for (int i = 0; i < n; i++) + cout << p[i] << " "; + cout << endl; +} + +void printAllUniqueParts(int n) +{ + int p[n]; // An array to store a partition + int k = 0; // Index of last element in a partition + p[k] = n; // Initialize first partition as number itself + // This loop first prints current partition, then generates next + // partition. The loop stops when the current partition has all 1s + while (true) + { + // print current partition + printArray(p, k + 1); + // Generate next partition + // Find the rightmost non-one value in p[]. Also, update the + // rem_val so that we know how much value can be accommodated + int rem_val = 0; + while (k >= 0 && p[k] == 1) + { + rem_val += p[k]; + k--; + } + // if k < 0, all the values are 1 so there are no more partitions + if (k < 0) + return; + // Decrease the p[k] found above and adjust the rem_val + p[k]--; + rem_val++; + // If rem_val is more, then the sorted order is violeted. Divide + // rem_val in differnt values of size p[k] and copy these values at + // different positions after p[k] + while (rem_val > p[k]) + { + p[k + 1] = p[k]; + rem_val = rem_val - p[k]; + k++; + } + // Copy rem_val to next position and increment position + p[k + 1] = rem_val; + k++; + } +} + +// Driver program to test above functions +int main() +{ + cout << "All Unique Partitions of 2 \n"; + printAllUniqueParts(2); + cout << "\nAll Unique Partitions of 3 \n"; + printAllUniqueParts(3); + cout << "\nAll Unique Partitions of 4 \n"; + printAllUniqueParts(4); + return 0; +} + +/* +All Unique Partitions of 2 +2 +1 1 + +All Unique Partitions of 3 +3 +2 1 +1 1 1 + +All Unique Partitions of 4 +4 +3 1 +2 2 +2 1 1 +1 1 1 1 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Perform the Unique Factorization of a Given Number.cpp b/c++/Numerical_Problems/C++ Program to Perform the Unique Factorization of a Given Number.cpp new file mode 100644 index 0000000..9c998a3 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Perform the Unique Factorization of a Given Number.cpp @@ -0,0 +1,81 @@ +#include +using namespace std; + +// A utility function to print an array p[] of size 'n' +void printArray(int p[], int n) +{ + for (int i = 0; i < n; i++) + cout << p[i] << " "; + cout << endl; +} + +void printAllUniqueParts(int n) +{ + int p[n]; // An array to store a partition + int k = 0; // Index of last element in a partition + p[k] = n; // Initialize first partition as number itself + // This loop first prints current partition, then generates next + // partition. The loop stops when the current partition has all 1s + while (true) + { + // print current partition + printArray(p, k + 1); + // Generate next partition + // Find the rightmost non-one value in p[]. Also, update the + // rem_val so that we know how much value can be accommodated + int rem_val = 0; + while (k >= 0 && p[k] == 1) + { + rem_val += p[k]; + k--; + } + // if k < 0, all the values are 1 so there are no more partitions + if (k < 0) + return; + // Decrease the p[k] found above and adjust the rem_val + p[k]--; + rem_val++; + // If rem_val is more, then the sorted order is violeted. Divide + // rem_val in differnt values of size p[k] and copy these values at + // different positions after p[k] + while (rem_val > p[k]) + { + p[k + 1] = p[k]; + rem_val = rem_val - p[k]; + k++; + } + // Copy rem_val to next position and increment position + p[k + 1] = rem_val; + k++; + } +} + +// Driver program to test above functions +int main() +{ + cout << "All Unique Partitions of 2 \n"; + printAllUniqueParts(2); + cout << "\nAll Unique Partitions of 3 \n"; + printAllUniqueParts(3); + cout << "\nAll Unique Partitions of 4 \n"; + printAllUniqueParts(4); + return 0; +} + +/* + +All Unique Partitions of 2 +2 +1 1 + +All Unique Partitions of 3 +3 +2 1 +1 1 1 + +All Unique Partitions of 4 +4 +3 1 +2 2 +2 1 1 +1 1 1 1 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Represent Linear Equations in Matrix Form.cpp b/c++/Numerical_Problems/C++ Program to Represent Linear Equations in Matrix Form.cpp new file mode 100644 index 0000000..3000509 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Represent Linear Equations in Matrix Form.cpp @@ -0,0 +1,49 @@ +#include +#include + +using namespace std; + +int main(void) +{ + char var[] = { 'x', 'y', 'z', 'w' }; + cout << "Enter the number of variables in the equations: "; + int n; + cin >> n; + cout << "\nEnter the coefficients of each variable for each equations"; + cout << "\nax + by + cz + ... = d"; + int mat[n][n]; + int constants[n][1]; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cin >> mat[i][j]; + } + cin >> constants[i][0]; + } + cout << "Matrix representation is: "; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cout << " " << mat[i][j]; + } + cout << " " << var[i]; + cout << " = " << constants[i][0]; + cout << "\n"; + } + return 0; +} + +/* +Enter the number of variables in the equations: 3 + +Enter the coefficients of each variable for each equations +ax + by + cz + ... = d +1 2 3 4 +1 2 6 8 +2 3 9 8 +Matrix representation is: + 1 2 3 x = 4 + 1 2 6 y = 8 + 2 3 9 z = 8 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Solve Knapsack Problem Using Dynamic Programming.cpp b/c++/Numerical_Problems/C++ Program to Solve Knapsack Problem Using Dynamic Programming.cpp new file mode 100644 index 0000000..a6171e2 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Solve Knapsack Problem Using Dynamic Programming.cpp @@ -0,0 +1,65 @@ +/*This is a C++ Program to knapsack problem using dynamic programming. The knapsack problem or rucksack problem is a problem in combinatorial optimization: Given a set of items, each with a mass and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most valuable items.*/ + +// A Dynamic Programming based solution for 0-1 Knapsack problem +#include + +using namespace std; + +// A utility function that returns maximum of two integers +int max(int a, int b) +{ + return (a > b) ? a : b; +} + +// Returns the maximum value that can be put in a knapsack of capacity W +int knapSack(int W, int wt[], int val[], int n) +{ + int i, w; + int K[n + 1][W + 1]; + // Build table K[][] in bottom up manner + for (i = 0; i <= n; i++) + { + for (w = 0; w <= W; w++) + { + if (i == 0 || w == 0) + K[i][w] = 0; + else if (wt[i - 1] <= w) + K[i][w] + = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); + else + K[i][w] = K[i - 1][w]; + } + } + return K[n][W]; +} + +int main() +{ + cout << "Enter the number of items in a Knapsack:"; + int n, W; + cin >> n; + int val[n], wt[n]; + for (int i = 0; i < n; i++) + { + cout << "Enter value and weight for item " << i << ":"; + cin >> val[i]; + cin >> wt[i]; + } + // int val[] = { 60, 100, 120 }; + // int wt[] = { 10, 20, 30 }; + // int W = 50; + cout << "Enter the capacity of knapsack"; + cin >> W; + cout << knapSack(W, wt, val, n); + return 0; +} + +/* +Enter the number of items in a Knapsack:5 +Enter value and weight for item 0:11 111 +Enter value and weight for item 1:22 121 +Enter value and weight for item 2:33 131 +Enter value and weight for item 3:44 141 +Enter value and weight for item 4:55 151 +Enter the capacity of knapsack 300 +99 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Solve any Linear Equation in One Variable.cpp b/c++/Numerical_Problems/C++ Program to Solve any Linear Equation in One Variable.cpp new file mode 100644 index 0000000..edc65a7 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Solve any Linear Equation in One Variable.cpp @@ -0,0 +1,647 @@ +#if !defined(MATRIX_H) +#define MATRIX_H +#include +#include +#include +#include +#include + +class CMatrix +{ +private: + int m_rows; + int m_cols; + char m_name[128]; + CMatrix(); +public: + double **m_pData; + CMatrix(const char *name, int rows, int cols) : + m_rows(rows), m_cols(cols) + { + strcpy(m_name, name); + m_pData = new double*[m_rows]; + for (int i = 0; i < m_rows; i++) + m_pData[i] = new double[m_cols]; + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + m_pData[i][j] = 0.0; + } + } + } + CMatrix(const CMatrix &other) + { + strcpy(m_name, other.m_name); + m_rows = other.m_rows; + m_cols = other.m_cols; + m_pData = new double*[m_rows]; + for (int i = 0; i < m_rows; i++) + m_pData[i] = new double[m_cols]; + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + m_pData[i][j] = other.m_pData[i][j]; + } + } + } + ~CMatrix() + { + for (int i = 0; i < m_rows; i++) + delete[] m_pData[i]; + delete[] m_pData; + m_rows = m_cols = 0; + } + void SetName(const char *name) + { + strcpy(m_name, name); + } + const char* GetName() const + { + return m_name; + } + void GetInput() + { + std::cin >> *this; + } + void FillSimulatedInput() + { + static int factor1 = 1, factor2 = 2; + std::cout << "\n\nEnter Input For Matrix : " << m_name << " Rows: " + << m_rows << " Cols: " << m_cols << "\n"; + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + std::cout << "Input For Row: " << i + 1 << " Col: " << j + + 1 << " = "; + int data = ((i + 1) * factor1) + (j + 1) * factor2; + m_pData[i][j] = data / 10.2; + std::cout << m_pData[i][j] << "\n"; + factor1 += (rand() % 4); + factor2 += (rand() % 3); + } + std::cout << "\n"; + } + std::cout << "\n"; + } + double Determinant() + { + double det = 0; + double **pd = m_pData; + switch (m_rows) + { + case 2: + { + det = pd[0][0] * pd[1][1] - pd[0][1] * pd[1][0]; + return det; + } + break; + case 3: + { + /*** + a b c + d e f + g h i + + a b c a b c + d e f d e f + g h i g h i + + + // det (A) = aei + bfg + cdh - afh - bdi - ceg. + ***/ + double a = pd[0][0]; + double b = pd[0][1]; + double c = pd[0][2]; + double d = pd[1][0]; + double e = pd[1][1]; + double f = pd[1][2]; + double g = pd[2][0]; + double h = pd[2][1]; + double i = pd[2][2]; + double det = (a * e * i + b * f * g + c * d * h); // - a*f*h - b*d*i - c*e*g); + det = det - a * f * h; + det = det - b * d * i; + det = det - c * e * g; + //std::cout << *this; + //std::cout << "deter: " << det << " \n"; + return det; + } + break; + case 4: + { + CMatrix *temp[4]; + for (int i = 0; i < 4; i++) + temp[i] = new CMatrix("", 3, 3); + for (int k = 0; k < 4; k++) + { + for (int i = 1; i < 4; i++) + { + int j1 = 0; + for (int j = 0; j < 4; j++) + { + if (k == j) + continue; + temp[k]->m_pData[i - 1][j1++] + = this->m_pData[i][j]; + } + } + } + double det = this->m_pData[0][0] * temp[0]->Determinant() + - this->m_pData[0][1] * temp[1]->Determinant() + + this->m_pData[0][2] * temp[2]->Determinant() + - this->m_pData[0][3] * temp[3]->Determinant(); + return det; + } + break; + case 5: + { + CMatrix *temp[5]; + for (int i = 0; i < 5; i++) + temp[i] = new CMatrix("", 4, 4); + for (int k = 0; k < 5; k++) + { + for (int i = 1; i < 5; i++) + { + int j1 = 0; + for (int j = 0; j < 5; j++) + { + if (k == j) + continue; + temp[k]->m_pData[i - 1][j1++] + = this->m_pData[i][j]; + } + } + } + double det = this->m_pData[0][0] * temp[0]->Determinant() + - this->m_pData[0][1] * temp[1]->Determinant() + + this->m_pData[0][2] * temp[2]->Determinant() + - this->m_pData[0][3] * temp[3]->Determinant() + + this->m_pData[0][4] * temp[4]->Determinant(); + return det; + } + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + default: + { + int DIM = m_rows; + CMatrix **temp = new CMatrix*[DIM]; + for (int i = 0; i < DIM; i++) + temp[i] = new CMatrix("", DIM - 1, DIM - 1); + for (int k = 0; k < DIM; k++) + { + for (int i = 1; i < DIM; i++) + { + int j1 = 0; + for (int j = 0; j < DIM; j++) + { + if (k == j) + continue; + temp[k]->m_pData[i - 1][j1++] + = this->m_pData[i][j]; + } + } + } + double det = 0; + for (int k = 0; k < DIM; k++) + { + if ((k % 2) == 0) + det = det + (this->m_pData[0][k] + * temp[k]->Determinant()); + else + det = det - (this->m_pData[0][k] + * temp[k]->Determinant()); + } + for (int i = 0; i < DIM; i++) + delete temp[i]; + delete[] temp; + return det; + } + break; + } + } + CMatrix& operator =(const CMatrix &other) + { + if (this->m_rows != other.m_rows || this->m_cols != other.m_cols) + { + std::cout + << "WARNING: Assignment is taking place with by changing the number of rows and columns of the matrix"; + } + for (int i = 0; i < m_rows; i++) + delete[] m_pData[i]; + delete[] m_pData; + m_rows = m_cols = 0; + strcpy(m_name, other.m_name); + m_rows = other.m_rows; + m_cols = other.m_cols; + m_pData = new double*[m_rows]; + for (int i = 0; i < m_rows; i++) + m_pData[i] = new double[m_cols]; + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + m_pData[i][j] = other.m_pData[i][j]; + } + } + return *this; + } + CMatrix CoFactor() + { + CMatrix cofactor("COF", m_rows, m_cols); + if (m_rows != m_cols) + return cofactor; + if (m_rows < 2) + return cofactor; + else if (m_rows == 2) + { + cofactor.m_pData[0][0] = m_pData[1][1]; + cofactor.m_pData[0][1] = -m_pData[1][0]; + cofactor.m_pData[1][0] = -m_pData[0][1]; + cofactor.m_pData[1][1] = m_pData[0][0]; + return cofactor; + } + else if (m_rows >= 3) + { + int DIM = m_rows; + CMatrix ***temp = new CMatrix**[DIM]; + for (int i = 0; i < DIM; i++) + temp[i] = new CMatrix*[DIM]; + for (int i = 0; i < DIM; i++) + for (int j = 0; j < DIM; j++) + temp[i][j] = new CMatrix("", DIM - 1, DIM - 1); + for (int k1 = 0; k1 < DIM; k1++) + { + for (int k2 = 0; k2 < DIM; k2++) + { + int i1 = 0; + for (int i = 0; i < DIM; i++) + { + int j1 = 0; + for (int j = 0; j < DIM; j++) + { + if (k1 == i || k2 == j) + continue; + temp[k1][k2]->m_pData[i1][j1++] + = this->m_pData[i][j]; + } + if (k1 != i) + i1++; + } + } + } + bool flagPositive = true; + for (int k1 = 0; k1 < DIM; k1++) + { + flagPositive = ((k1 % 2) == 0); + for (int k2 = 0; k2 < DIM; k2++) + { + if (flagPositive == true) + { + cofactor.m_pData[k1][k2] + = temp[k1][k2]->Determinant(); + flagPositive = false; + } + else + { + cofactor.m_pData[k1][k2] + = -temp[k1][k2]->Determinant(); + flagPositive = true; + } + } + } + for (int i = 0; i < DIM; i++) + for (int j = 0; j < DIM; j++) + delete temp[i][j]; + for (int i = 0; i < DIM; i++) + delete[] temp[i]; + delete[] temp; + } + return cofactor; + } + CMatrix Adjoint() + { + CMatrix cofactor("COF", m_rows, m_cols); + CMatrix adj("ADJ", m_rows, m_cols); + if (m_rows != m_cols) + return adj; + cofactor = this->CoFactor(); + // adjoint is transpose of a cofactor of a matrix + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + adj.m_pData[j][i] = cofactor.m_pData[i][j]; + } + } + return adj; + } + CMatrix Transpose() + { + CMatrix trans("TR", m_cols, m_rows); + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + trans.m_pData[j][i] = m_pData[i][j]; + } + } + return trans; + } + CMatrix Inverse() + { + CMatrix cofactor("COF", m_rows, m_cols); + CMatrix inv("INV", m_rows, m_cols); + if (m_rows != m_cols) + return inv; + // to find out Determinant + double det = Determinant(); + cofactor = this->CoFactor(); + // inv = transpose of cofactor / Determinant + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + inv.m_pData[j][i] = cofactor.m_pData[i][j] / det; + } + } + return inv; + } + CMatrix operator +(const CMatrix &other) + { + if (this->m_rows != other.m_rows || this->m_cols != other.m_cols) + { + std::cout + << "Addition could not take place because number of rows and columns are different between the two matrices"; + return *this; + } + CMatrix result("", m_rows, m_cols); + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + result.m_pData[i][j] = this->m_pData[i][j] + + other.m_pData[i][j]; + } + } + return result; + } + CMatrix operator -(const CMatrix &other) + { + if (this->m_rows != other.m_rows || this->m_cols != other.m_cols) + { + std::cout + << "Subtraction could not take place because number of rows and columns are different between the two matrices"; + return *this; + } + CMatrix result("", m_rows, m_cols); + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + result.m_pData[i][j] = this->m_pData[i][j] + - other.m_pData[i][j]; + } + } + return result; + } + CMatrix operator *(const CMatrix &other) + { + if (this->m_cols != other.m_rows) + { + std::cout + << "Multiplication could not take place because number of columns of 1st Matrix and number of rows in 2nd Matrix are different"; + return *this; + } + CMatrix result("", this->m_rows, other.m_cols); + for (int i = 0; i < this->m_rows; i++) + { + for (int j = 0; j < other.m_cols; j++) + { + for (int k = 0; k < this->m_cols; k++) + { + result.m_pData[i][j] += this->m_pData[i][k] + * other.m_pData[k][j]; + } + } + } + return result; + } + bool operator ==(const CMatrix &other) + { + if (this->m_rows != other.m_rows || this->m_cols != other.m_cols) + { + std::cout + << "Comparision could not take place because number of rows and columns are different between the two matrices"; + return false; + } + CMatrix result("", m_rows, m_cols); + bool bEqual = true; + for (int i = 0; i < m_rows; i++) + { + for (int j = 0; j < m_cols; j++) + { + if (this->m_pData[i][j] != other.m_pData[i][j]) + bEqual = false; + } + } + return bEqual; + } + friend std::istream& operator >>(std::istream &is, CMatrix &m); + friend std::ostream& operator <<(std::ostream &os, const CMatrix &m); +}; +std::istream& operator >>(std::istream &is, CMatrix &m) +{ + std::cout << "\n\nEnter Input For Matrix : " << m.m_name << " Rows: " + << m.m_rows << " Cols: " << m.m_cols << "\n"; + for (int i = 0; i < m.m_rows; i++) + { + for (int j = 0; j < m.m_cols; j++) + { + std::cout << "Input For Row: " << i + 1 << " Col: " << j + 1 + << " = "; + is >> m.m_pData[i][j]; + } + std::cout << "\n"; + } + std::cout << "\n"; + return is; +} +std::ostream& operator <<(std::ostream &os, const CMatrix &m) +{ + os << "\n\nMatrix : " << m.m_name << " Rows: " << m.m_rows << " Cols: " + << m.m_cols << "\n\n"; + for (int i = 0; i < m.m_rows; i++) + { + os << " | "; + for (int j = 0; j < m.m_cols; j++) + { + char buf[32]; + double data = m.m_pData[i][j]; + if (m.m_pData[i][j] > -0.00001 && m.m_pData[i][j] < 0.00001) + data = 0; + sprintf(buf, "%10.2lf ", data); + os << buf; + } + os << "|\n"; + } + os << "\n\n"; + return os; +} +#endif +int main() +{ + CMatrix a("A", 6, 6); + CMatrix b("B", 6, 1); + a.FillSimulatedInput(); + b.FillSimulatedInput(); + std::cout << a << "\n Determinant : "; + std::cout << a.Determinant() << "\n"; + std::cout << b << "\n Determinant : "; + std::cout << b.Determinant() << "\n"; + CMatrix ainv = a.Inverse(); + CMatrix q = a * ainv; + q.SetName("A * A'"); + std::cout << q << "\n"; + CMatrix x = ainv * b; + x.SetName("X"); + std::cout << x << "\n"; + CMatrix y = a * x; // we will get B + y.SetName("Y"); + std::cout << y << "\n"; + return 0; +} + +/* + +Enter Input For Matrix : A Rows: 6 Cols: 6 +Input For Row: 1 Col: 1 = 0.294118 +Input For Row: 1 Col: 2 = 0.980392 +Input For Row: 1 Col: 3 = 1.86275 +Input For Row: 1 Col: 4 = 2.84314 +Input For Row: 1 Col: 5 = 3.62745 +Input For Row: 1 Col: 6 = 5.58824 + +Input For Row: 2 Col: 1 = 2.94118 +Input For Row: 2 Col: 2 = 4.11765 +Input For Row: 2 Col: 3 = 5.88235 +Input For Row: 2 Col: 4 = 8.43137 +Input For Row: 2 Col: 5 = 10.3922 +Input For Row: 2 Col: 6 = 12.3529 + +Input For Row: 3 Col: 1 = 8.13725 +Input For Row: 3 Col: 2 = 9.70588 +Input For Row: 3 Col: 3 = 12.0588 +Input For Row: 3 Col: 4 = 15.098 +Input For Row: 3 Col: 5 = 17.8431 +Input For Row: 3 Col: 6 = 20.5882 + +Input For Row: 4 Col: 1 = 14.902 +Input For Row: 4 Col: 2 = 18.2353 +Input For Row: 4 Col: 3 = 21.4706 +Input For Row: 4 Col: 4 = 24.7059 +Input For Row: 4 Col: 5 = 27.549 +Input For Row: 4 Col: 6 = 31.1765 + +Input For Row: 5 Col: 1 = 24.902 +Input For Row: 5 Col: 2 = 27.9412 +Input For Row: 5 Col: 3 = 32.451 +Input For Row: 5 Col: 4 = 36.0784 +Input For Row: 5 Col: 5 = 39.7059 +Input For Row: 5 Col: 6 = 43.9216 + +Input For Row: 6 Col: 1 = 36.3725 +Input For Row: 6 Col: 2 = 39.6078 +Input For Row: 6 Col: 3 = 43.8235 +Input For Row: 6 Col: 4 = 47.2549 +Input For Row: 6 Col: 5 = 51.3725 +Input For Row: 6 Col: 6 = 55.2941 + + + + +Enter Input For Matrix : B Rows: 6 Cols: 1 +Input For Row: 1 Col: 1 = 9.41176 + +Input For Row: 2 Col: 1 = 15.7843 + +Input For Row: 3 Col: 1 = 22.7451 + +Input For Row: 4 Col: 1 = 29.902 + +Input For Row: 5 Col: 1 = 37.1569 + +Input For Row: 6 Col: 1 = 44.6078 + + + + +Matrix : A Rows: 6 Cols: 6 + + | 0.29 0.98 1.86 2.84 3.63 5.59 | + | 2.94 4.12 5.88 8.43 10.39 12.35 | + | 8.14 9.71 12.06 15.10 17.84 20.59 | + | 14.90 18.24 21.47 24.71 27.55 31.18 | + | 24.90 27.94 32.45 36.08 39.71 43.92 | + | 36.37 39.61 43.82 47.25 51.37 55.29 | + + + + Determinant : -11.9339 + + +Matrix : B Rows: 6 Cols: 1 + + | 9.41 | + | 15.78 | + | 22.75 | + | 29.90 | + | 37.16 | + | 44.61 | + + + + Determinant : -1.#IND + + +Matrix : A * A' Rows: 6 Cols: 6 + + | 1.00 0.00 0.00 0.00 0.00 0.00 | + | 0.00 1.00 0.00 0.00 0.00 0.00 | + | 0.00 0.00 1.00 0.00 0.00 0.00 | + | 0.00 0.00 0.00 1.00 0.00 0.00 | + | 0.00 0.00 0.00 0.00 1.00 0.00 | + | 0.00 0.00 0.00 0.00 0.00 1.00 | + + + + + +Matrix : X Rows: 6 Cols: 1 + + | 0.82 | + | 3.47 | + | -9.38 | + | 7.71 | + | -5.76 | + | 3.98 | + + + + + +Matrix : Y Rows: 6 Cols: 1 + + | 9.41 | + | 15.78 | + | 22.75 | + | 29.90 | + | 37.16 | + | 44.61 | \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Solve the 0-1 Knapsack Problem.cpp b/c++/Numerical_Problems/C++ Program to Solve the 0-1 Knapsack Problem.cpp new file mode 100644 index 0000000..4c43e45 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Solve the 0-1 Knapsack Problem.cpp @@ -0,0 +1,61 @@ +/*This is a C++ Program to solve 0-1 knapsack problem. The knapsack problem or rucksack problem is a problem in combinatorial optimization: Given a set of items, each with a mass and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most valuable items.*/ + +#include +#include +#include + +using namespace std; + +// A utility function that returns maximum of two integers +int max(int a, int b) +{ + return (a > b) ? a : b; +} + +// Returns the maximum value that can be put in a knapsack of capacity W +int knapSack(int W, int wt[], int val[], int n) +{ + // Base Case + if (n == 0 || W == 0) + return 0; + // If weight of the nth item is more than Knapsack capacity W, then + // this item cannot be included in the optimal solution + if (wt[n - 1] > W) + return knapSack(W, wt, val, n - 1); + // Return the maximum of two cases: (1) nth item included (2) not included + else + return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), + knapSack(W, wt, val, n - 1)); +} + +// Driver program to test above function +int main() +{ + cout << "Enter the number of items in a Knapsack:"; + int n, W; + cin >> n; + int val[n], wt[n]; + for (int i = 0; i < n; i++) + { + cout << "Enter value and weight for item " << i << ":"; + cin >> val[i]; + cin >> wt[i]; + } + // int val[] = { 60, 100, 120 }; + // int wt[] = { 10, 20, 30 }; + // int W = 50; + cout << "Enter the capacity of knapsack"; + cin >> W; + cout << knapSack(W, wt, val, n); + return 0; +} + +/* +Enter the number of items in a Knapsack:5 +Enter value and weight for item 0:11 111 +Enter value and weight for item 1:22 121 +Enter value and weight for item 2:33 131 +Enter value and weight for item 3:44 141 +Enter value and weight for item 4:55 151 +Enter the capacity of knapsack 300 +99 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Solve the Fractional Knapsack Problem.cpp b/c++/Numerical_Problems/C++ Program to Solve the Fractional Knapsack Problem.cpp new file mode 100644 index 0000000..1dd73ef --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Solve the Fractional Knapsack Problem.cpp @@ -0,0 +1,78 @@ +/*This is a C++ Program to solve fractional knapsack. The knapsack problem or rucksack problem is a problem in combinatorial optimization: Given a set of items, each with a mass and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most valuable items.*/ + +/* program to implement fractional knapsack problem using greedy programming */ +#include +using namespace std; +int main() +{ + int array[2][100], n, w, i, curw, used[100], maxi = -1, totalprofit = 0; + //input number of objects + cout << "Enter number of objects: "; + cin >> n; + //input max weight of knapsack + cout << "Enter the weight of the knapsack: "; + cin >> w; + /* Array's first row is to store weights + second row is to store profits */ + for (i = 0; i < n; i++) + { + cin >> array[0][i] >> array[1][i]; + } + for (i = 0; i < n; i++) + { + used[i] = 0; + } + curw = w; + //loop until knapsack is full + while (curw >= 0) + { + maxi = -1; + //loop to find max profit object + for (i = 0; i < n; i++) + { + if ((used[i] == 0) && ((maxi == -1) || (((float) array[1][i] + / (float) array[0][i]) > ((float) array[1][maxi] + / (float) array[0][maxi])))) + { + maxi = i; + } + } + used[maxi] = 1; + //decrease current wight + curw -= array[0][maxi]; + //increase total profit + totalprofit += array[1][maxi]; + if (curw >= 0) + { + cout << "\nAdded object " << maxi + 1 << " Weight: " + << array[0][maxi] << " Profit: " << array[1][maxi] + << " completely in the bag, Space left: " << curw; + } + else + { + cout << "\nAdded object " << maxi + 1 << " Weight: " + << (array[0][maxi] + curw) << " Profit: " + << (array[1][maxi] / array[0][maxi]) * (array[0][maxi] + + curw) << " partially in the bag, Space left: 0" + << " Weight added is: " << curw + array[0][maxi]; + totalprofit -= array[1][maxi]; + totalprofit += ((array[1][maxi] / array[0][maxi]) * (array[0][maxi] + + curw)); + } + } + //print total worth of objects filled in knapsack + cout << "\nBags filled with objects worth: " << totalprofit; + return 0; +} + +/* +Enter number of objects: 3 +Enter the weight of the knapsack: 50 +10 60 +20 100 +30 120 + +Added object 1 Weight: 10 Profit: 60 completely in the bag, Space left: 40 +Added object 2 Weight: 20 Profit: 100 completely in the bag, Space left: 20 +Added object 3 Weight: 20 Profit: 80 partially in the bag, Space left: 0 Weight added is: 20 +Bags filled with objects worth: 240 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to Use rand and srand Functions.cpp b/c++/Numerical_Problems/C++ Program to Use rand and srand Functions.cpp new file mode 100644 index 0000000..f84ec50 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to Use rand and srand Functions.cpp @@ -0,0 +1,20 @@ +#include +#include +#include + +using namespace std; + +int main(int argc, char **argv) +{ + cout << "First number: " << rand() % 100; + srand(time(NULL)); + cout << "\nRandom number: " << rand() % 100; + srand(1); + cout << "\nAgain the first number: " << rand() % 100; + return 0; +} + +/* +First number: 41 +Random number: 98 +Again the first number: 41 \ No newline at end of file diff --git a/c++/Numerical_Problems/C++ Program to implement Gauss Jordan Elimination algorithm..cpp b/c++/Numerical_Problems/C++ Program to implement Gauss Jordan Elimination algorithm..cpp new file mode 100644 index 0000000..0444346 --- /dev/null +++ b/c++/Numerical_Problems/C++ Program to implement Gauss Jordan Elimination algorithm..cpp @@ -0,0 +1,82 @@ +/*/This is a C++ Program to implement Gauss Jordan Elimination algorithm. In linear algebra, Gaussian elimination (also known as row reduction) is an algorithm for solving systems of linear equations. It is usually understood as a sequence of operations performed on the associated matrix of coefficients. This method can also be used to find the rank of a matrix, to calculate the determinant of a matrix, and to calculate the inverse of an invertible square matrix.*/ + + +#include +#include + +using namespace std; + +int main() +{ + int i, j, k, n; + float a[10][10] = { 0 }, d; + cout << "No of equations ? "; + cin >> n; + cout << "Read all coefficients of matrix with b matrix too " << endl; + for (i = 1; i <= n; i++) + for (j = 1; j <= n; j++) + cin >> a[i][j]; + for (i = 1; i <= n; i++) + for (j = 1; j <= 2 * n; j++) + if (j == (i + n)) + a[i][j] = 1; + /************** partial pivoting **************/ + for (i = n; i > 1; i--) + { + if (a[i - 1][1] < a[i][1]) + for (j = 1; j <= n * 2; j++) + { + d = a[i][j]; + a[i][j] = a[i - 1][j]; + a[i - 1][j] = d; + } + } + cout << "pivoted output: " << endl; + for (i = 1; i <= n; i++) + { + for (j = 1; j <= n * 2; j++) + cout << a[i][j] << " "; + cout << endl; + } + /********** reducing to diagonal matrix ***********/ + for (i = 1; i <= n; i++) + { + for (j = 1; j <= n * 2; j++) + if (j != i) + { + d = a[j][i] / a[i][i]; + for (k = 1; k <= n * 2; k++) + a[j][k] -= a[i][k] * d; + } + } + /************** reducing to unit matrix *************/ + for (i = 1; i <= n; i++) + { + d = a[i][i]; + for (j = 1; j <= n * 2; j++) + a[i][j] = a[i][j] / d; + } + cout << "your solutions: " << endl; + for (i = 1; i <= n; i++) + { + for (j = n + 1; j <= n * 2; j++) + cout << a[i][j] << " "; + cout << endl; + } + getch(); + return 0; +} + +/*No of equations ? 3 +Read all coefficients of matrix with b matrix too +2 3 4 +5 6 3 +9 8 6 +pivoted output: +9 8 6 0 0 1 +2 3 4 1 0 0 +5 6 3 0 1 0 +your solutions: +-0.292683 -0.341463 0.365854 +0.0731707 0.585366 -0.341463 +0.341463 -0.268293 0.0731708*/ \ No newline at end of file diff --git a/c++/Overview/C++ Program to Compare Two Strings Using Pointers.cpp b/c++/Overview/C++ Program to Compare Two Strings Using Pointers.cpp new file mode 100644 index 0000000..5768572 --- /dev/null +++ b/c++/Overview/C++ Program to Compare Two Strings Using Pointers.cpp @@ -0,0 +1,31 @@ + + + #include + #include + using namespace std; + main() { + char str1[50],str2[50]; + int str_cmp(char*,char*); + cout<<“Enter first string:”; + gets(str1); + cout<<“Enter second string:”; + gets(str2); + if(str_cmp(str1,str2)) + cout<<“nStrings are equal”; else + cout<<“nStrings are not equal”; + return 0; + } + int str_cmp(char *s1,char *s2) { + while(*s1==*s2) { + if(*s1==’’||*s2==’’) + break; + s1++; + s2++; + } + if(*s1==’’&&*s2==’’) + return 1; + return 0; + } + + + diff --git a/c++/Overview/C++ program to add two complex numbers.cpp b/c++/Overview/C++ program to add two complex numbers.cpp new file mode 100644 index 0000000..d3ff712 --- /dev/null +++ b/c++/Overview/C++ program to add two complex numbers.cpp @@ -0,0 +1,31 @@ +#include + +using namespace std; + +class complex +{ +public : + int real, img; +}; + +int main() +{ + complex a, b, c; + cout << "Enter a and b where a + ib is the first complex number."; + cout << "\na = "; + cin >> a.real; + cout << "b = "; + cin >> a.img; + cout << "Enter c and d where c + id is the second complex number."; + cout << "\nc = "; + cin >> b.real; + cout << "d = "; + cin >> b.img; + c.real = a.real + b.real; + c.img = a.img + b.img; + if ( c.img >= 0 ) + cout << "Sum of two complex numbers = " << c.real << " + " << c.img << "i"; + else + cout << "Sum of two complex numbers = " << c.real << " " << c.img << "i"; + return 0; +} \ No newline at end of file diff --git a/c++/Overview/C++ program to generate random numbers.cpp b/c++/Overview/C++ program to generate random numbers.cpp new file mode 100644 index 0000000..8c2cd9e --- /dev/null +++ b/c++/Overview/C++ program to generate random numbers.cpp @@ -0,0 +1,20 @@ +#include +#include + +using namespace std; + +main() +{ + int n, max, num, c; + cout << "Enter the number of random numbers you want "; + cin >> n; + cout << "Enter the maximum value of random number "; + cin >> max; + cout << "random numbers from 0 to " << max << " are :-" << endl; + for ( c = 1 ; c <= n ; c++ ) + { + num = random(max); + cout << num << endl; + } + return 0; +} \ No newline at end of file diff --git a/c++/Overview/C++ program to reverse a number.cpp b/c++/Overview/C++ program to reverse a number.cpp new file mode 100644 index 0000000..9a9aac5 --- /dev/null +++ b/c++/Overview/C++ program to reverse a number.cpp @@ -0,0 +1,38 @@ +#include + +using namespace std; + +class Operations +{ + long c; + +public: + void inputNumber() + { + cout << "Input a number\n"; + cin >> c; + } + + long reverseNumber() + { + long invert = 0; + while (c != 0) + { + invert = invert * 10; + invert = invert + c%10; + c = c/10; + } + return invert; + } + +}; + +int main() +{ + long result; + Operations t; + t.inputNumber(); + result = t.reverseNumber(); + cout << "Number obtained on reversal = " << result; + return 0; +} \ No newline at end of file diff --git a/c++/Overview/C++ program to swap two numbers using pointers.cpp b/c++/Overview/C++ program to swap two numbers using pointers.cpp new file mode 100644 index 0000000..e69de29 diff --git a/c++/Overview/CPP Program For Accessing Member Function Through Object.cpp b/c++/Overview/CPP Program For Accessing Member Function Through Object.cpp new file mode 100644 index 0000000..4c7ee41 --- /dev/null +++ b/c++/Overview/CPP Program For Accessing Member Function Through Object.cpp @@ -0,0 +1,49 @@ +#include + +#include + +class Power +{ + + double b; + + int e; + + double val; + +public: + + Power(double base, int exp); + + double getPower() + { + return val; + } + +}; + +Power::Power(double base, int exp) + +{ + b = base; + e = exp; + val = 1; + if(exp == 0) + return; + for( ; exp > 0; exp--) + val = val * b; +} + +int main() + +{ + clrscr(): + Power x(4.0, 2), y(2.5, 1), z(5.0, 0); + cout << x.getPower() << " "; + cout << y.getPower() << " "; + cout << z.getPower() << endl; + getch(); + return 0; + } + + diff --git a/c++/Overview/CPP Program For Call By Reference.cpp b/c++/Overview/CPP Program For Call By Reference.cpp new file mode 100644 index 0000000..139741a --- /dev/null +++ b/c++/Overview/CPP Program For Call By Reference.cpp @@ -0,0 +1,31 @@ +#include + +#include + + + +void multi(int &a) + +{ + int a,b,c; + int *q = &p; +cout<<”Enter the b value: + ” + cin>>b; + c=q*b; +cout<<”Multiplication of a and b is: + “<>a; + muti(&a); + return 0; +} + + diff --git a/c++/Overview/CPP Program For Call By Value.cpp b/c++/Overview/CPP Program For Call By Value.cpp new file mode 100644 index 0000000..c5f2263 --- /dev/null +++ b/c++/Overview/CPP Program For Call By Value.cpp @@ -0,0 +1,23 @@ +#include + +void doubleIt(int); + +int main () + +{ + int num; + cout << "Enter number: "; + cin >> num; + doubleIt(num); + cout << "The number doubled in main is " << num << endl; + return 0; +} + +void doubleIt (int x) + +{ + cout << "The number to be doubled is " << x << endl; + x *= 2; + cout << "The number doubled in doubleIt is " << x << endl; +} + diff --git a/c++/Overview/CPP Program For Constructor Over Loading.cpp b/c++/Overview/CPP Program For Constructor Over Loading.cpp new file mode 100644 index 0000000..2f4faba --- /dev/null +++ b/c++/Overview/CPP Program For Constructor Over Loading.cpp @@ -0,0 +1,76 @@ +// Step 1: Create the class. + +// Step 2: Declare the constructors with different parameter type and list. + +// Step 3: Create the objects for the Fixed_deposite. + +// Step 4: Object creation automatically call the type matched constructor. + +// Step 5: The matched type constructor procedure will be run. + +// Step 6: Compile and run the program. + +#include +class Fixed_deposite +{ + long int P_amount; + int Years; + float Rate; + float R_value; +public : + Fixed_deposit() {} + Fixed_deposit(long int p, int y,float r=0.12); + Fixed_deposit(long int p,int y,int r); + Void display(void); +}; +Fixed_deposite :: Fixed_deposit (long int p,int y,float r) +{ + P_amount=p; + Years=y; + Rate =r; + R_value=p_amount; + for(int i=1; i<=y; i++) + R_value=R_value * (1.0+r); +} + +Fixed_deposite :: Fixed_deposit (long int p,int y,int r) +{ + P_amount=p; + Years=y; + Rate =r; + R_value=p_amount; + for(int i=1; i<=y; i++) + R_value=R_value * (1.0+float(r)/100); +} + +void Fixed_deposite :: display(void) +{ + cout<<”\n”<<”Principal Amount=”<>p>>y>>R; + FD1 =Fixed_deposite(p,y,R); + cout<<”ENTER amount,period,interest rate(decimal form)”<<”\n”; + cin>>p>>y>>r; + FD2 =Fixed_deposite(p,y,R); + cout<<”Enter the amount and period\n”; + cin>>p>>y; + FD1 =Fixed_deposite(p,y); + cout<<"\nDeposiote"; + FD1.display(); + cout<<"\nDeposiote"; + FD2.display(); + cout<<"\nDeposiote"; + FD3.display(); +return 0: +} + + + diff --git a/c++/Overview/CPP Program For Declaring Pointers as Class Member.cpp b/c++/Overview/CPP Program For Declaring Pointers as Class Member.cpp new file mode 100644 index 0000000..ebe79ab --- /dev/null +++ b/c++/Overview/CPP Program For Declaring Pointers as Class Member.cpp @@ -0,0 +1,34 @@ +// Start the program +// Create the class and declare the data members and member functions +// Declare the pointer and store the address of data in the pointer +// Create the object and call the function in the main program +// Compile and execute the program + +#include + +class c1 + +{ + +public: + + int i; + + c1(int j) + + { + i = j; + } + +}; + +int main() + +{ + c1 ob(1); + int *p; + p = &ob.i; //get address of ob.i + cout<<*p; // access ob.i via p + return 0; +} + diff --git a/c++/Overview/CPP Program For Declaring Static Members as Class Member.cpp b/c++/Overview/CPP Program For Declaring Static Members as Class Member.cpp new file mode 100644 index 0000000..3937420 --- /dev/null +++ b/c++/Overview/CPP Program For Declaring Static Members as Class Member.cpp @@ -0,0 +1,49 @@ +// Start the program +// Create the static class and declare the static data members in the class +// Declare the static member function +// Create the object for the static class +// Pass the static data value when we call the static member function in the main program +// Compile and execute the program + + +#include + +class static_type + +{ + + static int i; + +public: + + static void init(int x) + + { + i = x; + } + + void show() + + { + cout< + +class matrix + +{ + + int a[2][2], b[2][2], c[2][2]; + + void add() + + { +cout<<”Enter the A matrix: + ”<<”\n”; + for(int i=0; i<2; i++) + { + for(int j=0; j<2; j++) + { + cin>>a[i][j]; + } + } +cout<<”Enter the B matrix: + ”<<”\n”; + for(int i=0; i<2; i++) + { + for (int j=0; j<2; j++) + { + cin>>b[i][j]; + } + } + for( i = 0; i< 2; i++) + { + for( j = 0; j<2; j++) + { + c[i][j] = a[i][j] + b[i][j]; + } + } +cout<<”Addition of Two matrixes: + ”< + +#include + +const int IN = 1; + +const int checked_out = 0; + +class book + +{ + + char author[40]; + + char title[40]; + + int status; + +public: + + book(char *n, char *t, int s); + + int get_status() + + { + return status; + } + + void set_status(int s) + + { + status = s; + } + + void show(); + +}; + +book::book(char *n, char *t, int s) + +{ + strcpy(author, n); + strcpy(title, t); + status = s; +} + +void book::show() + +{ + cout< +class loc +{ + int longtitude,latitude; +public: + loc(); + loc(int lg,int lt) + { + longtitude = lg; + latitude=lt; + } + + void show() + { + cout< +#include +class exforsys +{ +private: + int a,b; +public: + void test() + { + a=100; + b=200; + } + friend int compute(exforsys e1) + + + +//Friend Function Declaration with keyword friend and with the object of class exforsys to which it is friend passed to it +}; + + +int compute(exforsys e1) +{ +//Friend Function Definition which has access to private data + return int(e1.a+e1.b-5); +} + +main() +{ + exforsys e; + e.test(); +//Calling of Friend Function with object as argument. + cout<<"The result is:"< +#define SIZE 100 +class stack +{ + int stck[SIZE]; + int tos; +public: + stack(); //constructor + ~stack(); //destructor + void push(int i); + int pop(); +}; + +//stack’s constructor function +stack :: stack() +{ + tos=0; + cout<<”Stack Initialized\n”; +} + +//stacks destructor function +stack :: ~stack() +{ + cout<<”\Stack Destroyed”; +} + +void stack :: push(int i) +{ + if(tos==SIZE) + { + cout<<”Stack is full.\n”; + return; + } + stck[tos] = i; + tos++; +} + + +int stack :: pop () +{ + if(tos==0) + { + cout<<”Stack underflow.\n”; + return; + } + tos--; + return stck[tos]; +} + +int main() +{ + stack a,b; + a. push(1); + b. push(2); + a. push(3); + b. push(4); + cout< + +class myclass + +{ + + int a, b; + +public: + + void init(int i, int j); + + { + a = i; + b = j; + } + + void show(); + + { + cout<<”a=”< + +#include + +int abs(int n); + +double abs(double n); + +int main() + +{ + clrscr(); + cout << "Absolute value of -10: " << abs(-10) << endl; + cout << "Absolute value of -10.01: " << abs(-10.01) << endl; + getch(); + return 0; +} + +int abs(int n) + +{ + cout << "In integer abs()\n"; + return n<0 ? -n : n; +} + +double abs(double n) + +{ + cout << "In double abs()\n"; + return n<0 ? -n : n; +} + + diff --git a/c++/Overview/CPP Program To Implement Inheritance.cpp b/c++/Overview/CPP Program To Implement Inheritance.cpp new file mode 100644 index 0000000..f3ad059 --- /dev/null +++ b/c++/Overview/CPP Program To Implement Inheritance.cpp @@ -0,0 +1,142 @@ +// Step 1: Create the base class building. It has the blue print structure of the buildings. + +// Step 2: Create the derived class house from building class. It extends the buildings properties and also it has its own properties. + +// Step 3: Create the derived class school from building. School as have its unique properties. + +// Step 4: Give the definition to base and derived class methods. + +// Step 5: Create the object for the derived classes school and house . + +// Step 6: Call the member function through the objects. Now derived classes object can call the base class methods also. + +// Step 7: Compile and run. + + +#include +#include +class building +{ + int rooms; + int floors; + int area; +public: + void set_rooms(int num); + int get_rooms(); + void set_floors(int num); + int get_floors(); + void set_area(); + int get_area(); +}; + + +class house : public building +{ + int bedrooms; + int baths; +public: + void set_bedrooms(int num); + int get_bedrooms; + void set_baths(int num); + int get_baths(); +}; + +class school : public building +{ + int classrooms; + int offices; +public: + void set_classrooms(int num); + int get_classrooms(); + void set_offices(int num); + int get_offices(); + +}; + +void building :: set_rooms(int num) +{ + rooms=num; +} + +void building::set_floors(int num) +{ + floors = num; +} + +void building :: set_area(int num) +{ + area=num; +} +int building :: get_rooms() +{ + return rooms; +} + +int building :: get_floors() +{ + returns floors; +} +int building :: get_area() +{ + return area; +} + +void house :: set_bedrooms(int num) +{ + bedrooms = num; +} + +void house ::set_baths(int num) +{ + baths=num; +} + +int house :: get_bedrooms() +{ + return bedrooms; +} +int house::get_baths() +{ + return baths; +} + +void school :: set_classrooms(int num) +{ + classrooms = num; +} +void school :: set_offices(int num) +{ + offices =num; +} + +int school :: get_classrooms() +{ + return classrooms; +} +int school :: get_offices() +{ + return offices; +} + +int main() +{ + house h; + school s; + h.set_rooms(12); + h.set_floors(3); + h.set_area(4500); + h.set_bedrooms(5); + h.set_baths(3); + cout<<"house has" << h.get_bedrooms(); + cout<< "bedrooms\n"; + s.set_rooms(200); + s.classrooms(180); + s.set_offices(5); + s.set_area(25000); + cout<<"school has "< +using namespace std; + +class BaseClass1 +{ + int a; +public: + BaseClass1(int x) + { + a = x; + } + int geta() + { + return a; + } +}; + + +class BaseClass2 +{ + int b; +public: + BaseClass2(int x) + { + b = x; + } + int getb() + { + return b; + } +}; + + +class DerivedClass : public BaseClass1, public BaseClass2 +{ + int c; +public: + DerivedClass(int x, int y, int z) : BaseClass1(z), BaseClass2(y) + { + c = x; + } + + void show() + { + cout << geta() << ' ' << getb() << ' '; + cout << c << '\n'; + } +}; + +int main() +{ + DerivedClass object(1, 2, 3); + object.show(); + return 0; +} + + diff --git a/c++/Overview/CPP Program To Implement Pure Virtual Function.cpp b/c++/Overview/CPP Program To Implement Pure Virtual Function.cpp new file mode 100644 index 0000000..5281c51 --- /dev/null +++ b/c++/Overview/CPP Program To Implement Pure Virtual Function.cpp @@ -0,0 +1,67 @@ +// Step 1: create a base class namely number and declare the pure virtual function show(). + +// Step 2: create the derived classes hextype, dectype & acttype from the class number + +// Step 3: create the objects for the class dectype, hextype and octtype. + +// Step 4: call the member function show(); + +// Step 5: Corresponding called function change the integer type as hex ,oct and decimal . + +// Step 6: Display the values. + +#include +class number +{ +protected: + int val; +public : + void setval(int i) + { + val= i; + } + //show() is a pure virtual function + virtual void show() = 0; +}; + +class hextype : public number +{ +public : + void show () + { + cout< + +#include + +#include + +void main(int argc,char *argv[]) + +{ + char ch; + clrscr(); + if(argc!=3) + { + cout<<"Usage Starting Location\n"; + } + ifstream in(argv[1],ios::in | ios::binary); + if(!in) + { + cout<<"Cannot open a file"; + } + in.seekg(0,ios::beg); + while(in.get(ch)) + cout< + +#include + +int main() + +{ + ifstream in(“INVENTRY”); //input + if(!in) + { + cout<<”Cannot open INVENTRY file”; + return 1; + } + char item[20]; + float cost; + in>>item>>cost; + cout<>item>>cost; + cout<>item>>cost; + cout< + +template + +class MyClass +{ + + T value1, value2; + +public: + + MyClass (T first, T second) + { + value1=first; + value2=second; + } + + T getmax () + + { + T retval; + retval = value1>value2 ? value1 : value2; + return retval; + } + +}; + +int main () + +{ + MyClass myobject (10, 5); + cout << myobject.getmax(); + return 0; +} + + diff --git a/c++/Overview/CPP Program To Implement Virtual Functions.cpp b/c++/Overview/CPP Program To Implement Virtual Functions.cpp new file mode 100644 index 0000000..1dd55a0 --- /dev/null +++ b/c++/Overview/CPP Program To Implement Virtual Functions.cpp @@ -0,0 +1,149 @@ +// Start the program +// Create the base class and declare the data member under protected access specifier and declare the function +// Create the derived class and access the base class data members in the derived class +// Create the object for derived class +// Call the public member function of the derived class +// Compile and run the program + +#include + +#include + +#include + +class Shape +{ + + double width; + + double height; + + char name[20]; + +public: + + Shape() + { + width = height = 0.0; + strcpy(name, "unknown"); + } + + Shape(double w, double h, char *n) + { + width = w; + height = h; + strcpy(name, n); + } + + Shape(double x, char *n) + { + width = height = x; + strcpy(name, n); + } + + void display() + { + cout << "Width and height are " << width << " and " << height << "\n"; + } + + double getWidth() + { + return width; + } + + double getHeight() + { + return height; + } + + void setWidth(double w) + { + width = w; + } + + void setHeight(double h) + { + height = h; + } + + char *getName() + { + return name; + } + + virtual double area() = 0; + +}; + +class Triangle : public Shape +{ + + char style[20]; + +public: + + Triangle() + { + strcpy(style, "unknown"); + } + + Triangle(char *str, double w, double h) : Shape(w, h, "triangle") + { + strcpy(style, str); + } + + Triangle(double x) : Shape(x, "triangle") + { + strcpy(style, "isosceles"); + } + + double area() + { + return getWidth() * getHeight() / 2; + } + + void showStyle() + { + cout << "Triangle is " << style << "\n"; + } + +}; + +class Rectangle : public Shape +{ + +public: + + Rectangle(double w, double h) : Shape(w, h, "rectangle") { } + + Rectangle(double x) : Shape(x, "rectangle") { } + + bool isSquare() + { + if(getWidth() == getHeight()) + return true; + return false; + } + + double area() + { + return getWidth() * getHeight(); + } + +}; + +int main() +{ + Shape *shapes[4]; + shapes[0] = &Triangle("right", 8.0, 12.0); + shapes[1] = &Rectangle(10); + shapes[2] = &Rectangle(10, 4); + shapes[3] = &Triangle(7.0); + for(int i=0; i < 4; i++) + { + cout << "object is " << shapes[i]->getName() << "\n"; + cout << "Area is " << shapes[i]->area() << "\n\n"; + } + return 0; +} + diff --git a/c++/Overview/CPP Program To Overriding Template Function.cpp b/c++/Overview/CPP Program To Overriding Template Function.cpp new file mode 100644 index 0000000..1db074c --- /dev/null +++ b/c++/Overview/CPP Program To Overriding Template Function.cpp @@ -0,0 +1,49 @@ +// Step 1: Declare the template function + +// Step 2: Declare the overload function swap args. + +// Step 3: Call the overloaded function swap args with float arguments. + +// Step 4: Call the overload function swap args with char arguments. + +// Step 5: Display the content. + + + +#include +template void swapargs(X &a,X &b) +{ + X temp; + temp = a; + a=b; + b=temp; + cout<<"Inside the template swapargs"; +} + +void swapargs(int &a,int &b) +{ + int temp; + temp=a; + a=b; + b=temp; + cout<<"Inside swapargs int specialization"; +} + +int main() +{ + int i=0,j=20; + double x=10.1,y=23.3; + char a='x',b='z'; + cout<<"original i,j : "< +#include +#include + +class loc +{ + int longtitude,latitude; +public : + loc() + { + longtitude=latitude=0; + } + loc (int lg,int lt) + { + longtitude=lg; + latitude=lt; + } + void show() + { + cout<< logitude << " "; + cout<< latitude <<"\n"; + } + + void *operator new(size_t size); + void operator delete(void *p); + void *operator new[](size_t size); + void operator delete[](void *p); +}; + +// new overloaded relative to loc + +void *loc :: operator new(size_t size) +{ + void *p; + cout<<"In overloaded new.\n"; + p=malloc(size); + if(!p) + { + bad_alloc ba; + throw ba; + } + return p; +} + +void loc :: operator delete (void *p) +{ + cout<< "In overloaded delete. \n"; + free(p); +} + +//new overloaded for loc arrays. +void *loc :: operator new[](size_t size) +{ + void *p; + cout<<"Using overload new[].\n"; + p=malloc(size); + if(!p) + { + bad_alloc ba; + throw ba; + } + return p; +} + +//delete overloaded for loc arrays. + +void loc :: operator delete[](void *p) +{ + cout<<"Freeing array using overloaded delete[]\n"; + free(p); +} + +int main() +{ + loc *p1,*p2; + int i; + try + { + p1=new loc(10,20); //allocate an object + } + catch (bad_alloc xa) + { + cout<<"Allocation error for p1.\n"; + return 1; + } + try + { + p2=new loc[10]; + } + catch(bad_alloc xa) + { + cout<<"Allocation error for p2 .\n"; + return 1; + } + p1->show(); + for(i=0; i<10; i++) + p2[i].show(); + delete p1; + delete [] p2; + return 0; +} + +// SAMPLE INPUT AND OUTPUT: + +// In overloaded new +// Using overload new[]. + +// 10 20 +// 0 0 +// 0 0 +// 0 0 +// 0 0 +// 0 0 +// 0 0 +// 0 0 +// 0 0 +// 0 0 +// 0 0 +// In overloaded delete. +// Freeing array using overloaded delete. diff --git a/c++/Overview/CPP Program to Implement Operator Overloading Including Unary and Binary Operators.cpp b/c++/Overview/CPP Program to Implement Operator Overloading Including Unary and Binary Operators.cpp new file mode 100644 index 0000000..9202cac --- /dev/null +++ b/c++/Overview/CPP Program to Implement Operator Overloading Including Unary and Binary Operators.cpp @@ -0,0 +1,44 @@ +// Start the program +// Create the class +// Write the function to implement unary +, - and = +// Write the function to implement binary + +// Create the instance and pass the value for the function +// Call the overloaded function and equate it to another object +// Compile and run the program + +#include + +class myclass + +{ + + int a, b; + +public: + + void init(int i, int j); + + { + a = i; + b = j; + } + + void show(); + + { + cout<<”a=”< + +class base + +{ + +protected: + + int i, j; //private to base but accessible to derived + +public: + + void setij(int a, int b) + + { + i = a; + j = b; + } + + void showij() + + { + cout< +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define MAX_NFA_STATES 10 +#define MAX_ALPHABET_SIZE 10 +using namespace std; +// Representation of an NFA state +class NFAstate +{ +public: + int transitions[MAX_ALPHABET_SIZE][MAX_NFA_STATES]; + NFAstate() + { + for (int i = 0; i < MAX_ALPHABET_SIZE; i++) + for (int j = 0; j < MAX_NFA_STATES; j++) + transitions[i][j] = -1; + } +}*NFAstates; +// Representation of a DFA state +struct DFAstate +{ + bool finalState; + bitset constituentNFAstates; + bitset transitions[MAX_ALPHABET_SIZE]; + int symbolicTransitions[MAX_ALPHABET_SIZE]; +}; +set NFA_finalStates; +vector DFA_finalStates; +vector DFAstates; +queue incompleteDFAstates; +int N, M; // N -> No. of stattes, M -> Size of input alphabet +// finds the epsilon closure of the NFA state "state" and stores it into "closure" +void epsilonClosure(int state, bitset &closure) +{ + for (int i = 0; i < N && NFAstates[state].transitions[0][i] != -1; i++) + if (closure[NFAstates[state].transitions[0][i]] == 0) + { + closure[NFAstates[state].transitions[0][i]] = 1; + epsilonClosure(NFAstates[state].transitions[0][i], closure); + } +} +// finds the epsilon closure of a set of NFA states "state" and stores it into "closure" +void epsilonClosure(bitset state, + bitset &closure) +{ + for (int i = 0; i < N; i++) + if (state[i] == 1) + epsilonClosure(i, closure); +} +// returns a bitset representing the set of states the NFA could be in after moving +// from state X on input symbol A +void NFAmove(int X, int A, bitset &Y) +{ + for (int i = 0; i < N && NFAstates[X].transitions[A][i] != -1; i++) + Y[NFAstates[X].transitions[A][i]] = 1; +} +// returns a bitset representing the set of states the NFA could be in after moving +// from the set of states X on input symbol A +void NFAmove(bitset X, int A, bitset &Y) +{ + for (int i = 0; i < N; i++) + if (X[i] == 1) + NFAmove(i, A, Y); +} +int main() +{ + int i, j, X, Y, A, T, F, D; + // read in the underlying NFA + ifstream fin("NFA.txt"); + fin >> N >> M; + NFAstates = new NFAstate[N]; + fin >> F; + for (i = 0; i < F; i++) + { + fin >> X; + NFA_finalStates.insert(X); + } + fin >> T; + while (T--) + { + fin >> X >> A >> Y; + for (i = 0; i < Y; i++) + { + fin >> j; + NFAstates[X].transitions[A][i] = j; + } + } + fin.close(); + // construct the corresponding DFA + D = 1; + DFAstates.push_back(new DFAstate); + DFAstates[0]->constituentNFAstates[0] = 1; + epsilonClosure(0, DFAstates[0]->constituentNFAstates); + for (j = 0; j < N; j++) + if (DFAstates[0]->constituentNFAstates[j] == 1 && NFA_finalStates.find( + j) != NFA_finalStates.end()) + { + DFAstates[0]->finalState = true; + DFA_finalStates.push_back(0); + break; + } + incompleteDFAstates.push(0); + while (!incompleteDFAstates.empty()) + { + X = incompleteDFAstates.front(); + incompleteDFAstates.pop(); + for (i = 1; i <= M; i++) + { + NFAmove(DFAstates[X]->constituentNFAstates, i, + DFAstates[X]->transitions[i]); + epsilonClosure(DFAstates[X]->transitions[i], + DFAstates[X]->transitions[i]); + for (j = 0; j < D; j++) + if (DFAstates[X]->transitions[i] + == DFAstates[j]->constituentNFAstates) + { + DFAstates[X]->symbolicTransitions[i] = j; + break; + } + if (j == D) + { + DFAstates[X]->symbolicTransitions[i] = D; + DFAstates.push_back(new DFAstate); + DFAstates[D]->constituentNFAstates + = DFAstates[X]->transitions[i]; + for (j = 0; j < N; j++) + if (DFAstates[D]->constituentNFAstates[j] == 1 + && NFA_finalStates.find(j) != NFA_finalStates.end()) + { + DFAstates[D]->finalState = true; + DFA_finalStates.push_back(D); + break; + } + incompleteDFAstates.push(D); + D++; + } + } + } + // write out the corresponding DFA + ofstream fout("DFA.txt"); + fout << D << " " << M << "\n" << DFA_finalStates.size(); + for (vector::iterator it = DFA_finalStates.begin(); it + != DFA_finalStates.end(); it++) + fout << " " << *it; + fout << "\n"; + for (i = 0; i < D; i++) + { + for (j = 1; j <= M; j++) + fout << i << " " << j << " " + << DFAstates[i]->symbolicTransitions[j] << "\n"; + } + fout.close(); + return 0; +} + +/* + +Input file +NFA.txt +4 2 +2 0 1 +4 +0 1 2 1 2 +1 1 2 1 2 +2 2 2 1 3 +3 1 2 1 2 + +Output file +DFA.txt +4 2 +3 0 1 3 +0 1 1 +0 2 2 +1 1 1 +1 2 3 +2 1 2 +2 2 2 +3 1 1 +3 2 2 diff --git a/c++/Sets_&_Strings/C++ Program to Decode a Message Encoded Using Playfair Cipher.cpp b/c++/Sets_&_Strings/C++ Program to Decode a Message Encoded Using Playfair Cipher.cpp new file mode 100644 index 0000000..910cffc --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Decode a Message Encoded Using Playfair Cipher.cpp @@ -0,0 +1,121 @@ +/* + * C++ Program to Decode a Message Encoded Using Playfair Cipher + This C++ program decodes any message encoded using the technique of traditional playfair cipher. The Playfair cipher or Playfair square is a manual symmetric encryption technique and was the first literal digraph substitution cipher. Input is not case sensitive and works only for characters from ‘a’ to ‘z’ and ‘A’ to ‘Z’. + */ +#include +#include +using namespace std; + +const char encoder[5][5] = {{'A','B','C','D','E'}, + {'F','G','H','I','K'}, + {'L','M','N','O','P'}, + {'Q','R','S','T','U'}, + {'V','W','X','Y','Z'} +}; + +void input_string(vector& a) +{ + char c; + while (1) + { + c=getchar(); + if (c >= 97 && c <= 122) + c -= 32; + if (c == '\n') + break; + else if (c==' ') + continue; + else if (c == 'J') + a.push_back('I'); + a.push_back(c); + } + return; +} + + + +void get_pos(char p, int& r, int& c) +{ + if (p < 'J') + { + r = (p - 65) / 5; + c = (p - 65) % 5; + } + else if (p > 'J') + { + r = (p - 66) / 5; + c = (p - 66) % 5; + } + return; +} + +void same_row(int r, vector& code, int c1, int c2) +{ + code.push_back(encoder[r][(c1 + 4) % 5]); + code.push_back(encoder[r][(c2 + 4) % 5]); + return; +} + +void same_column(int c, vector& code, int r1, int r2) +{ + code.push_back(encoder[(r1 + 4) % 5][c]); + code.push_back(encoder[(r2 + 4) % 5][c]); + return; +} + +void diff_col_row(int r1, int c1, vector& code, int r2, int c2) +{ + code.push_back(encoder[r1][c2]); + code.push_back(encoder[r2][c1]); + return; +} + + +void encode(vector msgx, int len) +{ + vector code; + int i = 0, j = 0; + int r1, c1, r2, c2; + while (i < len) + { + get_pos(msgx[i], r1, c1); + i++; + get_pos(msgx[i], r2, c2); + if (r1 == r2) + { + same_row(r1, code, c1, c2); + } + else if (c1 == c2) + { + same_column(c1, code, r1, r2); + } + else + { + diff_col_row(r1, c1, code, r2, c2); + } + i++; + } + cout<<"\nCODE: "; + for (j = 0; j < code.size(); j++) + { + if (code[j] == 'X') + continue; + cout< msg; + std::cout<<"Enter the Encrypted Message:"; + input_string(msg); + int len=msg.size(); + encode(msg,len); + return 0; +} + +/* +Enter the Encrypted Message:CBNVMPPO +CODE: BALLOON \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Encode a Message Using Playfair Cipher.cpp b/c++/Sets_&_Strings/C++ Program to Encode a Message Using Playfair Cipher.cpp new file mode 100644 index 0000000..4e9ae5f --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Encode a Message Using Playfair Cipher.cpp @@ -0,0 +1,158 @@ +/* + * C++ Program to Encode a Message Using Playfair Cipher + */ +#include +#include +using namespace std; + +void get_pos(char, int&, int&); +void same_row(int, vector&, int, int); +void same_column(int, vector&, int, int); +void diff_col_row(int, int, vector&, int, int); +void encode(vector, int); +void get_input(vector&); +void convert_string(vector&, vector&); + +const char encoder[5][5]= {{'A','B','C','D','E'}, + {'F','G','H','I','K'}, + {'L','M','N','O','P'}, + {'Q','R','S','T','U'}, + {'V','W','X','Y','Z'} +}; + +void get_pos(char p, int& r, int& c) +{ + if (p < 'J') + { + r = (p - 65) / 5; + c = (p - 65) % 5; + } + else if (p > 'J') + { + r = (p - 66) / 5; + c = (p - 66) % 5; + } + return; +} + +void same_row(int r, vector& code, int c1, int c2) +{ + code.push_back(encoder[r][(c1 + 1) % 5]); + code.push_back(encoder[r][(c2 + 1) % 5]); + return; +} + +void same_column(int c, vector& code, int r1, int r2) +{ + code.push_back(encoder[(r1 + 1) % 5][c]); + code.push_back(encoder[(r2 + 1) % 5][c]); + return; +} + +void diff_col_row(int r1, int c1, vector& code, int r2, int c2) +{ + code.push_back(encoder[r1][c2]); + code.push_back(encoder[r2][c1]); + return; +} + +void encode(vector msgx, int len) +{ + vector code; + int i = 0, j = 0; + int r1, c1, r2, c2; + while (i < len) + { + get_pos(msgx[i], r1, c1); + i++; + get_pos(msgx[i], r2, c2); + if (r1 == r2) + { + same_row(r1, code, c1, c2); + } + else if (c1 == c2) + { + same_column(c1, code, r1, r2); + } + else + { + diff_col_row(r1, c1, code, r2, c2); + } + i++; + } + cout<<"\nCODE: "; + for (j = 0; j < code.size(); j++) + { + cout<& a) +{ + char c; + while (1) + { + c = getchar(); + if (c >= 97 && c <= 122) + c- =32; + if (c == '\n') + break; + else if (c==' ') + continue; + else if (c == 'J') + a.push_back('I'); + a.push_back(c); + } + return; +} + +void convert_string(vector& msg, vector& msgx) +{ + int i, j; + i = j = 0; + while (i < msg.size()) + { + msgx.push_back(msg[i]); + i++; + if (i == msg.size()) + { + msgx.push_back('X'); + break; + } + if (msg[i] == msgx[j]) + { + msgx.push_back('X'); + j++; + } + else if(msg[i] != msgx[j]) + { + j++; + msgx.push_back(msg[i]); + i+ = 1; + } + j++; + } +} + +int main() +{ + vector msg; + vector msgx; + int i, j; + cout<<"Enter Message to Encrypt:"; + get_input(msg); + convert_string(msg, msgx); + int len = msgx.size(); + /* + cout<<"\n\n"; + for (i = 0;i < len;i++) + cout< +#include +using namespace std; + +// A utility function to find maximum of two integers +int max(int a, int b) +{ + return (a > b)? a : b; +} + +/* Returns length of longest common substring of X[0..m-1] and Y[0..n-1] */ +int LCSubStr(char *X, char *Y, int m, int n) +{ + int LCSuff[m + 1][n + 1]; + int result = 0; + for (int i = 0; i <= m; i++) + { + for (int j=0; j<=n; j++) + { + if (i == 0 || j == 0) + LCSuff[i][j] = 0; + else if (X[i-1] == Y[j-1]) + { + LCSuff[i][j] = LCSuff[i-1][j-1] + 1; + result = max(result, LCSuff[i][j]); + } + else LCSuff[i][j] = 0; + } + } + return result; +} + +/*Main */ +int main() +{ + char X[] = "Sanfoundry"; + char Y[] = "foundation"; + int m = strlen(X); + int n = strlen(Y); + cout << "Length of Longest Common Substring is " << LCSubStr(X, Y, m, n); + return 0; +} + +/* +Length of Longest Common Substring is 5 \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Find the Longest Increasing Subsequence of a Given Sequence.cpp b/c++/Sets_&_Strings/C++ Program to Find the Longest Increasing Subsequence of a Given Sequence.cpp new file mode 100644 index 0000000..7789c86 --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Find the Longest Increasing Subsequence of a Given Sequence.cpp @@ -0,0 +1,59 @@ +/*This is a C++ Program to implement LCS. The longest common subsequence (LCS) problem is to find the longest subsequence common to all sequences in a set of sequences (often just two). (Note that a subsequence is different from a substring, for the terms of the former need not be consecutive terms of the original sequence.) It is a classic computer science problem, the basis of data comparison programs such as the diff utility, and has applications in bioinformatics.*/ + +#include +#include +#include + +using namespace std; + +#define ARRAY_SIZE(A) sizeof(A)/sizeof(A[0]) +// Binary search (note boundaries in the caller) +// A[] is ceilIndex in the caller +int CeilIndex(int A[], int l, int r, int key) +{ + int m; + while (r - l > 1) + { + m = l + (r - l) / 2; + (A[m] >= key ? r : l) = m; // ternary expression returns an l-value + } + return r; +} + +int LongestIncreasingSubsequenceLength(int A[], int size) +{ + // Add boundary case, when array size is one + int *tailTable = new int[size]; + int len; // always points empty slot + memset(tailTable, 0, sizeof(tailTable[0]) * size); + tailTable[0] = A[0]; + len = 1; + for (int i = 1; i < size; i++) + { + if (A[i] < tailTable[0]) + // new smallest value + tailTable[0] = A[i]; + else if (A[i] > tailTable[len - 1]) + // A[i] wants to extend largest subsequence + tailTable[len++] = A[i]; + else + // A[i] wants to be current end candidate of an existing subsequence + // It will replace ceil value in tailTable + tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i]; + } + delete[] tailTable; + return len; +} + +int main() +{ + int A[] = { 2, 5, 3, 7, 11, 8, 10, 13, 6 }; + int n = ARRAY_SIZE(A); + printf("Length of Longest Increasing Subsequence is %d\n", + LongestIncreasingSubsequenceLength(A, n)); + return 0; +} + +/* + +Length of Longest Increasing Subsequence is 6 \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Implement Affine Cipher.cpp b/c++/Sets_&_Strings/C++ Program to Implement Affine Cipher.cpp new file mode 100644 index 0000000..4ee3bed --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Implement Affine Cipher.cpp @@ -0,0 +1,57 @@ +/*This is a C++ Program to implement Affine Cipher. The affine cipher is a type of monoalphabetic substitution cipher, wherein each letter in an alphabet is mapped to its numeric equivalent, encrypted using a simple mathematical function, and converted back to a letter. The formula used means that each letter encrypts to one other letter, and back again, meaning the cipher is essentially a standard substitution cipher with a rule governing which letter goes to which. As such, it has the weaknesses of all substitution ciphers. Each letter is enciphered with the function (ax+b)mod(26), where b is the magnitude of the shift.*/ + +#include +#include +#include +using namespace std; +string encryptionMessage(string Msg) +{ + string CTxt = ""; + int a = 3; + int b = 6; + for (int i = 0; i < Msg.length(); i++) + { + CTxt = CTxt + (char) ((((a * Msg[i]) + b) % 26) + 65); + } + return CTxt; +} + +string decryptionMessage(string CTxt) +{ + string Msg = ""; + int a = 3; + int b = 6; + int a_inv = 0; + int flag = 0; + for (int i = 0; i < 26; i++) + { + flag = (a * i) % 26; + if (flag == 1) + { + a_inv = i; + } + } + for (int i = 0; i < CTxt.length(); i++) + { + Msg = Msg + (char) (((a_inv * ((CTxt[i] - b)) % 26)) + 65); + } + return Msg; +} +int main(int argc, char **argv) +{ + cout << "Enter the message: "; + string message; + cin >> message; + cout << "Message is :" << message; + cout << "\nEncrypted Message is : " << encryptionMessage(message); + cout << "\nDecrypted Message is: " << decryptionMessage( + encryptionMessage(message)); +} + + +/* + +Enter the message: SANFOUNDRY +Message is :SANFOUNDRY +Encrypted Message is : VTGIJBGCSN +Decrypted Message is: SANFOUNDRY \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Implement Aho-Corasick Algorithm for String Matching.cpp b/c++/Sets_&_Strings/C++ Program to Implement Aho-Corasick Algorithm for String Matching.cpp new file mode 100644 index 0000000..243c99a --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Implement Aho-Corasick Algorithm for String Matching.cpp @@ -0,0 +1,146 @@ +/*n computer science, the Aho–Corasick string matching algorithm is a string searching algorithm, it is a kind of dictionary-matching algorithm that locates elements of a finite set of strings (the “dictionary”) within an input text. It matches all patterns simultaneously. The complexity of the algorithm is linear in the length of the patterns plus the length of the searched text plus the number of output matches. Note that because all matches are found, there can be a quadratic number of matches if every substring matches (e.g. dictionary = a, aa, aaa, aaaa and input string is aaaa).*/ + +using namespace std; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define foreach(x, v) for (typeof (v).begin() x=(v).begin(); x !=(v).end(); ++x) +#define For(i, a, b) for (int i=(a); i<(b); ++i) +#define D(x) cout << #x " is " << x << endl + +const int MAXS = 6 * 50 + 10; // Max number of states in the matching machine. +// Should be equal to the sum of the length of all keywords. + +const int MAXC = 26; // Number of characters in the alphabet. + +int out[MAXS]; // Output for each state, as a bitwise mask. +int f[MAXS]; // Failure function +int g[MAXS][MAXC]; // Goto function, or -1 if fail. + +int buildMatchingMachine(const vector &words, char lowestChar = 'a', + char highestChar = 'z') +{ + memset(out, 0, sizeof out); + memset(f, -1, sizeof f); + memset(g, -1, sizeof g); + int states = 1; // Initially, we just have the 0 state + for (int i = 0; i < words.size(); ++i) + { + const string &keyword = words[i]; + int currentState = 0; + for (int j = 0; j < keyword.size(); ++j) + { + int c = keyword[j] - lowestChar; + if (g[currentState][c] == -1) + { + // Allocate a new node + g[currentState][c] = states++; + } + currentState = g[currentState][c]; + } + out[currentState] |= (1 << i); // There's a match of keywords[i] at node currentState. + } + // State 0 should have an outgoing edge for all characters. + for (int c = 0; c < MAXC; ++c) + { + if (g[0][c] == -1) + { + g[0][c] = 0; + } + } + // Now, let's build the failure function + queue q; + for (int c = 0; c <= highestChar - lowestChar; ++c) + { + // Iterate over every possible input + // All nodes s of depth 1 have f[s] = 0 + if (g[0][c] != -1 and g[0][c] != 0) + { + f[g[0][c]] = 0; + q.push(g[0][c]); + } + } + while (q.size()) + { + int state = q.front(); + q.pop(); + for (int c = 0; c <= highestChar - lowestChar; ++c) + { + if (g[state][c] != -1) + { + int failure = f[state]; + while (g[failure][c] == -1) + { + failure = f[failure]; + } + failure = g[failure][c]; + f[g[state][c]] = failure; + out[g[state][c]] |= out[failure]; // Merge out values + q.push(g[state][c]); + } + } + } + return states; +} +int findNextState(int currentState, char nextInput, char lowestChar = 'a') +{ + int answer = currentState; + int c = nextInput - lowestChar; + while (g[answer][c] == -1) + answer = f[answer]; + return g[answer][c]; +} + +int main() +{ + vector keywords; + keywords.push_back("he"); + keywords.push_back("she"); + keywords.push_back("hers"); + keywords.push_back("his"); + string text = "ahishers"; + buildMatchingMachine(keywords, 'a', 'z'); + int currentState = 0; + for (int i = 0; i < text.size(); ++i) + { + currentState = findNextState(currentState, text[i], 'a'); + if (out[currentState] == 0) + continue; // Nothing new, let's move on to the next character. + for (int j = 0; j < keywords.size(); ++j) + { + if (out[currentState] & (1 << j)) + { + // Matched keywords[j] + cout << "Keyword " << keywords[j] << " appears from " << i + - keywords[j].size() + 1 << " to " << i << endl; + } + } + } + return 0; +} + +/* + + +Keyword his appears from 1 to 3 +Keyword he appears from 4 to 5 +Keyword she appears from 3 to 5 +Keyword hers appears from 4 to 7 \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Implement Bitap Algorithm for String Matching.cpp b/c++/Sets_&_Strings/C++ Program to Implement Bitap Algorithm for String Matching.cpp new file mode 100644 index 0000000..ec85825 --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Implement Bitap Algorithm for String Matching.cpp @@ -0,0 +1,64 @@ +/*This is a C++ Program to Implement Bitap Algorithm. The bitap algorithm (also known as the shift-or, shift-and or Baeza-Yates–Gonnet algorithm) is an approximate string matching algorithm. The algorithm tells whether a given text contains a substring which is “approximately equal” to a given pattern, where approximate equality is defined in terms of Levenshtein distance — if the substring and pattern are within a given distance k of each other, then the algorithm considers them equal. The algorithm begins by precomputing a set of bitmasks containing one bit for each element of the pattern. Then it is able to do most of the work with bitwise operations, which are extremely fast.*/ + +#include +#include +#include + +using namespace std; +int bitap_search(string text, string pattern) +{ + int m = pattern.length(); + long pattern_mask[256]; + /** Initialize the bit array R **/ + long R = ~1; + if (m == 0) + return -1; + if (m > 63) + { + cout<<"Pattern is too long!"; + return -1; + } + /** Initialize the pattern bitmasks **/ + for (int i = 0; i <= 255; ++i) + pattern_mask[i] = ~0; + for (int i = 0; i < m; ++i) + pattern_mask[pattern[i]] &= ~(1L << i); + for (int i = 0; i < text.length(); ++i) + { + /** Update the bit array **/ + R |= pattern_mask[text[i]]; + R <<= 1; + if ((R & (1L << m)) == 0) + return i - m + 1; + } + return -1; +} +void findPattern(string t, string p) +{ + int pos = bitap_search(t, p); + if (pos == -1) + cout << "\nNo Match\n"; + else + cout << "\nPattern found at position : " << pos; +} + +int main(int argc, char **argv) +{ + cout << "Bitap Algorithm Test\n"; + cout << "Enter Text\n"; + string text; + cin >> text; + cout << "Enter Pattern\n"; + string pattern; + cin >> pattern; + findPattern(text, pattern); +} + +/* +Bitap Algorithm Test +Enter Text +DharmendraHingu +Enter Pattern +Hingu + +Pattern found at position : 10 \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Implement Boyer-Moore Algorithm for String Matching.cpp b/c++/Sets_&_Strings/C++ Program to Implement Boyer-Moore Algorithm for String Matching.cpp new file mode 100644 index 0000000..608a337 --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Implement Boyer-Moore Algorithm for String Matching.cpp @@ -0,0 +1,61 @@ +/*This is a C++ Program to implement Boyer-Moore algorithm. The idea of bad character heuristic is simple. The character of the text which doesn’t match with the current character of pattern is called the Bad Character. Whenever a character doesn’t match, we slide the pattern in such a way that aligns the bad character with the last occurrence of it in pattern. We preprocess the pattern and store the last occurrence of every possible character in an array of size equal to alphabet size. If the character is not present at all, then it may result in a shift by m (length of pattern). Therefore, the bad character heuristic takes O(n/m) time in the best case.*/ + +/* Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm */ + +# include +# include +# include + +# define NO_OF_CHARS 256 + +// A utility function to get maximum of two integers +int max(int a, int b) +{ + return (a > b) ? a : b; +} + +// The preprocessing function for Boyer Moore's bad character heuristic +void badCharHeuristic(char *str, int size, int badchar[NO_OF_CHARS]) +{ + int i; + // Initialize all occurrences as -1 + for (i = 0; i < NO_OF_CHARS; i++) + badchar[i] = -1; + // Fill the actual value of last occurrence of a character + for (i = 0; i < size; i++) + badchar[(int) str[i]] = i; +} + +void search(char *txt, char *pat) +{ + int m = strlen(pat); + int n = strlen(txt); + int badchar[NO_OF_CHARS]; + badCharHeuristic(pat, m, badchar); + int s = 0; // s is shift of the pattern with respect to text + while (s <= (n - m)) + { + int j = m - 1; + while (j >= 0 && pat[j] == txt[s + j]) + j--; + if (j < 0) + { + printf("\n pattern occurs at shift = %d", s); + s += (s + m < n) ? m - badchar[txt[s + m]] : 1; + } + else + s += max(1, j - badchar[txt[s + j]]); + } +} + +/* Driver program to test above funtion */ +int main() +{ + char txt[] = "ABAAABCD"; + char pat[] = "ABC"; + search(txt, pat); + return 0; +} + +/* +pattern occurs at shift = 4 diff --git a/c++/Sets_&_Strings/C++ Program to Implement Caesar Cypher.cpp b/c++/Sets_&_Strings/C++ Program to Implement Caesar Cypher.cpp new file mode 100644 index 0000000..c9e2906 --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Implement Caesar Cypher.cpp @@ -0,0 +1,40 @@ +#include +#include +using namespace std; +char caesar(char); +int main() +{ + string input; + do + { + cout << "Enter cipertext and press enter to continue." << endl; + cout << "Enter blank line to quit." << endl; + getline(cin, input); + string output = ""; + for (int x = 0; x < input.length(); x++) + { + output += caesar(input[x]); + } + cout << output << endl; + } + while (!input.length() == 0); +} //end main + +char caesar(char c) +{ + if (isalpha(c)) + { + c = toupper(c); //use upper to keep from having to use two seperate for A..Z a..z + c = (((c - 65) + 13) % 26) + 65; + } + //if c isn't alpha, just send it back. + return c; +} + +/* +Enter cipertext and press enter to continue. +Enter blank line to quit. +Sanfoundry +FNASBHAQEL +Enter cipertext and press enter to continue. +Enter blank line to quit. \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Implement Kadane’s Algorithm.cpp b/c++/Sets_&_Strings/C++ Program to Implement Kadane’s Algorithm.cpp new file mode 100644 index 0000000..9bca56a --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Implement Kadane’s Algorithm.cpp @@ -0,0 +1,39 @@ +#include +#include +using namespace std; + +#define MAX(X, Y) (X > Y) ? X : Y +#define POS(X) (X > 0) ? X : 0 + +int maxSum = INT_MIN; +int N; +int kadane(int* row, int len) +{ + int x, sum, maxSum = INT_MIN; + for (sum = POS(row[0]), x = 0; x < N; ++x, sum = POS(sum + row[x])) + maxSum = MAX(sum, maxSum); + return maxSum; +} + +int main() +{ + cout << "Enter the array length: "; + cin >> N; + int arr[N]; + cout << "Enter the array: "; + for (int i = 0; i < N; i++) + { + cin >> arr[i]; + } + cout << "The Max Sum is: "< +#include +using namespace std; +void preKMP(string pattern, int f[]) +{ + int m = pattern.length(), k; + f[0] = -1; + for (int i = 1; i < m; i++) + { + k = f[i - 1]; + while (k >= 0) + { + if (pattern[k] == pattern[i - 1]) + break; + else + k = f[k]; + } + f[i] = k + 1; + } +} + +//check whether target string contains pattern +bool KMP(string pattern, string target) +{ + int m = pattern.length(); + int n = target.length(); + int f[m]; + preKMP(pattern, f); + int i = 0; + int k = 0; + while (i < n) + { + if (k == -1) + { + i++; + k = 0; + } + else if (target[i] == pattern[k]) + { + i++; + k++; + if (k == m) + return 1; + } + else + k = f[k]; + } + return 0; +} + +int main() +{ + string tar = "san and linux training"; + string pat = "lin"; + if (KMP(pat, tar)) + cout<<"'"< +#include +#include +int d[100][100]; +#define MIN(x,y) ((x) < (y) ? (x) : (y)) +int main() +{ + int i,j,m,n,temp,tracker; + char s[] = "Sanfoundry"; + char t[] = "Education"; + m = strlen(s); + n = strlen(t); + for(i=0; i<=m; i++) + d[0][i] = i; + for(j=0; j<=n; j++) + d[j][0] = j; + for (j=1; j<=m; j++) + { + for(i=1; i<=n; i++) + { + if(s[i-1] == t[j-1]) + { + tracker = 0; + } + else + { + tracker = 1; + } + temp = MIN((d[i-1][j]+1),(d[i][j-1]+1)); + d[i][j] = MIN(temp,(d[i-1][j-1]+tracker)); + } + } + printf("the Levinstein distance is %d\n",d[n][m]); + return 0; +} + +/* + +the Levinstein distance is 9 diff --git a/c++/Sets_&_Strings/C++ Program to Implement Longest Prefix Matching.cpp b/c++/Sets_&_Strings/C++ Program to Implement Longest Prefix Matching.cpp new file mode 100644 index 0000000..dd8a856 --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Implement Longest Prefix Matching.cpp @@ -0,0 +1,120 @@ +/* + * C++ Program to Implement Longest Prefix Matching + */ +#include +#include +#include +#include +using namespace std; + +/* + * node Declaration + */ +struct node +{ + char data; + node *child[128]; + node() + { + for (int i = 0; i < 128; i++) + child[i] = NULL; + } +}; + +/* + * trie class Declaration + */ +class trie +{ +private: + node *root; +public: + trie() + { + root = new_node(0); + } + + node *new_node(int data) + { + node *Q = new node; + Q->data = data; + return Q; + } + + void add(string S) + { + node *cur = root; + for (int i = 0; i < S.length(); i++) + { + if (!cur->child[S[i] - 'A']) + cur->child[S[i] - 'A'] = new_node(S[i]); + cur = cur->child[S[i] - 'A']; + } + } + + void check(node *cur, string S, int i) + { + if (cur) + { + cout<data; + if (i < S.length()) + check(cur->child[S[i] - 'A'], S, i + 1); + } + } + + void checkroot(string S) + { + if (root && S.length() > 0 && S[0] > 'A') + check(root->child[S[0] - 'A'],S,1); + else + cout<<"\nEmpty root \n"; + } +}; + +/* + * Main + */ +int main() +{ + trie dict; + dict.add("are"); + dict.add("area"); + dict.add("base"); + dict.add("cat"); + dict.add("cater"); + dict.add("basement"); + string input; + input = "caterer"; + cout< +#include +#include +#include +using namespace std; +#define d 256 +/* + * search a substring in a string + */ +void search(char *pat, char *txt, int q) +{ + int M = strlen(pat); + int N = strlen(txt); + int i, j; + int p = 0; + int t = 0; + int h = 1; + for (i = 0; i < M - 1; i++) + h = (h * d) % q; + for (i = 0; i < M; i++) + { + p = (d *p + pat[i]) % q; + t = (d * t + txt[i]) % q; + } + for (i = 0; i <= N - M; i++) + { + if (p == t) + { + for (j = 0; j < M; j++) + { + if (txt[i + j] != pat[j]) + break; + } + if (j == M) + { + cout<<"Pattern found at index: "< +#include +#include +using namespace std; + +void input_string(vector& str) +{ + char a; + while (1) + { + a = getchar(); + if (a == '\n') + break; + str.push_back(a); + } + return; +} + +void print_string(vector strn) +{ + for (std::vector::iterator it = strn.begin(); it != strn.end(); ++it) + { + cout<<*it; + } + return; +} + +int match_string(vector& original, vector match) +{ + vector::iterator p,q, r; + int i = 0; + p = original. begin(); + while (r <= match.end() && p <= original.end()) + { + r = match.begin(); + while (*p != *r && p < original.end()) + { + p++; + i++; + } + q = p; + while (*p == *r && r <= match.end() && p<=original.end()) + { + p++; + i++; + r++; + } + if (r >= match.end()) + { + original.erase(original.begin(), q + 1); + return (i - match.size() + 1); + } + if (p >= original.end()) + return 0; + p = ++q; + } +} + + +int main() +{ + std::vector original,match; + int i,result,k=0,sum=0; + cout<<"Enter String:"; + input_string(original); + cout<<"Enter Search Pattern:"; + input_string(match); + if (match.size() > original.size()) + { + cout<<"Error:Original string too small."; + } + do + { + result = match_string(original, match); + sum += result; //to store previous found position + if (result > 0) + { + k++; + cout<<"\nMatch found from Position = "< 0); //loop to find all patterns + if (k == 0) + cout<<"Error:Match Not Found"; + return 0; +} + +/* +Enter String:all men went to apall mall +Enter Search Pattern:all + +Match found from Position = 1 +Match found from Position = 19 +Match found from Position = 24 \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Implement Wagner and Fisher Algorithm for online String Matching.cpp b/c++/Sets_&_Strings/C++ Program to Implement Wagner and Fisher Algorithm for online String Matching.cpp new file mode 100644 index 0000000..509cc4e --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Implement Wagner and Fisher Algorithm for online String Matching.cpp @@ -0,0 +1,41 @@ +/*This is a C++ Program to implement online search. The Wagner–Fischer algorithm is a dynamic programming algorithm that measures the Levenshtein distance between two strings of characters. +For example, the Levenshtein distance between “kitten” and “sitting” is 3, since the following three edits change one into the other, and there is no way to do it with fewer than three edits.*/ + +#include +#include +#include +int d[100][100]; +#define MIN(x,y) ((x) < (y) ? (x) : (y)) +int main() +{ + int i,j,m,n,temp,tracker; + char s[] = "Sanfoundry"; + char t[] = "Education"; + m = strlen(s); + n = strlen(t); + for(i=0; i<=m; i++) + d[0][i] = i; + for(j=0; j<=n; j++) + d[j][0] = j; + for (j=1; j<=m; j++) + { + for(i=1; i<=n; i++) + { + if(s[i-1] == t[j-1]) + { + tracker = 0; + } + else + { + tracker = 1; + } + temp = MIN((d[i-1][j]+1),(d[i][j-1]+1)); + d[i][j] = MIN(temp,(d[i-1][j-1]+tracker)); + } + } + printf("the Levinstein distance is %d\n",d[n][m]); + return 0; +} + +/* +the Levinstein distance is 9 \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Implement Z-Algorithm.cpp b/c++/Sets_&_Strings/C++ Program to Implement Z-Algorithm.cpp new file mode 100644 index 0000000..7e11258 --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Implement Z-Algorithm.cpp @@ -0,0 +1,62 @@ +/* + * C++ Program to Implement Z-Algorithm + */ +#include +#include +#include +using namespace std; +bool zAlgorithm(string pattern, string target) +{ + string s = pattern + '$' + target; + int n = s.length(); + vector z(n, 0); + int goal = pattern.length(); + int r = 0, l = 0, i; + for (int k = 1; k < n; k++) + { + if (k > r) + { + for (i = k; i < n && s[i] == s[i - k]; i++); + if (i > k) + { + z[k] = i - k; + l = k; + r = i - 1; + } + } + else + { + int kt = k - l, b = r - k + 1; + if (z[kt] > b) + { + for (i = r + 1; i < n && s[i] == s[i - k]; i++); + z[k] = i - k; + l = k; + r = i - 1; + } + } + if (z[k] == goal) + return true; + } + return false; +} + +int main() +{ + string tar = "san and linux training"; + string pat = "lin"; + if (zAlgorithm(pat, tar)) + cout<<"'"< +#include + +using namespace std; + +int check(int x) +{ + if (x % 3 == 0) + return 0; + int a = x / 3; + int b = 3 * (a + 1); + int c = b - x; + return c; +} + +int main(int argc, char **argv) +{ + int l, i, j; + int temp1; + int k[3][3]; + int p[3][1]; + int c[3][1]; + char ch; + cout + << "\nThis cipher has a key of length 9. ie. a 3*3 matrix.\nEnter the 9 character key. "; + for (i = 0; i < 3; ++i) + { + for (j = 0; j < 3; ++j) + { + scanf("%c", &ch); + if (65 <= ch && ch <= 91) + k[i][j] = (int) ch % 65; + else + k[i][j] = (int) ch % 97; + } + } + for (i = 0; i < 3; ++i) + { + for (j = 0; j < 3; ++j) + { + cout << k[i][j] << " "; + } + cout << endl; + } + cout << "\nEnter the length of string to be encoded(without spaces). "; + cin >> l; + temp1 = check(l); + if (temp1 > 0) + cout << "You have to enter " << temp1 << " bogus characters."; + char pi[l + temp1]; + cout << "\nEnter the string. "; + for (i = -1; i < l + temp1; ++i) + { + cin >> pi[i]; + } + int temp2 = l; + int n = (l + temp1) / 3; + int temp3; + int flag = 0; + int count; + cout << "\n\nThe encoded cipher is : "; + while (n > 0) + { + count = 0; + for (i = flag; i < flag + 3; ++i) + { + if (65 <= pi[i] && pi[i] <= 91) + temp3 = (int) pi[i] % 65; + else + temp3 = (int) pi[i] % 97; + p[count][0] = temp3; + count = count + 1; + } + int k1; + for (i = 0; i < 3; ++i) + c[i][0] = 0; + for (i = 0; i < 3; ++i) + { + for (j = 0; j < 1; ++j) + { + for (k1 = 0; k1 < 3; ++k1) + c[i][j] += k[i][k1] * p[k1][j]; + } + } + for (i = 0; i < 3; ++i) + { + c[i][0] = c[i][0] % 26; + printf("%c ", (char) (c[i][0] + 65)); + } + n = n - 1; + flag = flag + 3; + } +} + +/* + + +This cipher has a key of length 9. ie. a 3*3 matrix. +Enter the 9 character key. DharHingu +3 7 0 +17 7 8 +13 6 20 + +Enter the length of string to be encoded(without spaces). 10 +You have to enter 2 bogus characters. +Enter the string. Sanfoundry + +The encoded cipher is : N B W A O Q Y Y X X D O \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Implement the Monoalphabetic Cypher.cpp b/c++/Sets_&_Strings/C++ Program to Implement the Monoalphabetic Cypher.cpp new file mode 100644 index 0000000..a17128d --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Implement the Monoalphabetic Cypher.cpp @@ -0,0 +1,88 @@ +/*This is a C++ Program to implement monoalphaetic cipher. In cryptography, a substitution cipher is a method of encoding by which units of plaintext are replaced with ciphertext, according to a regular system; the “units” may be single letters (the most common), pairs of letters, triplets of letters, mixtures of the above, and so forth. The receiver deciphers the text by performing an inverse substitution. +Substitution ciphers can be compared with transposition ciphers. In a transposition cipher, the units of the plaintext are rearranged in a different and usually quite complex order, but the units themselves are left unchanged. By contrast, in a substitution cipher, the units of the plaintext are retained in the same sequence in the ciphertext, but the units themselves are altered. + +There are a number of different types of substitution cipher. If the cipher operates on single letters, it is termed a simple substitution cipher; a cipher that operates on larger groups of letters is termed polygraphic. A monoalphabetic cipher uses fixed substitution over the entire message, whereas a polyalphabetic cipher uses a number of substitutions at different positions in the message, where a unit from the plaintext is mapped to one of several possibilities in the ciphertext and vice versa.*/ + +#include +#include +#include +#include +#include +#include + +// the rot13 function +std::string rot13(std::string s) +{ + static std::string const lcalph = "abcdefghijklmnopqrstuvwxyz", ucalph = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + std::string result; + std::string::size_type pos; + result.reserve(s.length()); + for (std::string::iterator it = s.begin(); it != s.end(); ++it) + { + if ((pos = lcalph.find(*it)) != std::string::npos) + result.push_back(lcalph[(pos + 13) % 26]); + else if ((pos = ucalph.find(*it)) != std::string::npos) + result.push_back(ucalph[(pos + 13) % 26]); + else + result.push_back(*it); + } + return result; +} + +// function to output the rot13 of a file on std::cout +// returns false if an error occurred processing the file, true otherwise +// on entry, the argument is must be open for reading +int rot13_stream(std::istream& is) +{ + std::string line; + while (std::getline(is, line)) + { + if (!(std::cout << rot13(line) << "\n")) + return false; + } + return is.eof(); +} + +// the main program +int main(int argc, char* argv[]) +{ + if (argc == 1) // no arguments given + return rot13_stream(std::cin) ? EXIT_SUCCESS : EXIT_FAILURE; + std::ifstream file; + for (int i = 1; i < argc; ++i) + { + file.open(argv[i], std::ios::in); + if (!file) + { + std::cerr << argv[0] << ": could not open for reading: " << argv[i] + << "\n"; + return EXIT_FAILURE; + } + if (!rot13_stream(file)) + { + if (file.eof()) + // no error occurred for file, so the error must have been in output + std::cerr << argv[0] << ": error writing to stdout\n"; + else + std::cerr << argv[0] << ": error reading from " << argv[i] + << "\n"; + return EXIT_FAILURE; + } + file.clear(); + file.close(); + if (!file) + std::cerr << argv[0] << ": warning: closing failed for " << argv[i] + << "\n"; + } + return EXIT_SUCCESS; +} + +/* + +Dharmendra +Qunezraqen +Hingu +Uvath +Sanfoundry +Fnasbhaqel \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Implement the One Time Pad Algorithm.cpp b/c++/Sets_&_Strings/C++ Program to Implement the One Time Pad Algorithm.cpp new file mode 100644 index 0000000..3b60cf2 --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Implement the One Time Pad Algorithm.cpp @@ -0,0 +1,92 @@ +/*This C++ program encodes any message using the technique of one time pad cipher technique. Input is not case sensitive and works only for all characters. White spaces are not ignored but are produced as random characters in the decoded message. +Note:Since the key is required for decryption, it is printed on stdout. However, it is not safe to make the key public.*/ + +/* + * C++ Program to Implement the One Time Pad Algorithm. + */ +#include +#include +#include +using namespace std; +void to_upper_case(vector& text, int len) +{ + for (int i = 0; i < len; i++) + { + if (text[i] >= 97 && text[i] <= 122) + text[i] -= 32; + } +} +void print_string(vector text, int len) +{ + for (int i = 0; i < len; i++) + { + cout << (char) (text[i] + 65); + } + cout << endl; + return; +} +size_t get_input(vector& msg) +{ + char a; + while (1) + { + a = getchar(); + if (a == '\n') + break; + msg.push_back(a); + } + return msg.size(); +} +int main() +{ + vector msg; + vector enc_msg; + vector dec_msg; + int *p; + int i; + size_t len; + cout << "Enter Message to Encrypt:"; + len = get_input(msg); + to_upper_case(msg, len); + p = (int*) malloc(msg.size() * sizeof(int)); + for (i = 0; i < len; i++) + { + p[i] = rand() % 26; + if (msg[i] >= 65 && msg[i] <= 90) + enc_msg.push_back((char) ((msg[i] - 65 + p[i]) % 26)); + else if (msg[i] >= 97 && msg[i] <= 122) + enc_msg.push_back((char) ((msg[i] - 97 + p[i]) % 26)); + else + enc_msg.push_back((char) msg[i]); + } + cout << "\nEncoded Message:"; + print_string(enc_msg, len); + cout << "\nKey for decryption:\n"; + for (i = 0; i < len; i++) + { + cout << (char) (p[i] + 65); + } + cout << endl; + cout << "\nDecrypted Message:"; + for (i = 0; i < len; i++) + { + if ((enc_msg[i] - p[i]) < 0) + dec_msg.push_back((char) (enc_msg[i] - p[i] + 26)); + else if ((enc_msg[i] - p[i]) >= 0) + dec_msg.push_back((char) (enc_msg[i] - p[i])); + else + dec_msg.push_back((char) enc_msg[i]); + } + print_string(dec_msg, len); + return 0; +} + + +/* +Enter Message to Encrypt: This is the demonstration of OTP algorithm +Encoded Message:IOYYaCEaTFPaOJPLSAKTVLKLTaPBaTGFaUICTENHGH + +Key for decryption: +PHQGHUMEAYLNLFDXFIRCVSCXGGBWKFNQDUXWFNFOZV + +Decrypted Message:THISZIS]THETDEMONSTRATION[OFWOTP^ALGORITHM \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Implement the RSA Algorithm.cpp b/c++/Sets_&_Strings/C++ Program to Implement the RSA Algorithm.cpp new file mode 100644 index 0000000..d5ef55d --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Implement the RSA Algorithm.cpp @@ -0,0 +1,183 @@ +/*This C++ program encodes any message using RSA Algorithm. Input is case sensitive and works only for all characters. RSA is one of the first practicable public-key cryptosystems and is widely used for secure data transmission. In such a cryptosystem, the encryption key is public and differs from the decryption key which is kept secret. In RSA, this asymmetry is based on the practical difficulty of factoring the product of two large prime numbers, the factoring problem. RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman.*/ + +/* + * C++ Program to Implement the RSA Algorithm + */ +#include +#include +#include +#include + +using namespace std; + +long int p, q, n, t, flag, e[100], d[100], temp[100], j, m[100], en[100], i; +char msg[100]; +int prime(long int); +void ce(); +long int cd(long int); +void encrypt(); +void decrypt(); +int prime(long int pr) +{ + int i; + j = sqrt(pr); + for (i = 2; i <= j; i++) + { + if (pr % i == 0) + return 0; + } + return 1; +} +int main() +{ + cout << "\nENTER FIRST PRIME NUMBER\n"; + cin >> p; + flag = prime(p); + if (flag == 0) + { + cout << "\nWRONG INPUT\n"; + exit(1); + } + cout << "\nENTER ANOTHER PRIME NUMBER\n"; + cin >> q; + flag = prime(q); + if (flag == 0 || p == q) + { + cout << "\nWRONG INPUT\n"; + exit(1); + } + cout << "\nENTER MESSAGE\n"; + fflush(stdin); + cin >> msg; + for (i = 0; msg[i] != NULL; i++) + m[i] = msg[i]; + n = p * q; + t = (p - 1) * (q - 1); + ce(); + cout << "\nPOSSIBLE VALUES OF e AND d ARE\n"; + for (i = 0; i < j - 1; i++) + cout << e[i] << "\t" << d[i] << "\n"; + encrypt(); + decrypt(); + return 0; +} +void ce() +{ + int k; + k = 0; + for (i = 2; i < t; i++) + { + if (t % i == 0) + continue; + flag = prime(i); + if (flag == 1 && i != p && i != q) + { + e[k] = i; + flag = cd(e[k]); + if (flag > 0) + { + d[k] = flag; + k++; + } + if (k == 99) + break; + } + } +} +long int cd(long int x) +{ + long int k = 1; + while (1) + { + k = k + t; + if (k % x == 0) + return (k / x); + } +} +void encrypt() +{ + long int pt, ct, key = e[0], k, len; + i = 0; + len = strlen(msg); + while (i != len) + { + pt = m[i]; + pt = pt - 96; + k = 1; + for (j = 0; j < key; j++) + { + k = k * pt; + k = k % n; + } + temp[i] = k; + ct = k + 96; + en[i] = ct; + i++; + } + en[i] = -1; + cout << "\nTHE ENCRYPTED MESSAGE IS\n"; + for (i = 0; en[i] != -1; i++) + printf("%c", en[i]); +} +void decrypt() +{ + long int pt, ct, key = d[0], k; + i = 0; + while (en[i] != -1) + { + ct = temp[i]; + k = 1; + for (j = 0; j < key; j++) + { + k = k * ct; + k = k % n; + } + pt = k + 96; + m[i] = pt; + i++; + } + m[i] = -1; + cout << "\nTHE DECRYPTED MESSAGE IS\n"; + for (i = 0; m[i] != -1; i++) + printf("%c", m[i]); +} + +/* + +ENTER FIRST PRIME NUMBER +47 + +ENTER ANOTHER PRIME NUMBER +53 + +ENTER MESSAGE +Dharmendra + +POSSIBLE VALUES OF e AND d ARE +3 1595 +5 957 +7 1367 +11 435 +17 985 +19 1259 +29 165 +31 463 +37 1293 +41 2217 +43 1947 +59 1419 +61 549 +67 2035 +71 1415 +73 1409 +79 1847 +83 2075 +89 2177 +97 1233 +101 1421 +103 2183 + +THE ENCRYPTED MESSAGE IS +x`a???]??a +THE DECRYPTED MESSAGE IS +Dharmendra \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Implement the String Search Algorithm for Short Text Sizes.cpp b/c++/Sets_&_Strings/C++ Program to Implement the String Search Algorithm for Short Text Sizes.cpp new file mode 100644 index 0000000..72d2fb0 --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Implement the String Search Algorithm for Short Text Sizes.cpp @@ -0,0 +1,52 @@ +/* + * C++ Program to Implement the String Search Algorithm for + * Short Text Sizes + */ + +//enter string without spaces +#include +using namespace std; + +int main() +{ + char org[100], dup[100]; + int i, j, k = 0, len_org, len_dup; + cout<<"NOTE:Strings are accepted only till blank space."; + cout<<"\nEnter Original String:"; + fflush(stdin); + cin>>org; + fflush(stdin); + cout<<"Enter Pattern to Search:"; + cin>>dup; + len_org = strlen(org); + len_dup = strlen(dup); + for (i = 0; i <= (len_org - len_dup); i++) + { + for (j = 0; j < len_dup; j++) + { + //cout<<"comparing '"< +#include + +void cipher(int i, int c); +int findMin(); +void makeArray(int, int); + +char arr[22][22], darr[22][22], emessage[111], retmessage[111], key[55]; +char temp[55], temp2[55]; +int k = 0; + +int main() +{ + char *message; + int i, j, klen, emlen, flag = 0; + int r, c, index, rows; + printf("Enter the key\n"); + fflush(stdin); + gets(key); + printf("\nEnter message to be ciphered\n"); + fflush(stdin); + gets(message); + strcpy(temp, key); + klen = strlen(key); + k = 0; + for (i = 0;; i++) + { + if (flag == 1) + break; + for (j = 0; key[j] != NULL; j++) + { + if (message[k] == NULL) + { + flag = 1; + arr[i][j] = '-'; + } + else + { + arr[i][j] = message[k++]; + } + } + } + r = i; + c = j; + for (i = 0; i < r; i++) + { + for (j = 0; j < c; j++) + { + printf("%c ", arr[i][j]); + } + printf("\n"); + } + k = 0; + for (i = 0; i < klen; i++) + { + index = findMin(); + cipher(index, r); + } + emessage[k] = '\0'; + printf("\nEncrypted message is\n"); + for (i = 0; emessage[i] != NULL; i++) + printf("%c", emessage[i]); + printf("\n\n"); + //deciphering + emlen = strlen(emessage); + //emlen is length of encrypted message + strcpy(temp, key); + rows = emlen / klen; + //rows is no of row of the array to made from ciphered message + j = 0; + for (i = 0, k = 1; emessage[i] != NULL; i++, k++) + { + //printf("\nEmlen=%d",emlen); + temp2[j++] = emessage[i]; + if ((k % rows) == 0) + { + temp2[j] = '\0'; + index = findMin(); + makeArray(index, rows); + j = 0; + } + } + printf("\nArray Retrieved is\n"); + k = 0; + for (i = 0; i < r; i++) + { + for (j = 0; j < c; j++) + { + printf("%c ", darr[i][j]); + //retrieving message + retmessage[k++] = darr[i][j]; + } + printf("\n"); + } + retmessage[k] = '\0'; + printf("\nMessage retrieved is\n"); + for (i = 0; retmessage[i] != NULL; i++) + printf("%c", retmessage[i]); + return (0); +} + +void cipher(int i, int r) +{ + int j; + for (j = 0; j < r; j++) + { + { + emessage[k++] = arr[j][i]; + } + } + // emessage[k]='\0'; +} + +void makeArray(int col, int row) +{ + int i, j; + for (i = 0; i < row; i++) + { + darr[i][col] = temp2[i]; + } +} + +int findMin() +{ + int i, j, min, index; + min = temp[0]; + index = 0; + for (j = 0; temp[j] != NULL; j++) + { + if (temp[j] < min) + { + min = temp[j]; + index = j; + } + } + temp[index] = 123; + return (index); +} + +/* + +Enter the key +hello + +Enter the message to be ciphered +how are you + +h o w a +r e y o +u - - - - + +Encrypted message is +oe-hruw - y-ao- + +Array Retrieved is +h o w a +r e y o +u - - - - + +Message retrieved is +how are you---- \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Perform Finite State Automaton based Search.cpp b/c++/Sets_&_Strings/C++ Program to Perform Finite State Automaton based Search.cpp new file mode 100644 index 0000000..261def4 --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Perform Finite State Automaton based Search.cpp @@ -0,0 +1,74 @@ +#include +#include +#define NO_OF_CHARS 256 + +int getNextState(char *pat, int M, int state, int x) +{ + // If the character c is same as next character in pattern, + // then simply increment state + if (state < M && x == pat[state]) + return state + 1; + int ns, i; // ns stores the result which is next state + // ns finally contains the longest prefix which is also suffix + // in "pat[0..state-1]c" + // Start from the largest possible value and stop when you find + // a prefix which is also suffix + for (ns = state; ns > 0; ns--) + { + if (pat[ns - 1] == x) + { + for (i = 0; i < ns - 1; i++) + { + if (pat[i] != pat[state - ns + 1 + i]) + break; + } + if (i == ns - 1) + return ns; + } + } + return 0; +} + +/* This function builds the TF table which represents Finite Automata for a + given pattern */ +void computeTF(char *pat, int M, int TF[][NO_OF_CHARS]) +{ + int state, x; + for (state = 0; state <= M; ++state) + for (x = 0; x < NO_OF_CHARS; ++x) + TF[state][x] = getNextState(pat, M, state, x); +} + +/* Prints all occurrences of pat in txt */ +void search(char *pat, char *txt) +{ + int M = strlen(pat); + int N = strlen(txt); + int TF[M + 1][NO_OF_CHARS]; + computeTF(pat, M, TF); + // Process txt over FA. + int i, state = 0; + for (i = 0; i < N; i++) + { + state = TF[state][txt[i]]; + if (state == M) + { + printf("\n pattern found at index %d", i - M + 1); + } + } +} + +// Driver program to test above function +int main() +{ + char *txt = "AABAACAADAABAAABAA"; + char *pat = "AABA"; + search(pat, txt); + return 0; +} + +/* + pattern found at index 0 + pattern found at index 9 + pattern found at index 13 +------------------ \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Perform Naive String Matching.cpp b/c++/Sets_&_Strings/C++ Program to Perform Naive String Matching.cpp new file mode 100644 index 0000000..c63aa32 --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Perform Naive String Matching.cpp @@ -0,0 +1,38 @@ +/*This is a C++ Program to perform Naive String matching algorithm. In computer science, string searching algorithms, sometimes called string matching algorithms, are an important class of string algorithms that try to find a place where one or several strings (also called patterns) are found within a larger string or text.*/ + +#include +#include +void search(char *pat, char *txt) +{ + int M = strlen(pat); + int N = strlen(txt); + /* A loop to slide pat[] one by one */ + for (int i = 0; i <= N - M; i++) + { + int j; + /* For current index i, check for pattern match */ + for (j = 0; j < M; j++) + { + if (txt[i + j] != pat[j]) + break; + } + if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] + { + printf("Pattern found at index %d \n", i); + } + } +} + +/* Driver program to test above function */ +int main() +{ + char *txt = "AABAACAADAABAAABAA"; + char *pat = "AABA"; + search(pat, txt); + return 0; +} + +/* +Pattern found at index 0 +Pattern found at index 9 +Pattern found at index 13 \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Perform String Matching Using String Library.cpp b/c++/Sets_&_Strings/C++ Program to Perform String Matching Using String Library.cpp new file mode 100644 index 0000000..d784039 --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Perform String Matching Using String Library.cpp @@ -0,0 +1,32 @@ +/* + * C++ Program to Perform String Matching Using String Library + */ + +#include +#include +using namespace std; +int main() +{ + std::string org, dup; + int result = -1, i = 1; + std::cout<<"Enter Original String:"; + getline(std::cin, org); + std::cout<<"Enter Pattern String:"; + getline(std::cin, dup); + do + { + result = org.find(dup, result + 1); + if (result != -1) + std::cout<<"\nInstance:"<= 0); + return 0; +} + +/* +Enter Original String:All men went to the appall mall +Enter Pattern String:all + +Instance:1 Position:23 +Instance:2 Position:28 \ No newline at end of file diff --git a/c++/Sets_&_Strings/C++ Program to Repeatedly Search the Same Text (such as Bible by building a Data Structure).cpp b/c++/Sets_&_Strings/C++ Program to Repeatedly Search the Same Text (such as Bible by building a Data Structure).cpp new file mode 100644 index 0000000..df96ad5 --- /dev/null +++ b/c++/Sets_&_Strings/C++ Program to Repeatedly Search the Same Text (such as Bible by building a Data Structure).cpp @@ -0,0 +1,49 @@ +//enter string without spaces +#include +#include +using namespace std; + +int main() +{ + char org[100], dup[100]; + int i, j, k = 0, len_org, len_dup; + cout << "NOTE:Strings are accepted only till blank space."; + cout << "\nEnter Original String:"; + fflush(stdin); + cin >> org; + fflush(stdin); + cout << "Enter Pattern to Search:"; + cin >> dup; + len_org = strlen(org); + len_dup = strlen(dup); + for (i = 0; i <= (len_org - len_dup); i++) + { + for (j = 0; j < len_dup; j++) + { + //cout<<"comparing '"< 0) + { + Console.WriteLine("Number is positive"); + } + else if (number == 0) + { + Console.WriteLine("Number is 0"); + } + else + { + Console.WriteLine("Number is negative"); + } + Console.ReadLine(); + } +} + +/* +Enter a Number : -4 +Number is Negative \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Accept the Height of a Person & Categorize as Tall, Dwarf or Average.cs b/c-sharp/Basic/C# Program to Accept the Height of a Person & Categorize as Tall, Dwarf or Average.cs new file mode 100644 index 0000000..43eaf08 --- /dev/null +++ b/c-sharp/Basic/C# Program to Accept the Height of a Person & Categorize as Tall, Dwarf or Average.cs @@ -0,0 +1,27 @@ +/* + * C# Program to Accept the Height of a Person & Categorize as + * Tall, Dwarf or Average + */ +using System; +class program +{ + public static void Main() + { + float height; + Console.WriteLine("Enter the Height (in centimeters) \n"); + height = int.Parse(Console.ReadLine()); + if (height < 150.0) + Console.WriteLine("Dwarf \n"); + else if ((height >= 150.0) && (height <= 165.0)) + Console.WriteLine(" Average Height \n"); + else if ((height >= 165.0) && (height <= 195.0)) + Console.WriteLine("Taller \n"); + else + Console.WriteLine("Abnormal height \n"); + } +} + +/* +Enter the Height (in centimeters) +165 + Average Height \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Calculate Acceleration.cs b/c-sharp/Basic/C# Program to Calculate Acceleration.cs new file mode 100644 index 0000000..25719e7 --- /dev/null +++ b/c-sharp/Basic/C# Program to Calculate Acceleration.cs @@ -0,0 +1,23 @@ +/* + * C# Program to Calculate Acceleration +using System; +class program +{ + static void Main(string[] args) + { + int v, t, acc; + Console.WriteLine("Enter the Velocity : "); + v = int.Parse(Console.ReadLine()); + Console.WriteLine("Enter the Time : "); + t = int.Parse(Console.ReadLine()); + acc = v / t; + Console.WriteLine("Acceleration : {0}", acc); + } +} + +/* +Enter the Velocity : +10 +Enter the Time : +2 +Acceleration : 5 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Check Whether the Entered Year is a Leap Year or Not.cs b/c-sharp/Basic/C# Program to Check Whether the Entered Year is a Leap Year or Not.cs new file mode 100644 index 0000000..d0220a2 --- /dev/null +++ b/c-sharp/Basic/C# Program to Check Whether the Entered Year is a Leap Year or Not.cs @@ -0,0 +1,42 @@ +/* + * C# Program to Check Whether the Entered Year is a Leap Year or Not + */ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Program +{ +class leapyear +{ + static void Main(string[] args) + { + leapyear obj = new leapyear(); + obj.readdata(); + obj.leap(); + } + int y; + public void readdata() + { + Console.WriteLine("Enter the Year in Four Digits : "); + y = Convert.ToInt32(Console.ReadLine()); + } + public void leap() + { + if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) + { + Console.WriteLine("{0} is a Leap Year", y); + } + else + { + Console.WriteLine("{0} is not a Leap Year", y); + } + Console.ReadLine(); + } +} +} + +/* +Enter the Year in Four Digits : 1004 +1004 is a Leap Year \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Check whether the Entered Number is Even or Odd.cs b/c-sharp/Basic/C# Program to Check whether the Entered Number is Even or Odd.cs new file mode 100644 index 0000000..ccfb25d --- /dev/null +++ b/c-sharp/Basic/C# Program to Check whether the Entered Number is Even or Odd.cs @@ -0,0 +1,34 @@ +/* + * C# Program to Check whether the Entered Number is Even or Odd + */ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace check1 +{ +class Program +{ + static void Main(string[] args) + { + int i; + Console.Write("Enter a Number : "); + i = int.Parse(Console.ReadLine()); + if (i % 2 == 0) + { + Console.Write("Entered Number is an Even Number"); + Console.Read(); + } + else + { + Console.Write("Entered Number is an Odd Number"); + Console.Read(); + } + } +} +} + +/* +Enter a Number : 25 +Entered Number is an Odd Number \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Check whether the given Integer has an Alternate Pattern.cs b/c-sharp/Basic/C# Program to Check whether the given Integer has an Alternate Pattern.cs new file mode 100644 index 0000000..0f19804 --- /dev/null +++ b/c-sharp/Basic/C# Program to Check whether the given Integer has an Alternate Pattern.cs @@ -0,0 +1,45 @@ +/* + * C# Program to Check whether the given Integer has an + * Alternate Pattern + */ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +class program +{ + public static void Main() + { + int num, x, y, count = 0; + Console.WriteLine("Enter the Number:"); + num = int.Parse(Console.ReadLine()); + x = num << 1; + y = x ^ num; + y = y + 1; + while ((y / 2) != 0) + { + if (y % 2 != 0) + { + count++; + break; + } + else + { + y = y / 2; + } + } + if (count == 1) + { + Console.WriteLine("false"); + } + else + { + Console.WriteLine("true"); + } + Console.Read(); + } +} + +/* +Enter the Number: 100 +false \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Compare Two Dates.cs b/c-sharp/Basic/C# Program to Compare Two Dates.cs new file mode 100644 index 0000000..ab6a902 --- /dev/null +++ b/c-sharp/Basic/C# Program to Compare Two Dates.cs @@ -0,0 +1,26 @@ +/* + * C# Program to Campare Two Dates + */ +using System; +namespace DateAndTime +{ +class Program +{ + static int Main() + { + DateTime sd = new DateTime(2010, 10, 12); + Console.WriteLine("Starting Date : {0}", sd); + DateTime ed = sd.AddDays(10); + Console.WriteLine("Ending Date : {0}", ed); + if (sd < ed) + Console.WriteLine("{0} Occurs Before {1}", sd, ed); + Console.Read(); + return 0; + } +} +} + +/* +Starting Date : 10/11/2010 12:00:00 AM +Ending Date : 10/21/2010 12:00:00 AM +10/11/2010 12:00:00 Am Occurs Before 10/21/2010 12:00:00 AM \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Compute Average for the Set of Values.cs b/c-sharp/Basic/C# Program to Compute Average for the Set of Values.cs new file mode 100644 index 0000000..026f551 --- /dev/null +++ b/c-sharp/Basic/C# Program to Compute Average for the Set of Values.cs @@ -0,0 +1,35 @@ +/* + * C# Program to Compute Average for the Set of Values + */ +using System; +class program +{ + public static void Main() + { + int m, i, sum = 0, avg = 0; + Console.WriteLine("Enter the Number of Terms in the Array "); + m = int.Parse(Console.ReadLine()); + int[] a = new int[m]; + Console.WriteLine("Enter the Array Elements "); + for (i = 0; i < m; i++) + { + a[i] = int.Parse(Console.ReadLine()); + } + for (i = 0; i < m; i++) + { + sum += a[i]; + } + avg = sum / m; + Console.WriteLine("Average is {0}", avg); + Console.ReadLine(); + } +} + +/* +Enter the Number of Terms in the Array : 4 +Enter the Elements +1 +2 +3 +4 +Average is 2 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Count the Number of 1’s in the Entered Number.cs b/c-sharp/Basic/C# Program to Count the Number of 1’s in the Entered Number.cs new file mode 100644 index 0000000..60c4b5c --- /dev/null +++ b/c-sharp/Basic/C# Program to Count the Number of 1’s in the Entered Number.cs @@ -0,0 +1,46 @@ +/* + * C# Program to Count the Number of 1's in the Entered Number + */ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace ConsoleApplication16 +{ +class Program +{ + static void Main(string[] args) + { + int m, count = 0; + Console.WriteLine("Enter the Limit : "); + m = int.Parse(Console.ReadLine()); + int[] a = new int[m]; + Console.WriteLine("Enter the Numbers :"); + for (int i = 0; i < m; i++) + { + a[i] = Convert.ToInt32(Console.ReadLine()); + } + foreach (int o in a) + { + if (o == 1) + { + count++; + } + } + Console.WriteLine("Number of 1's in the Entered Number : "); + Console.WriteLine(count); + Console.ReadLine(); + } +} +} + +/* +Enter the Limit : 5 +Enter the Numbers : +1 +2 +1 +4 +1 +Number of 1's in the Entered Number : 3 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Create Sealed Class.cs b/c-sharp/Basic/C# Program to Create Sealed Class.cs new file mode 100644 index 0000000..6dd6481 --- /dev/null +++ b/c-sharp/Basic/C# Program to Create Sealed Class.cs @@ -0,0 +1,24 @@ +/* + * C# Program to Create Sealed Class + */ +using System; +sealed class SealedClass +{ + public int x; + public int y; +} + +class SealedTest +{ + static void Main() + { + SealedClass sc = new SealedClass(); + sc.x = 100; + sc.y = 180; + Console.WriteLine("x = {0}, y = {1}", sc.x, sc.y); + Console.ReadLine(); + } +} + +/* +x = 100 ,y = 180 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Display All the Prime Numbers Between 1 to 100.cs b/c-sharp/Basic/C# Program to Display All the Prime Numbers Between 1 to 100.cs new file mode 100644 index 0000000..64c7c9a --- /dev/null +++ b/c-sharp/Basic/C# Program to Display All the Prime Numbers Between 1 to 100.cs @@ -0,0 +1,41 @@ +/* + * C# Program to Display All the Prime Numbers Between 1 to 100 + */ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +namespace PrimeNumber +{ +class Program +{ + static void Main(string[] args) + { + bool isPrime = true; + Console.WriteLine("Prime Numbers : "); + for (int i = 2; i <= 100; i++) + { + for (int j = 2; j <= 100; j++) + { + if (i != j && i % j == 0) + { + isPrime = false; + break; + } + } + if (isPrime) + { + Console.Write("\t" +i); + } + isPrime = true; + } + Console.ReadKey(); + } +} +} + +/* +Prime Numbers : + 2 3 5 7 11 13 17 19 23 29 +31 37 41 43 47 53 59 61 67 71 +73 79 83 89 97 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Display Numbers in the form of Triangle.cs b/c-sharp/Basic/C# Program to Display Numbers in the form of Triangle.cs new file mode 100644 index 0000000..3f3c88e --- /dev/null +++ b/c-sharp/Basic/C# Program to Display Numbers in the form of Triangle.cs @@ -0,0 +1,42 @@ +/* + * C# Program to Display Numbers in the form of Triangle + */ +using System; +class Pascal +{ + public static void Main() + { + int[,] arr = new int[8, 8]; + for (int i = 0; i < 8; i++) + { + for (int k = 7; k > i; k--) + { + //For loop to print spaces + Console.Write(" "); + } + for (int j = 0; j < i; j++) + { + if (j == 0 || i == j) + { + arr[i, j] = 1; + } + else + { + arr[i, j] = arr[i - 1, j] + arr[i - 1, j - 1]; + } + Console.Write(arr[i, j] + " "); + } + Console.WriteLine(); + } + Console.ReadLine(); + } +} + +/* + 1 + 1 1 + 1 2 1 + 1 3 3 1 + 1 4 6 4 1 + 1 5 10 10 5 1 +1 6 15 20 15 6 1 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Display Squarefeet of a House.cs b/c-sharp/Basic/C# Program to Display Squarefeet of a House.cs new file mode 100644 index 0000000..41418c6 --- /dev/null +++ b/c-sharp/Basic/C# Program to Display Squarefeet of a House.cs @@ -0,0 +1,23 @@ +/* + * C# Program to Display Squarefeet of a House + */ +using System; +class pgm +{ + public static void Main() + { + int length, width, area; + Console.Write ("Enter length of room in feet: "); + length = Convert.ToInt32 (Console.ReadLine()); + Console.Write ( "Enter width of room in feet:"); + width = Convert.ToInt32(Console.ReadLine()); + area = length * width; + Console.WriteLine ("Floor is " + area + " square feet."); + Console.ReadLine(); + } +} + +/* +Enter Length of Room in Feet : 20 +Enter width of Room in Feet : 20 +Floor is 400 square feet. \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Display the ATM Transaction.cs b/c-sharp/Basic/C# Program to Display the ATM Transaction.cs new file mode 100644 index 0000000..12e1bed --- /dev/null +++ b/c-sharp/Basic/C# Program to Display the ATM Transaction.cs @@ -0,0 +1,77 @@ +/* + * C# Program to Display the ATM Transaction + */ +using System; +class program +{ + public static void Main() + { + int amount = 1000, deposit, withdraw; + int choice, pin = 0, x = 0; + Console.WriteLine("Enter Your Pin Number "); + pin = int.Parse(Console.ReadLine()); + while (true) + { + Console.WriteLine("********Welcome to ATM Service**************\n"); + Console.WriteLine("1. Check Balance\n"); + Console.WriteLine("2. Withdraw Cash\n"); + Console.WriteLine("3. Deposit Cash\n"); + Console.WriteLine("4. Quit\n"); + Console.WriteLine("*********************************************\n\n"); + Console.WriteLine("Enter your choice: "); + choice = int.Parse(Console.ReadLine()); + switch (choice) + { + case 1: + Console.WriteLine("\n YOUR BALANCE IN Rs : {0} ", amount); + break; + case 2: + Console.WriteLine("\n ENTER THE AMOUNT TO WITHDRAW: "); + withdraw = int.Parse(Console.ReadLine()); + if (withdraw % 100 != 0) + { + Console.WriteLine("\n PLEASE ENTER THE AMOUNT IN MULTIPLES OF 100"); + } + else if (withdraw > (amount - 500)) + { + Console.WriteLine("\n INSUFFICENT BALANCE"); + } + else + { + amount = amount - withdraw; + Console.WriteLine("\n\n PLEASE COLLECT CASH"); + Console.WriteLine("\n YOUR CURRENT BALANCE IS {0}", amount); + } + break; + case 3: + Console.WriteLine("\n ENTER THE AMOUNT TO DEPOSIT"); + deposit = int.Parse(Console.ReadLine()); + amount = amount + deposit; + Console.WriteLine("YOUR BALANCE IS {0}", amount); + break; + case 4: + Console.WriteLine("\n THANK U USING ATM"); + break; + } + } + Console.WriteLine("\n\n THANKS FOR USING OUT ATM SERVICE"); + } +} + +/* +Enter Your Pin Number +123 +********Welcome to ATM Service************** + +1. Check Balance + +2. Withdraw Cash + +3. Deposit Cash + +4. Quit + +********************************************* +Enter your choice: +1 +YOUR BALANCE IN Rs : 1000 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Display the Date in Various Formats.cs b/c-sharp/Basic/C# Program to Display the Date in Various Formats.cs new file mode 100644 index 0000000..3d3e761 --- /dev/null +++ b/c-sharp/Basic/C# Program to Display the Date in Various Formats.cs @@ -0,0 +1,36 @@ +/* + * C# Program to Display the Date in Various Formats + */ +using System; +namespace DateAndTime +{ +class Program +{ + static int Main() + { + DateTime date = new DateTime(2013,6, 23); + Console.WriteLine("Some Date Formats : "); + Console.WriteLine("Date and Time: {0}", date); + Console.WriteLine(date.ToString("yyyy-MM-dd")); + Console.WriteLine(date.ToString("dd-MMM-yy")); + Console.WriteLine(date.ToString("M/d/yyyy")); + Console.WriteLine(date.ToString("M/d/yy")); + Console.WriteLine(date.ToString("MM/dd/yyyy")); + Console.WriteLine(date.ToString("MM/dd/yy")); + Console.WriteLine(date.ToString("yy/MM/dd")); + Console.Read(); + return 0; + } +} +} + +/* +Some Date Formats : +Date and Time : 6/23/2013 12:00:00 AM +2013-06-23 +23-Jun-13 +6/23/2013 +6/23/13 +06/23/2013 +06/23/13 +13/06/23 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Find Greatest among 2 numbers.cs b/c-sharp/Basic/C# Program to Find Greatest among 2 numbers.cs new file mode 100644 index 0000000..bb4e35e --- /dev/null +++ b/c-sharp/Basic/C# Program to Find Greatest among 2 numbers.cs @@ -0,0 +1,29 @@ +/* + * C# Program to Find Greatest among 2 numbers + */ +using System; +class prog +{ + public static void Main() + { + int a, b; + Console.WriteLine("Enter the Two Numbers : "); + a = Convert.ToInt32(Console.ReadLine()); + b = Convert.ToInt32(Console.ReadLine()); + if (a > b) + { + Console.WriteLine("{0} is the Greatest Number", a); + } + else + { + Console.WriteLine("{0} is the Greatest Number ", b); + } + Console.ReadLine(); + } +} + +/* +Enter the Two Numbers : +24 +34 +34 is the Greatest Number \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Find Magnitude of Integer.cs b/c-sharp/Basic/C# Program to Find Magnitude of Integer.cs new file mode 100644 index 0000000..003239c --- /dev/null +++ b/c-sharp/Basic/C# Program to Find Magnitude of Integer.cs @@ -0,0 +1,26 @@ +/* + * C# Program to Find Magnitude of Integer + */ +using System; +public class Program +{ + public static void Main() + { + int num, mag=0; + Console.WriteLine("Enter the Number : "); + num = int.Parse(Console.ReadLine()); + Console.WriteLine("Number: " + num); + while (num > 0) + { + mag++; + num = num / 10; + }; + Console.WriteLine("Magnitude: " + mag); + Console.Read(); + } +} + +/* +Enter the Number : 3145678 +Number : 3145678 +Magnitude : 7 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Find a Number using Pythagoras Theorem.cs b/c-sharp/Basic/C# Program to Find a Number using Pythagoras Theorem.cs new file mode 100644 index 0000000..6122fcf --- /dev/null +++ b/c-sharp/Basic/C# Program to Find a Number using Pythagoras Theorem.cs @@ -0,0 +1,28 @@ +/* + * C# Program to Find a Number using Pythagoras Theorem + */ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +class Program +{ + static void Main(string[] args) + { + double a, b, c; + Console.WriteLine("Enter the First Value "); + a = double.Parse(Console.ReadLine()); + Console.WriteLine("Enter the Second Value "); + b = double.Parse(Console.ReadLine()); + c = Math.Sqrt(a * a + b * b); + Console.WriteLine("The Other Number is : {0}", c); + Console.ReadLine(); + } +} + +/* +Enter the First Value +3 +Enter the Second Value +4 +The Other Number is : 5 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Generate Random Numbers.cs b/c-sharp/Basic/C# Program to Generate Random Numbers.cs new file mode 100644 index 0000000..ec53c24 --- /dev/null +++ b/c-sharp/Basic/C# Program to Generate Random Numbers.cs @@ -0,0 +1,34 @@ +/* + * C# Program to Generate Random Numbers + */ +using System; +class Program +{ + static void Main() + { + Console.WriteLine("Some Random Numbers that are generated are : "); + for (int i = 1; i < 10; i++) + { + Randfunc(); + } + } + static Random r = new Random(); + static void Randfunc() + { + int n = r.Next(); + Console.WriteLine(n); + Console.ReadLine(); + } +} + +/* +Some Random Numbers that are generated are : +1234567 +8754352 +9864930 +8352048 +1920472 +2846104 +7649207 +4928756 +9261746 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Get a Number and Display the Number with its Reverse.cs b/c-sharp/Basic/C# Program to Get a Number and Display the Number with its Reverse.cs new file mode 100644 index 0000000..c8e6b06 --- /dev/null +++ b/c-sharp/Basic/C# Program to Get a Number and Display the Number with its Reverse.cs @@ -0,0 +1,31 @@ +/* + * C# Program to Get a Number and Display the Number with its Reverse + */ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Program +{ +class Program +{ + static void Main(string[] args) + { + int num, reverse = 0; + Console.WriteLine("Enter a Number : "); + num = int.Parse(Console.ReadLine()); + while (num != 0) + { + reverse = reverse * 10; + reverse = reverse + num % 10; + num = num / 10; + } + Console.WriteLine("Reverse of Entered Number is : "+reverse); + Console.ReadLine(); + } +} +} + +Enter a Number : 123 +Reverse of Entered Number : 321 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Get a Number and Display the Sum of the Digits.cs b/c-sharp/Basic/C# Program to Get a Number and Display the Sum of the Digits.cs new file mode 100644 index 0000000..07f7583 --- /dev/null +++ b/c-sharp/Basic/C# Program to Get a Number and Display the Sum of the Digits.cs @@ -0,0 +1,31 @@ +/* + * C# Program to Get a Number and Display the Sum of the Digits + */ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Program +{ +class Program +{ + static void Main(string[] args) + { + int num, sum = 0, r; + Console.WriteLine("Enter a Number : "); + num = int.Parse(Console.ReadLine()); + while (num != 0) + { + r = num % 10; + num = num / 10; + sum = sum + r; + } + Console.WriteLine("Sum of Digits of the Number : "+sum); + Console.ReadLine(); + } +} +} + +Enter a Number : 123 +Sum of Digits of the Number : 6 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Illustrate LeftShift Operations.cs b/c-sharp/Basic/C# Program to Illustrate LeftShift Operations.cs new file mode 100644 index 0000000..08779a7 --- /dev/null +++ b/c-sharp/Basic/C# Program to Illustrate LeftShift Operations.cs @@ -0,0 +1,28 @@ +/* + * C# Program to Illustrate LeftShift Operations + */ +using System; +class sample +{ + public static void Main() + { + int x = 1024 * 1024 * 1024; + uint p = 1024 * 1024 * 1024; + int y = -42; + Console.WriteLine("LEFT SHIFT OPERATIONS :"); + Console.WriteLine("{0},{1},{2}", x, x * 2, x << 1); + Console.WriteLine("{0},{1},{2}", p, p * 2, p << 1); + Console.WriteLine("{0},{1},{2}", x, x * 4, x << 2); + Console.WriteLine("{0},{1},{2}", p, p * 4, p << 2); + Console.WriteLine("{0},{1},{2}", y, y * 1024 * 1024 * 64, x << 26); + Console.ReadLine(); + } +} + +/* +LEFT SHIFT OPERATIONS : +1073741824,-2147483648,-2147483648 +1073741824,2147483648,2147483648 +1073741824,0,0 +1073741824,0,0 +-42,1476395008,0 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Illustrate the Use of Access Specifiers.cs b/c-sharp/Basic/C# Program to Illustrate the Use of Access Specifiers.cs new file mode 100644 index 0000000..d7d0479 --- /dev/null +++ b/c-sharp/Basic/C# Program to Illustrate the Use of Access Specifiers.cs @@ -0,0 +1,48 @@ +/* + * C# Program to Illustrate the Use of Access Specifiers + */ +using System; +namespace accessspecifier +{ +class Program +{ + static void Main(string[] args) + { + two B = new two(); + B.show(); + } +} +class one +{ + private int x; + protected int y; + internal int z; + public int a; + protected internal int b; +} +class two : one +{ + public void show() + { + Console.WriteLine("Values are : "); + //x=10; + y = 20; + z = 30; + a = 40; + b = 50; + // Console.WriteLine(+x); // Error x is not accessible + Console.WriteLine(y); + Console.WriteLine(z); + Console.WriteLine(a); + Console.WriteLine(b); + Console.ReadLine(); + } +} +} + +/* +Values are : +20 +30 +40 +50 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Implement PhoneBook.cs b/c-sharp/Basic/C# Program to Implement PhoneBook.cs new file mode 100644 index 0000000..ed3cda3 --- /dev/null +++ b/c-sharp/Basic/C# Program to Implement PhoneBook.cs @@ -0,0 +1,52 @@ +/* + * C# Program to Implement PhoneBook + */ +using System; +using System.Collections; +using System.IO; +class PhoneBook +{ + + static void Main(string[] arg) + { + Hashtable tab = new Hashtable(); + string fileName; + if + { + (arg.Length > 0) fileName = arg[0]; + } + else + { + fileName = "phoneBook.txt"; + } + StreamReader r = File.OpenText(fileName); + string line = r.ReadLine(); + while (line != null) + { + int pos = line.IndexOf('='); + string name = line.Substring(0, pos).Trim(); + long phone = Convert.ToInt64(line.Substring(pos + 1)); + tab[name] = phone; + line = r.ReadLine(); + } + r.Close(); + for (; ; ) + { + Console.Write("Name : "); + string name = Console.ReadLine().Trim(); + if (name == "") + break; + object phone = tab[name]; + if (phone == null) + Console.WriteLine("-- Not Found in Phone Book"); + else + Console.WriteLine(phone); + } + } +} + +/* +Name : Ram +9999945670 +Name : Raj +-- Not Found in Phone Book \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Implement for-each in Inteface.cs b/c-sharp/Basic/C# Program to Implement for-each in Inteface.cs new file mode 100644 index 0000000..8637230 --- /dev/null +++ b/c-sharp/Basic/C# Program to Implement for-each in Inteface.cs @@ -0,0 +1,85 @@ +/* + * C# Program to Implement for-each in Inteface + */ +using System; +using System.Collections; +class GrowableArray : IEnumerable +{ + object[] a; + public GrowableArray(int size) + { + a = new object[size]; + } + public GrowableArray() : this(8) {} + void Grow() + { + object[] b = new object[2 * a.Length]; + Array.Copy(a, b, a.Length); + a = b; + } + public object this[int i] + { + set + { + if (i >= a.Length) Grow(); + a[i] = value; + } + get + { + if (i >= a.Length) Grow(); + return a[i]; + } + } + public IEnumerator GetEnumerator() + { + return new GAEnumerator(a); + } + class GAEnumerator : IEnumerator + { + object[] a; + int i = -1; + public GAEnumerator(object[] a) + { + this.a = a; + } + public object Current + { + get + { + return a[i]; + } + } + public void Reset() + { + i = -1; + } + public bool MoveNext() + { + do i++; + while (i < a.Length && a[i] == null); + if (i == a.Length) + return false; + else return true; + } + } + +} +class Test +{ + public static void Main() + { + GrowableArray a = new GrowableArray(2); + a[0] = 0; + a[1] = 1; + a[3] = 3; + foreach (object x in a) Console.Write(" " + x); + } + + /* + Demonstrating foreach Interface by Displaying Numbers from 100 to 105 : + 100 + 101 + 102 + 103 + 104 + 105 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Perform Division of Exponents of Same Base.cs b/c-sharp/Basic/C# Program to Perform Division of Exponents of Same Base.cs new file mode 100644 index 0000000..64c5bde --- /dev/null +++ b/c-sharp/Basic/C# Program to Perform Division of Exponents of Same Base.cs @@ -0,0 +1,29 @@ +/* + * C# Program to Perform Division of Exponents of Same Base + */ +using System; +class Program +{ + static void Main() + { + Console.WriteLine("Enter the Base : "); + double num = double.Parse(Console.ReadLine()); + Console.WriteLine("Enter the First Exponent :"); + double exp1 = double.Parse(Console.ReadLine()); + Console.WriteLine("Enter the Second Exponent :"); + double exp2 = double.Parse(Console.ReadLine()); + double div; + div = exp1 - exp2; + Console.WriteLine("Result is : {0}^{1} : {2}", num, div, Math.Pow(num, div)); + Console.ReadLine(); + } +} + +/* +Enter the Base : +2 +Enter the First Exponent : +4 +Enter the Second Exponent : +3 +Result is : 2^1 : 2 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Perform Unboxing Operation.cs b/c-sharp/Basic/C# Program to Perform Unboxing Operation.cs new file mode 100644 index 0000000..cd2d9ca --- /dev/null +++ b/c-sharp/Basic/C# Program to Perform Unboxing Operation.cs @@ -0,0 +1,29 @@ +/* + * C# Program to Perform Unboxing Operation + */ +using System; +class sample +{ + int data; + void insert(object x) + { + data = (int)x * 5; + } + object delete() + { + data=0; + return (object)data; + } + public static void Main() + { + sample s = new sample(); + s.insert(10); + Console.WriteLine("Data : {0}", s.data); + Console.WriteLine("Data : {0}", s.delete()); + Console.ReadLine(); + } +} + +/* +Data : 50 +Data : 0 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Print a BinaryTriangle.cs b/c-sharp/Basic/C# Program to Print a BinaryTriangle.cs new file mode 100644 index 0000000..d8e3c5a --- /dev/null +++ b/c-sharp/Basic/C# Program to Print a BinaryTriangle.cs @@ -0,0 +1,46 @@ +/* + * C# Program to Print a BinaryTriangle + */ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Program +{ +class Program +{ + public static void Main(String[] args) + { + int p, lastInt = 0, input; + Console.WriteLine("Enter the Number of Rows : "); + input = int.Parse(Console.ReadLine()); + for (int i = 1; i <= input; i++) + { + for (p = 1; p <= i; p++) + { + if (lastInt == 1) + { + Console.Write("0"); + lastInt = 0; + } + else if (lastInt == 0) + { + Console.Write("1"); + lastInt = 1; + } + } + Console.Write("\n"); + } + Console.ReadLine(); + } +} +} + +/* +Enter the Number of Rows : 5 +1 +01 +010 +1010 +10101 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Print a Diamond Using Nested Loop.cs b/c-sharp/Basic/C# Program to Print a Diamond Using Nested Loop.cs new file mode 100644 index 0000000..e8f0c68 --- /dev/null +++ b/c-sharp/Basic/C# Program to Print a Diamond Using Nested Loop.cs @@ -0,0 +1,43 @@ +/* + * C# Program to Print the Sum of all the Multiples of 3 and 5 + */ +using System; +class program +{ + public static void Main() + { + int number, i, k, count = 1; + Console.Write("Enter number of rows\n"); + number = int.Parse(Console.ReadLine()); + count = number - 1; + for (k = 1; k <= number; k++) + { + for (i = 1; i <= count; i++) + Console.Write(" "); + count--; + for (i = 1; i <= 2 * k - 1; i++) + Console.Write("*"); + Console.WriteLine(); + } + count = 1; + for (k = 1; k <= number - 1; k++) + { + for (i = 1; i <= count; i++) + Console.Write(" "); + count++; + for (i = 1; i <= 2 * (number - k) - 1; i++) + Console.Write("*"); + Console.WriteLine(); + } + Console.ReadLine(); + } +} + +/* +Enter number of rows +3 + * + *** +***** + *** + * \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Read a Grade & Display the Equivalent Description.cs b/c-sharp/Basic/C# Program to Read a Grade & Display the Equivalent Description.cs new file mode 100644 index 0000000..da509b5 --- /dev/null +++ b/c-sharp/Basic/C# Program to Read a Grade & Display the Equivalent Description.cs @@ -0,0 +1,41 @@ +/* + * C# Program to Read a Grade & Display the Equivalent Description + */ +using System; +using System.IO; +class program +{ + public static void Main() + { + char grade; + Console.WriteLine("Enter the Grade in UpperCase \n"); + grade = Convert.ToChar(Console.ReadLine()); + switch (grade) + { + case 'S': + Console.WriteLine(" SUPER"); + break; + case 'A': + Console.WriteLine(" VERY GOOD"); + break; + case 'B': + Console.WriteLine(" FAIR"); + break; + case 'Y': + Console.WriteLine(" ABSENT"); + break; + case 'F': + Console.WriteLine(" FAIL"); + break; + default: + Console.WriteLine("ERROR IN GRADE \n"); + break; + Console.ReadLine(); + } + } +} + +/* +Enter the Grade in UpperCase +A + VERY GOOD \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Swap 2 Numbers.cs b/c-sharp/Basic/C# Program to Swap 2 Numbers.cs new file mode 100644 index 0000000..2f24378 --- /dev/null +++ b/c-sharp/Basic/C# Program to Swap 2 Numbers.cs @@ -0,0 +1,35 @@ +/* + * C# Program to Swap two Numbers + */ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +namespace Program +{ +class Program +{ + static void Main(string[] args) + { + int num1, num2, temp; + Console.Write("\nEnter the First Number : "); + num1 = int.Parse(Console.ReadLine()); + Console.Write("\nEnter the Second Number : "); + num2 = int.Parse(Console.ReadLine()); + temp = num1; + num1 = num2; + num2 = temp; + Console.Write("\nAfter Swapping : "); + Console.Write("\nFirst Number : "+num1); + Console.Write("\nSecond Number : "+num2); + Console.Read(); + } +} +} + +/* +Enter the First Number : 23 +Enter the Second Number : 25 +After Swapping : +First Number : 25 +Second Number : 23 \ No newline at end of file diff --git a/c-sharp/Basic/C# Program to Swap the Contents of two Numbers using Bitwise XOR Operation.cs b/c-sharp/Basic/C# Program to Swap the Contents of two Numbers using Bitwise XOR Operation.cs new file mode 100644 index 0000000..61483e1 --- /dev/null +++ b/c-sharp/Basic/C# Program to Swap the Contents of two Numbers using Bitwise XOR Operation.cs @@ -0,0 +1,27 @@ +/* + * C# Program to Swap the Contents of two Numbers using Bitwise XOR Operation + */ +using System; +class program +{ + public static void Main() + { + int i, k; + Console.WriteLine("Enter two integers \n"); + i = int.Parse(Console.ReadLine()); + k = int.Parse(Console.ReadLine()); + Console.WriteLine("\n Before swapping i= {0} and k = {1}", i, k); + i = i ^ k; + k = i ^ k; + i = i ^ k; + Console.WriteLine("\n After swapping i= {0} and k = {1}", i, k); + Console.ReadLine(); + } +} + +/* +Enter two integers +23 +34 +Before swapping i= 23 and k = 34 +After swapping i= 34 and k = 23 \ No newline at end of file diff --git a/c-sharp/Basic/C# Sharp program that takes a number as input and print its multiplication table.cs b/c-sharp/Basic/C# Sharp program that takes a number as input and print its multiplication table.cs new file mode 100644 index 0000000..52241fe --- /dev/null +++ b/c-sharp/Basic/C# Sharp program that takes a number as input and print its multiplication table.cs @@ -0,0 +1,31 @@ +using System; +public class Exercise8 +{ + public static void Main() + { + int x; + int result; + Console.WriteLine("Enter a number:"); + x = Convert.ToInt32(Console.ReadLine() ); + result = x * 1; + Console.WriteLine("The table is : {0} x {1} = {2}", x, 1, result); + result = x * 2; + Console.WriteLine(" : {0} x {1} = {2}", x, 2, result); + result = x * 3; + Console.WriteLine(" : {0} x {1} = {2}", x, 3, result); + result = x * 4; + Console.WriteLine(" : {0} x {1} = {2}", x, 4, result); + result = x * 5; + Console.WriteLine(" : {0} x {1} = {2}", x, 5, result); + result = x * 6; + Console.WriteLine(" : {0} x {1} = {2}", x, 6, result); + result = x * 7; + Console.WriteLine(" : {0} x {1} = {2}", x, 7, result); + result = x * 8; + Console.WriteLine(" : {0} x {1} = {2}", x, 8, result); + result = x * 9; + Console.WriteLine(" : {0} x {1} = {2}", x, 9, result); + result = x * 10; + Console.WriteLine(" : {0} x {1} = {2}", x, 10, result); + } +} \ No newline at end of file diff --git a/c-sharp/Basic/C# Sharp program that takes an age (for example 20) as input and prints something as.cs b/c-sharp/Basic/C# Sharp program that takes an age (for example 20) as input and prints something as.cs new file mode 100644 index 0000000..cc0178b --- /dev/null +++ b/c-sharp/Basic/C# Sharp program that takes an age (for example 20) as input and prints something as.cs @@ -0,0 +1,13 @@ +C# Sharp program that takes an age (for example 20) as input and prints something as "You look older than 20. + + using System; +public class Exercise11 +{ + public static void Main() + { + int age; + Console.Write("Enter your age "); + age = Convert.ToInt32(Console.ReadLine()); + Console.Write("You look younger than {0} ",age); + } +} \ No newline at end of file diff --git a/c-sharp/Basic/C# Sharp program that takes four numbers as input to calculate and print the average.cs b/c-sharp/Basic/C# Sharp program that takes four numbers as input to calculate and print the average.cs new file mode 100644 index 0000000..38f0a9b --- /dev/null +++ b/c-sharp/Basic/C# Sharp program that takes four numbers as input to calculate and print the average.cs @@ -0,0 +1,19 @@ +using System; +public class Exercise9 +{ + public static void Main() + { + int number1,number2,number3,number4; + Console.Write("Enter the First number: "); + number1 = Convert.ToInt32(Console.ReadLine()); + Console.Write("Enter the Second number: "); + number2 = Convert.ToInt32(Console.ReadLine()); + Console.Write("Enter the third number: "); + number3 = Convert.ToInt32(Console.ReadLine()); + Console.Write("Enter the four number: "); + number4 = Convert.ToInt32(Console.ReadLine()); + int result = (number1 + number2 + number3 + number4) / 4; + Console.WriteLine("The average of {0} , {1} , {2} , {3} is: {4} ", + number1, number2, number3, number4, result); + } +} \ No newline at end of file diff --git a/c-sharp/Basic/C# Sharp program to convert from celsius degrees to Kelvin and Fahrenheit.cs b/c-sharp/Basic/C# Sharp program to convert from celsius degrees to Kelvin and Fahrenheit.cs new file mode 100644 index 0000000..5faec92 --- /dev/null +++ b/c-sharp/Basic/C# Sharp program to convert from celsius degrees to Kelvin and Fahrenheit.cs @@ -0,0 +1,11 @@ +using System; +public class Exercise14 +{ + public static void Main( ) + { + Console.Write("Enter the amount of celsius: "); + int celsius = Convert.ToInt32(Console.ReadLine()); + Console.WriteLine("Kelvin = {0}", celsius + 273); + Console.WriteLine("Fahrenheit = {0}", celsius * 18 / 10 + 32); + } +} \ No newline at end of file diff --git a/c-sharp/Basic/C# Sharp program to print Hello and your name in a separate line.cs b/c-sharp/Basic/C# Sharp program to print Hello and your name in a separate line.cs new file mode 100644 index 0000000..d18d03b --- /dev/null +++ b/c-sharp/Basic/C# Sharp program to print Hello and your name in a separate line.cs @@ -0,0 +1,12 @@ +public class Exercise1 +{ + public static void Main( ) + { + System.Console.WriteLine("Hello"); + System.Console.WriteLine("Alexandra Abramov!"); + } +} +Output : + +Hello +Alexandra Abramov \ No newline at end of file diff --git a/c-sharp/Basic/C# Sharp program to print on screen the output of adding, subtracting, multiplying and dividing of two numbers which will be entered by the user.cs b/c-sharp/Basic/C# Sharp program to print on screen the output of adding, subtracting, multiplying and dividing of two numbers which will be entered by the user.cs new file mode 100644 index 0000000..b1679f5 --- /dev/null +++ b/c-sharp/Basic/C# Sharp program to print on screen the output of adding, subtracting, multiplying and dividing of two numbers which will be entered by the user.cs @@ -0,0 +1,16 @@ +using System; +public class Exercise7 +{ + public static void Main() + { + Console.Write("Enter a number: "); + int num1= Convert.ToInt32(Console.ReadLine()); + Console.Write("Enter another number: "); + int num2= Convert.ToInt32(Console.ReadLine()); + Console.WriteLine("{0} + {1} = {2}", num1, num2, num1+num2); + Console.WriteLine("{0} - {1} = {2}", num1, num2, num1-num2); + Console.WriteLine("{0} x {1} = {2}", num1, num2, num1*num2); + Console.WriteLine("{0} / {1} = {2}", num1, num2, num1/num2); + Console.WriteLine("{0} mod {1} = {2}", num1, num2, num1%num2); + } +} \ No newline at end of file diff --git a/c-sharp/Basic/C# Sharp program to print the output of multiplication of three numbers which will be entered by the user.cs b/c-sharp/Basic/C# Sharp program to print the output of multiplication of three numbers which will be entered by the user.cs new file mode 100644 index 0000000..3b54feb --- /dev/null +++ b/c-sharp/Basic/C# Sharp program to print the output of multiplication of three numbers which will be entered by the user.cs @@ -0,0 +1,17 @@ +using System; +public class Exercise6 +{ + public static void Main() + { + int num1, num2, num3; + Console.Write("Input the first number to multiply: "); + num1 = Convert.ToInt32(Console.ReadLine()); + Console.Write("Input the second number to multiply: "); + num2 = Convert.ToInt32(Console.ReadLine()); + Console.Write("Input the third number to multiply: "); + num3 = Convert.ToInt32(Console.ReadLine()); + int result = num1 * num2 * num3; + Console.WriteLine("Output: {0} x {1} x {2} = {3}", + num1, num2, num3, result); + } +} \ No newline at end of file diff --git a/c-sharp/Basic/C# Sharp program to print the result of dividing two numbers.cs b/c-sharp/Basic/C# Sharp program to print the result of dividing two numbers.cs new file mode 100644 index 0000000..8a6df63 --- /dev/null +++ b/c-sharp/Basic/C# Sharp program to print the result of dividing two numbers.cs @@ -0,0 +1,7 @@ +public class Exercise3 +{ + public static void Main() + { + System.Console.WriteLine(36/6); + } +} \ No newline at end of file diff --git a/c-sharp/Basic/C# Sharp program to print the result of the specified operations.cs b/c-sharp/Basic/C# Sharp program to print the result of the specified operations.cs new file mode 100644 index 0000000..618c43d --- /dev/null +++ b/c-sharp/Basic/C# Sharp program to print the result of the specified operations.cs @@ -0,0 +1,32 @@ +/* + +Write a C# Sharp program to print the result of the specified operations. + +Test data: +• -1 + 4 * 6 +• ( 35+ 5 ) % 7 +• 14 + -4 * 6 / 11 +• 2 + 15 / 6 * 1 - 7 % 2 +Expected Output: + +23 +5 +12 +3 + +*/ + +public class Exercise4 +{ + public static void Main() + { + System.Console.WriteLine(-1+4*6); + //-1 + 24 = 23 + System.Console.WriteLine((35+5)%7); + //40 % 7 = 5 (remainder of 40/7) + System.Console.WriteLine(14+-4*6/11); + //14 - (24/11)= 14 - 2 = 12 + System.Console.WriteLine(2+15/6*1-7%2); + //2 + (15/6) - remainder of (7/2) = 2 + 2 - 1 = 4 - 1 = 3 + } +} \ No newline at end of file diff --git a/c-sharp/Basic/C# Sharp program to print the sum of two numbers.cs b/c-sharp/Basic/C# Sharp program to print the sum of two numbers.cs new file mode 100644 index 0000000..997157f --- /dev/null +++ b/c-sharp/Basic/C# Sharp program to print the sum of two numbers.cs @@ -0,0 +1,7 @@ +public class Exercise2 +{ + public static void Main() + { + System.Console.WriteLine(15+17); + } +} \ No newline at end of file diff --git a/c-sharp/Basic/C# Sharp program to swap two numbers.cs b/c-sharp/Basic/C# Sharp program to swap two numbers.cs new file mode 100644 index 0000000..4478a67 --- /dev/null +++ b/c-sharp/Basic/C# Sharp program to swap two numbers.cs @@ -0,0 +1,19 @@ +using System; +public class Exercise5 +{ + public static void Main(string[] args) + { + int number1, number2, temp; + Console.Write("\nInput the First Number : "); + number1 = int.Parse(Console.ReadLine()); + Console.Write("\nInput the Second Number : "); + number2 = int.Parse(Console.ReadLine()); + temp = number1; + number1 = number2; + number2 = temp; + Console.Write("\nAfter Swapping : "); + Console.Write("\nFirst Number : "+number1); + Console.Write("\nSecond Number : "+number2); + Console.Read(); + } +} \ No newline at end of file diff --git a/c-sharp/Basic/C# Sharp program to that takes three numbers(x,y,z) as input and print the output of (x+y)úz and xúy + yúz.cs b/c-sharp/Basic/C# Sharp program to that takes three numbers(x,y,z) as input and print the output of (x+y)úz and xúy + yúz.cs new file mode 100644 index 0000000..378744e --- /dev/null +++ b/c-sharp/Basic/C# Sharp program to that takes three numbers(x,y,z) as input and print the output of (x+y)úz and xúy + yúz.cs @@ -0,0 +1,16 @@ +using System; +public class Exercise10 +{ + public static void Main() + { + int number1, number2, number3; + Console.Write("Enter first number - "); + number1 = Convert.ToInt32(Console.ReadLine()); + Console.Write("Enter second number - "); + number2 = Convert.ToInt32(Console.ReadLine()); + Console.Write("Enter third number - "); + number3 = Convert.ToInt32(Console.ReadLine()); + Console.Write("Result of specified numbers {0}, {1} and {2}, (x+y)·z is {3} and x·y + y·z is {4}\n\n", + number1, number2, number3, ((number1+number2)*number3), (number1*number2+number2*number3)); + } +} \ No newline at end of file diff --git a/c-sharp/Basic/C# program that takes a number as input and then displays a rectangle of 3 columns wide and 5 rows tall using that digit.cs b/c-sharp/Basic/C# program that takes a number as input and then displays a rectangle of 3 columns wide and 5 rows tall using that digit.cs new file mode 100644 index 0000000..e3b753c --- /dev/null +++ b/c-sharp/Basic/C# program that takes a number as input and then displays a rectangle of 3 columns wide and 5 rows tall using that digit.cs @@ -0,0 +1,15 @@ +using System; +public class Exercise13 +{ + public static void Main() + { + int x; + Console.Write("Enter a number: "); + x=Convert.ToInt32(Console.ReadLine()); + Console.WriteLine("{0}{0}{0}",x); + Console.WriteLine("{0} {0}",x); + Console.WriteLine("{0} {0}",x); + Console.WriteLine("{0} {0}",x); + Console.WriteLine("{0}{0}{0}",x); + } +} \ No newline at end of file diff --git a/c-sharp/Basic/C# program to that takes a number as input and display it four times in a row (separated by blank spaces), and then four times in the next row, with no separation.cs b/c-sharp/Basic/C# program to that takes a number as input and display it four times in a row (separated by blank spaces), and then four times in the next row, with no separation.cs new file mode 100644 index 0000000..9726806 --- /dev/null +++ b/c-sharp/Basic/C# program to that takes a number as input and display it four times in a row (separated by blank spaces), and then four times in the next row, with no separation.cs @@ -0,0 +1,29 @@ +using System; +public class Exercise12 +{ + public static void Main() + { + int num; + Console.WriteLine("Enter a digit: "); + num = Convert.ToInt32( Console.ReadLine() ); + // Part A: "num num num num" using Write + Console.Write( num ); + Console.Write(" "); + Console.Write( num ); + Console.Write(" "); + Console.Write( num ); + Console.Write(" "); + Console.Write( num ); + Console.WriteLine(); + // Part B: "numnumnumnum" using Write + Console.Write( num ); + Console.Write( num ); + Console.Write( num ); + Console.WriteLine( num ); + Console.WriteLine(); + // Part C: "num num num num" using {0} + Console.WriteLine("{0} {0} {0} {0}", num); + // Part D: "numnumnumnum" using {0} + Console.WriteLine("{0}{0}{0}{0}", num); + } +} \ No newline at end of file diff --git a/c-sharp/README.md b/c-sharp/README.md new file mode 100644 index 0000000..270f18a --- /dev/null +++ b/c-sharp/README.md @@ -0,0 +1,3 @@ +# C-Sharp programming language + +C-Sharp is a general-purpose, multi-paradigm programming language encompassing strong typing, lexically scoped, imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines. \ No newline at end of file diff --git a/c/Basic/Accessing an array using pointers.c b/c/Basic/Accessing an array using pointers.c new file mode 100644 index 0000000..295fd2c --- /dev/null +++ b/c/Basic/Accessing an array using pointers.c @@ -0,0 +1,17 @@ + #include + + main(){ + int a[5]; + int i; + for(i = 0;i<5;i++){ + a[i]=i; + } + + int *b; + + b=a; + for(i = 0;i<5;i++){ + printf("value in array %d and address is %16lu\n",*b,b); + b=b+2; + } + } \ No newline at end of file diff --git a/c/Basic/C Program to Accept the Height of a Person & Categorize as Taller, Dwarf & Average.c b/c/Basic/C Program to Accept the Height of a Person & Categorize as Taller, Dwarf & Average.c new file mode 100644 index 0000000..053b281 --- /dev/null +++ b/c/Basic/C Program to Accept the Height of a Person & Categorize as Taller, Dwarf & Average.c @@ -0,0 +1,21 @@ +/* + * C program to accept the height of a person in centimeter and + * categorize the person based on height as taller, dwarf and + * average height person + */ + +#include +void main() +{ + float height; + printf("Enter the Height (in centimetres) \n"); + scanf("%f", &height); + if (height < 150.0) + printf("Dwarf \n"); + else if ((height >= 150.0) && (height <= 165.0)) + printf(" Average Height \n"); + else if ((height >= 165.0) && (height <= 195.0)) + printf("Taller \n"); + else + printf("Abnormal height \n"); +} \ No newline at end of file diff --git a/c/Basic/C Program to Accept two Integers and Check if they are Equal.c b/c/Basic/C Program to Accept two Integers and Check if they are Equal.c new file mode 100644 index 0000000..5d06c95 --- /dev/null +++ b/c/Basic/C Program to Accept two Integers and Check if they are Equal.c @@ -0,0 +1,14 @@ +/* + * C program to accept two integers and check if they are equal + */ +#include +void main() +{ + int m, n; + printf("Enter the values for M and N\n"); + scanf("%d %d", &m, &n); + if (m == n) + printf("M and N are equal\n"); + else + printf("M and N are not equal\n"); +} \ No newline at end of file diff --git a/c/Basic/C Program to Add two Complex Numbers.c b/c/Basic/C Program to Add two Complex Numbers.c new file mode 100644 index 0000000..ee35c48 --- /dev/null +++ b/c/Basic/C Program to Add two Complex Numbers.c @@ -0,0 +1,31 @@ +/* + * C Program to Add two Complex Numbers + */ +#include + +struct complex +{ + int realpart, imaginary; +}; + +main() +{ + struct complex a, b, c; + printf("Enter value of a and b complex number a + ib.\n"); + printf("value of complex number a is = "); + scanf("%d", &a.realpart); + printf("value of complex number b is = "); + scanf("%d", &a.imaginary); + printf("Enter value of c and d complex number c + id.\n"); + printf("value of complex number c is = "); + scanf("%d", &b.realpart); + printf("value of complex number d is = "); + scanf("%d", &b.imaginary); + c.realpart = a.realpart + b.realpart; + c.imaginary = a.imaginary + b.imaginary; + if (c.imaginary >= 0) + printf("complex numbers sum is = %d + %di\n", c.realpart, c.imaginary); + else + printf("complex numbers sum = %d %di\n", c.realpart, c.imaginary); + return 0; +} \ No newline at end of file diff --git a/c/Basic/C Program to Calculate the Sum of Odd & Even Numbers.c b/c/Basic/C Program to Calculate the Sum of Odd & Even Numbers.c new file mode 100644 index 0000000..4db9d47 --- /dev/null +++ b/c/Basic/C Program to Calculate the Sum of Odd & Even Numbers.c @@ -0,0 +1,20 @@ +/* + * C program to find the sum of odd and even numbers from 1 to N + */ +#include + +void main() +{ + int i, num, odd_sum = 0, even_sum = 0; + printf("Enter the value of num\n"); + scanf("%d", &num); + for (i = 1; i <= num; i++) + { + if (i % 2 == 0) + even_sum = even_sum + i; + else + odd_sum = odd_sum + i; + } + printf("Sum of all odd numbers = %d\n", odd_sum); + printf("Sum of all even numbers = %d\n", even_sum); +} \ No newline at end of file diff --git a/c/Basic/C Program to Check if a given Integer is Odd or Even.c b/c/Basic/C Program to Check if a given Integer is Odd or Even.c new file mode 100644 index 0000000..e48ef5b --- /dev/null +++ b/c/Basic/C Program to Check if a given Integer is Odd or Even.c @@ -0,0 +1,16 @@ +/* + * C program to check whether a given integer is odd or even + */ +#include + +void main() +{ + int ival, remainder; + printf("Enter an integer : "); + scanf("%d", &ival); + remainder = ival % 2; + if (remainder == 0) + printf("%d is an even integer\n", ival); + else + printf("%d is an odd integer\n", ival); +} \ No newline at end of file diff --git a/c/Basic/C Program to Check if a given Integer is Positive or Negative.c b/c/Basic/C Program to Check if a given Integer is Positive or Negative.c new file mode 100644 index 0000000..7c8d8cd --- /dev/null +++ b/c/Basic/C Program to Check if a given Integer is Positive or Negative.c @@ -0,0 +1,16 @@ +/* + * C program to check whether a given integer is positive + * or negative + */ +#include + +void main() +{ + int number; + printf("Enter a number \n"); + scanf("%d", &number); + if (number >= 0) + printf("%d is a positive number \n", number); + else + printf("%d is a negative number \n", number); +} \ No newline at end of file diff --git a/c/Basic/C Program to Check whether a given Number is Armstrong.c b/c/Basic/C Program to Check whether a given Number is Armstrong.c new file mode 100644 index 0000000..30d0649 --- /dev/null +++ b/c/Basic/C Program to Check whether a given Number is Armstrong.c @@ -0,0 +1,24 @@ +/* + * C Program to Check whether a given Number is Armstrong + */ +#include +#include + +void main() +{ + int number, sum = 0, rem = 0, cube = 0, temp; + printf ("enter a number"); + scanf("%d", &number); + temp = number; + while (number != 0) + { + rem = number % 10; + cube = pow(rem, 3); + sum = sum + cube; + number = number / 10; + } + if (sum == temp) + printf ("The given no is armstrong no"); + else + printf ("The given no is not a armstrong no"); +} \ No newline at end of file diff --git a/c/Basic/C Program to Check whether a given Number is Perfect Number.c b/c/Basic/C Program to Check whether a given Number is Perfect Number.c new file mode 100644 index 0000000..491af60 --- /dev/null +++ b/c/Basic/C Program to Check whether a given Number is Perfect Number.c @@ -0,0 +1,24 @@ +/* + * C Program to Check whether a given Number is Perfect Number + */ +#include + +int main() +{ + int number, rem, sum = 0, i; + printf("Enter a Number\n"); + scanf("%d", &number); + for (i = 1; i <= (number - 1); i++) + { + rem = number % i; + if (rem == 0) + { + sum = sum + i; + } + } + if (sum == number) + printf("Entered Number is perfect number"); + else + printf("Entered Number is not a perfect number"); + return 0; +} \ No newline at end of file diff --git a/c/Basic/C Program to Check whether the given Number is Palindrome or not using Bitwise Operator.c b/c/Basic/C Program to Check whether the given Number is Palindrome or not using Bitwise Operator.c new file mode 100644 index 0000000..4b9fe81 --- /dev/null +++ b/c/Basic/C Program to Check whether the given Number is Palindrome or not using Bitwise Operator.c @@ -0,0 +1,70 @@ +/* +* C Program to Check whether the given Number is Palindrome +* or not using Bitwise Operator +*/ +#include +#include +#define SIZE 8 +/* Function Prototype */ +int is_palindrome(unsigned char[]); + +void main() +{ + int num, num1 = 0, i = 0, j = SIZE - 1, res; + unsigned char c[SIZE]; + printf("Enter a number(max 255)"); + scanf("%d", &num); + num1 = num; + while (num != 0) + { + c[j] = num&1; + j--; + num = num>>1; /* Shifting right the given number by 1 bit */ + } + printf("The number %d in binary is:", num1); + for (i = 0; i < SIZE; i++) + { + printf("%d", c[i]); + } + res = is_palindrome(c); /* Calling Function */ + if (res == 0) + { + printf(" + NUMBER IS PALINDROME + "); + } + else + { + printf(" + NUMBER IS NOT PALINDROME + "); + } +} + +/* Code to check if the number is palindrome or not */ +int is_palindrome(unsigned char c[]) +{ + char temp[SIZE]; + int i, j, flag = 0; + for (i = 0, j = SIZE - 1; i < SIZE, j >= 0; i++, j--) + { + temp[j] = c[i]; + } + for (i = 0; i < SIZE; i++) + { + if (temp[i] != c[i]) + { + flag = 1; + } + } + return flag; +} + + + +Enter a number(max 255)153 +The number 153 in binary is:10011001 +NUMBER IS PALINDROME +Enter a number(max 255)24 +The number 24 in binary is:00011000 +NUMBER IS PALINDROME \ No newline at end of file diff --git a/c/Basic/C Program to Compute First N Fibonacci Numbers using Command Line Arguments.c b/c/Basic/C Program to Compute First N Fibonacci Numbers using Command Line Arguments.c new file mode 100644 index 0000000..0c6340b --- /dev/null +++ b/c/Basic/C Program to Compute First N Fibonacci Numbers using Command Line Arguments.c @@ -0,0 +1,34 @@ +/* + * C Program to Compute First N Fibonacci Numbers using Command Line Arguments + */ +#include + +/* Global Variable Declaration */ +int first = 0; +int second = 1; +int third; +/* Function Prototype */ +void rec_fibonacci(int); + +void main(int argc, char *argv[])/* Command line Arguments*/ +{ + int number = atoi(argv[1]); + printf("%d\t%d", first, second); /* To print first and second number of fibonacci series */ + rec_fibonacci(number); + printf("\n"); +} + +/* Code to print fibonacci series using recursive function */ +void rec_fibonacci(int num) +{ + if (num == 2) /* To exit the function as the first two numbers are already printed */ + { + return; + } + third = first + second; + printf("\t%d", third); + first = second; + second = third; + num--; + rec_fibonacci(num); +} \ No newline at end of file diff --git a/c/Basic/C Program to Compute the Sum of Digits in a given Integer.c b/c/Basic/C Program to Compute the Sum of Digits in a given Integer.c new file mode 100644 index 0000000..4c981a3 --- /dev/null +++ b/c/Basic/C Program to Compute the Sum of Digits in a given Integer.c @@ -0,0 +1,20 @@ +/* + * C program to accept an integer & find the sum of its digits + */ +#include + +void main() +{ + long num, temp, digit, sum = 0; + printf("Enter the number \n"); + scanf("%ld", &num); + temp = num; + while (num > 0) + { + digit = num % 10; + sum = sum + digit; + num /= 10; + } + printf("Given number = %ld\n", temp); + printf("Sum of the digits %ld = %ld\n", temp, sum); +} \ No newline at end of file diff --git a/c/Basic/C Program to Convert Binary Code of a Number into its Equivalent Gray’s Code using Recursion.c b/c/Basic/C Program to Convert Binary Code of a Number into its Equivalent Gray’s Code using Recursion.c new file mode 100644 index 0000000..152e79a --- /dev/null +++ b/c/Basic/C Program to Convert Binary Code of a Number into its Equivalent Gray’s Code using Recursion.c @@ -0,0 +1,40 @@ +/* + * C Program to Convert Binary Code of a Number into its Equivalent + * Gray's Code using Recursion + */ +#include + +int bintogray(int); + +int main () +{ + int bin, gray; + printf("Enter a binary number: "); + scanf("%d", &bin); + gray = bintogray(bin); + printf("The gray code of %d is %d\n", bin, gray); + return 0; +} + +int bintogray(int bin) +{ + int a, b, result = 0, i = 0; + if (!bin) + { + return 0; + } + else + { + a = bin % 10; + bin = bin / 10; + b = bin % 10; + if ((a && !b) || (!a && b)) + { + return (1 + 10 * bintogray(bin)); + } + else + { + return (10 * bintogray(bin)); + } + } +} \ No newline at end of file diff --git a/c/Basic/C Program to Convert Binary Code of a Number into its Equivalent Gray’s Code without using Recursion.c b/c/Basic/C Program to Convert Binary Code of a Number into its Equivalent Gray’s Code without using Recursion.c new file mode 100644 index 0000000..020d700 --- /dev/null +++ b/c/Basic/C Program to Convert Binary Code of a Number into its Equivalent Gray’s Code without using Recursion.c @@ -0,0 +1,35 @@ +/* + * C Program to Convert Binary Code of a Number into its Equivalent + * Gray's Code without using Recursion + */ +#include +#include + +int bintogray(int); + +int main () +{ + int bin, gray; + printf("Enter a binary number: "); + scanf("%d", &bin); + gray = bintogray(bin); + printf("The gray code of %d is %d\n", bin, gray); + return 0; +} + +int bintogray(int bin) +{ + int a, b, result = 0, i = 0; + while (bin != 0) + { + a = bin % 10; + bin = bin / 10; + b = bin % 10; + if ((a && !b) || (!a && b)) + { + result = result + pow(10, i); + } + i++; + } + return result; +} \ No newline at end of file diff --git a/c/Basic/C Program to Convert Binary to Hexadecimal.c b/c/Basic/C Program to Convert Binary to Hexadecimal.c new file mode 100644 index 0000000..1b19012 --- /dev/null +++ b/c/Basic/C Program to Convert Binary to Hexadecimal.c @@ -0,0 +1,20 @@ +/* + * C Program to Convert Binary to Hexadecimal + */ +#include + +int main() +{ + long int binaryval, hexadecimalval = 0, i = 1, remainder; + printf("Enter the binary number: "); + scanf("%ld", &binaryval); + while (binaryval != 0) + { + remainder = binaryval % 10; + hexadecimalval = hexadecimalval + remainder * i; + i = i * 2; + binaryval = binaryval / 10; + } + printf("Equivalent hexadecimal value: %lX", hexadecimalval); + return 0; +} \ No newline at end of file diff --git a/c/Basic/C Program to Convert Binary to Octal.c b/c/Basic/C Program to Convert Binary to Octal.c new file mode 100644 index 0000000..6c38d56 --- /dev/null +++ b/c/Basic/C Program to Convert Binary to Octal.c @@ -0,0 +1,20 @@ +/* + * C Program to Convert Binary to Octal + */ +#include + +int main() +{ + long int binarynum, octalnum = 0, j = 1, remainder; + printf("Enter the value for binary number: "); + scanf("%ld", &binarynum); + while (binarynum != 0) + { + remainder = binarynum % 10; + octalnum = octalnum + remainder * j; + j = j * 2; + binarynum = binarynum / 10; + } + printf("Equivalent octal value: %lo", octalnum); + return 0; +} \ No newline at end of file diff --git a/c/Basic/C Program to Convert Hexadecimal to Binary.c b/c/Basic/C Program to Convert Hexadecimal to Binary.c new file mode 100644 index 0000000..890a63d --- /dev/null +++ b/c/Basic/C Program to Convert Hexadecimal to Binary.c @@ -0,0 +1,91 @@ +/* + * C Program to Convert Hexadecimal to Binary + */ +#include +#define MAX 1000 + +int main() +{ + char binarynum[MAX], hexa[MAX]; + long int i = 0; + printf("Enter the value for hexadecimal "); + scanf("%s", hexa); + printf("\n Equivalent binary value: "); + while (hexa[i]) + { + switch (hexa[i]) + { + case '0': + printf("0000"); + break; + case '1': + printf("0001"); + break; + case '2': + printf("0010"); + break; + case '3': + printf("0011"); + break; + case '4': + printf("0100"); + break; + case '5': + printf("0101"); + break; + case '6': + printf("0110"); + break; + case '7': + printf("0111"); + break; + case '8': + printf("1000"); + break; + case '9': + printf("1001"); + break; + case 'A': + printf("1010"); + break; + case 'B': + printf("1011"); + break; + case 'C': + printf("1100"); + break; + case 'D': + printf("1101"); + break; + case 'E': + printf("1110"); + break; + case 'F': + printf("1111"); + break; + case 'a': + printf("1010"); + break; + case 'b': + printf("1011"); + break; + case 'c': + printf("1100"); + break; + case 'd': + printf("1101"); + break; + case 'e': + printf("1110"); + break; + case 'f': + printf("1111"); + break; + default: + printf("\n Invalid hexa digit %c ", hexa[i]); + return 0; + } + i++; + } + return 0; +} \ No newline at end of file diff --git a/c/Basic/C Program to Convert Numbers to Roman Numerals.c b/c/Basic/C Program to Convert Numbers to Roman Numerals.c new file mode 100644 index 0000000..b7f7f4f --- /dev/null +++ b/c/Basic/C Program to Convert Numbers to Roman Numerals.c @@ -0,0 +1,125 @@ +/* + * C Program to Convert Numbers to Roman Numerals + */ +#include + +void predigit(char num1, char num2); +void postdigit(char c, int n); + +char romanval[1000]; +int i = 0; +int main() +{ + int j; + long number; + printf("Enter the number: "); + scanf("%d", &number); + if (number <= 0) + { + printf("Invalid number"); + return 0; + } + while (number != 0) + { + if (number >= 1000) + { + postdigit('M', number / 1000); + number = number - (number / 1000) * 1000; + } + else if (number >= 500) + { + if (number < (500 + 4 * 100)) + { + postdigit('D', number / 500); + number = number - (number / 500) * 500; + } + else + { + predigit('C','M'); + number = number - (1000-100); + } + } + else if (number >= 100) + { + if (number < (100 + 3 * 100)) + { + postdigit('C', number / 100); + number = number - (number / 100) * 100; + } + else + { + predigit('L', 'D'); + number = number - (500 - 100); + } + } + else if (number >= 50 ) + { + if (number < (50 + 4 * 10)) + { + postdigit('L', number / 50); + number = number - (number / 50) * 50; + } + else + { + predigit('X','C'); + number = number - (100-10); + } + } + else if (number >= 10) + { + if (number < (10 + 3 * 10)) + { + postdigit('X', number / 10); + number = number - (number / 10) * 10; + } + else + { + predigit('X','L'); + number = number - (50 - 10); + } + } + else if (number >= 5) + { + if (number < (5 + 4 * 1)) + { + postdigit('V', number / 5); + number = number - (number / 5) * 5; + } + else + { + predigit('I', 'X'); + number = number - (10 - 1); + } + } + else if (number >= 1) + { + if (number < 4) + { + postdigit('I', number / 1); + number = number - (number / 1) * 1; + } + else + { + predigit('I', 'V'); + number = number - (5 - 1); + } + } + } + printf("Roman number is: "); + for(j = 0; j < i; j++) + printf("%c", romanval[j]); + return 0; +} + +void predigit(char num1, char num2) +{ + romanval[i++] = num1; + romanval[i++] = num2; +} + +void postdigit(char c, int n) +{ + int j; + for (j = 0; j < n; j++) + romanval[i++] = c; +} \ No newline at end of file diff --git a/c/Basic/C Program to Convert Octal to Binary.c b/c/Basic/C Program to Convert Octal to Binary.c new file mode 100644 index 0000000..2894f21 --- /dev/null +++ b/c/Basic/C Program to Convert Octal to Binary.c @@ -0,0 +1,49 @@ +/* + * C Program to Convert Octal to Binary + */ +#include +#define MAX 1000 + +int main() +{ + char octalnum[MAX]; + long i = 0; + printf("Enter any octal number: "); + scanf("%s", octalnum); + printf("Equivalent binary value: "); + while (octalnum[i]) + { + switch (octalnum[i]) + { + case '0': + printf("000"); + break; + case '1': + printf("001"); + break; + case '2': + printf("010"); + break; + case '3': + printf("011"); + break; + case '4': + printf("100"); + break; + case '5': + printf("101"); + break; + case '6': + printf("110"); + break; + case '7': + printf("111"); + break; + default: + printf("\n Invalid octal digit %c ", octalnum[i]); + return 0; + } + i++; + } + return 0; +} \ No newline at end of file diff --git a/c/Basic/C Program to Convert Octal to Decimal.c b/c/Basic/C Program to Convert Octal to Decimal.c new file mode 100644 index 0000000..a9da073 --- /dev/null +++ b/c/Basic/C Program to Convert Octal to Decimal.c @@ -0,0 +1,20 @@ +/* + * C Program to Convert Octal to Decimal + */ +#include +#include + +int main() +{ + long int octal, decimal = 0; + int i = 0; + printf("Enter any octal number: "); + scanf("%ld", &octal); + while (octal != 0) + { + decimal = decimal +(octal % 10)* pow(8, i++); + octal = octal / 10; + } + printf("Equivalent decimal value: %ld",decimal); + return 0; +} diff --git a/c/Basic/C Program to Convert Roman Number to Decimal Number.c b/c/Basic/C Program to Convert Roman Number to Decimal Number.c new file mode 100644 index 0000000..3c942e8 --- /dev/null +++ b/c/Basic/C Program to Convert Roman Number to Decimal Number.c @@ -0,0 +1,66 @@ +/* + * C Program to Convert Roman Number to Decimal Number + */ +#include +#include + +int digit(char); + +int main() +{ + char romanval[1000]; + int i = 0; + long int number = 0; + printf("Enter roman num (Valid digits are I, V, X, L, C, D, M):\n"); + scanf("%s", romanval); + while (romanval[i]) + { + if (digit(romanval[i]) 2) + { + if (digit(romanval[i]) = digit(romanval[i+1])) + number = number + digit(romanval[i]); + else + { + number = number + (digit(romanval[i + 1]) - + digit(romanval[i])); + i++; + } + i++; + } + printf("Its decimal value is : %ld", number); + return 0; + } + int digit(char c) + { + int value = 0; + switch (c) + { + case 'I': + value = 1; + break; + case 'V': + value = 5; + break; + case 'X': + value = 10; + break; + case 'L': + value = 50; + break; + case 'C': + value = 100; + break; + case 'D': + value = 500; + break; + case 'M': + value = 1000; + break; + case '0': + value = 0; + break; + default: + value = -1; + } + return value; + } \ No newline at end of file diff --git a/c/Basic/C Program to Convert a Decimal Number to Binary & Count the Number of 1s.c b/c/Basic/C Program to Convert a Decimal Number to Binary & Count the Number of 1s.c new file mode 100644 index 0000000..c595704 --- /dev/null +++ b/c/Basic/C Program to Convert a Decimal Number to Binary & Count the Number of 1s.c @@ -0,0 +1,28 @@ +/* + * C program to accept a decimal number and convert it to binary + * and count the number of 1's in the binary number + */ +#include + +void main() +{ + long num, decimal_num, remainder, base = 1, binary = 0, no_of_1s = 0; + printf("Enter a decimal integer \n"); + scanf("%ld", &num); + decimal_num = num; + while (num > 0) + { + remainder = num % 2; + /* To count no.of 1s */ + if (remainder == 1) + { + no_of_1s++; + } + binary = binary + remainder * base; + num = num / 2; + base = base * 10; + } + printf("Input number is = %d\n", decimal_num); + printf("Its binary equivalent is = %ld\n", binary); + printf("No.of 1's in the binary number is = %d\n", no_of_1s); +} \ No newline at end of file diff --git a/c/Basic/C Program to Convert a Given Number of Days in terms of Years, Weeks & Days.c b/c/Basic/C Program to Convert a Given Number of Days in terms of Years, Weeks & Days.c new file mode 100644 index 0000000..7eac27f --- /dev/null +++ b/c/Basic/C Program to Convert a Given Number of Days in terms of Years, Weeks & Days.c @@ -0,0 +1,19 @@ +/* + * C program to convert given number of days to a measure of time given + * in years, weeks and days. For example 375 days is equal to 1 year + * 1 week and 3 days (ignore leap year) + */ +#include +#define DAYSINWEEK 7 + +void main() +{ + int ndays, year, week, days; + printf("Enter the number of daysn"); + scanf("%d", &ndays); + year = ndays / 365; + week =(ndays % 365) / DAYSINWEEK; + days =(ndays % 365) % DAYSINWEEK; + printf ("%d is equivalent to %d years, %d weeks and %d daysn", + ndays, year, week, days); +} \ No newline at end of file diff --git a/c/Basic/C Program to Convert a Number Decimal System to Binary System using Recursion.c b/c/Basic/C Program to Convert a Number Decimal System to Binary System using Recursion.c new file mode 100644 index 0000000..3301a55 --- /dev/null +++ b/c/Basic/C Program to Convert a Number Decimal System to Binary System using Recursion.c @@ -0,0 +1,28 @@ +/* + * C Program to Convert a Number Decimal System to Binary System using Recursion + */ +#include + +int convert(int); + +int main() +{ + int dec, bin; + printf("Enter a decimal number: "); + scanf("%d", &dec); + bin = convert(dec); + printf("The binary equivalent of %d is %d.\n", dec, bin); + return 0; +} + +int convert(int dec) +{ + if (dec == 0) + { + return 0; + } + else + { + return (dec % 2 + 10 * convert(dec / 2)); + } +} \ No newline at end of file diff --git a/c/Basic/C Program to Convert the given Binary Number into Decimal.c b/c/Basic/C Program to Convert the given Binary Number into Decimal.c new file mode 100644 index 0000000..866c02d --- /dev/null +++ b/c/Basic/C Program to Convert the given Binary Number into Decimal.c @@ -0,0 +1,21 @@ +/* + * C program to convert the given binary number into decimal + */ +#include + +void main() +{ + int num, binary_val, decimal_val = 0, base = 1, rem; + printf("Enter a binary number(1s and 0s) \n"); + scanf("%d", &num); /* maximum five digits */ + binary_val = num; + while (num > 0) + { + rem = num % 10; + decimal_val = decimal_val + rem * base; + num = num / 10 ; + base = base * 2; + } + printf("The Binary number is = %d \n", binary_val); + printf("Its decimal equivalent is = %d \n", decimal_val); +} \ No newline at end of file diff --git a/c/Basic/C Program to Count Number of Words in a given Text Or Sentence.c b/c/Basic/C Program to Count Number of Words in a given Text Or Sentence.c new file mode 100644 index 0000000..9bd05de --- /dev/null +++ b/c/Basic/C Program to Count Number of Words in a given Text Or Sentence.c @@ -0,0 +1,27 @@ +/* +* C Program to Count Number of Words in a given Text Or Sentence +*/ +#include +#include + +void main() +{ + char s[200]; + int count = 0, i; + printf("enter the string + "); + scanf("%[^ + ]s", s); + for (i = 0; s[i] != ''; i++) + { + if (s[i] == ' ') + count++; + } + printf("number of words in given string are: %d + ", count + 1); +} + + +enter the string +welcome to illuminate's c-programming app! +number of words in given string are: 5 \ No newline at end of file diff --git a/c/Basic/C Program to Count the Number of Occurrence of each Character Ignoring the Case of Alphabets & Display them.c b/c/Basic/C Program to Count the Number of Occurrence of each Character Ignoring the Case of Alphabets & Display them.c new file mode 100644 index 0000000..9c729d9 --- /dev/null +++ b/c/Basic/C Program to Count the Number of Occurrence of each Character Ignoring the Case of Alphabets & Display them.c @@ -0,0 +1,86 @@ +/* +* C Program to Count the Number of Occurrence of +* each Character Ignoring the Case of Alphabets +* & Display them +*/ +#include +#include +#include + +struct detail +{ + char c; + int freq; +}; +int main() +{ + struct detail s[26]; + char string[100], c; + int i = 0, index; + for (i = 0; i < 26; i++) + { + s[i].c = i + 'a'; + s[i].freq = 0; + } + printf("Enter string: "); + i = 0; + do + { + fflush(stdin); + c = getchar(); + string[i++] = c; + if (c == ' + ') + { + break; + } + c = tolower(c); + index = c - 'a'; + s[index].freq++; + } +while (1); + string[i - 1] = ''; + printf("The string entered is: %s + ", string); + printf("************************* + Character Frequency + ************************* + "); + for (i = 0; i < 26; i++) + { + if (s[i].freq) + { + printf(" %c %d + ", s[i].c, s[i].freq); + } + } + return + 0; +} + + +Enter string: +A quIck brOwn fox JumpEd over a lazy dOg +The string entered is: +A quIck brOwn fox JumpEd over a lazy dOg +************************* +Character Frequency +********************* +a 3 +b 1 +c 1 +d 2 +e 2 +f 1 +g 1 +i 1 +j 1 +k 1 +l 1 +m 1 +n 1 +o 4 +p 1 +q 1 +r 2 +u 2 v 1 w 1 x 1 y 1 z 1 \ No newline at end of file diff --git a/c/Basic/C Program to Count the Number of Unique Words.c b/c/Basic/C Program to Count the Number of Unique Words.c new file mode 100644 index 0000000..aaf0ba5 --- /dev/null +++ b/c/Basic/C Program to Count the Number of Unique Words.c @@ -0,0 +1,65 @@ +/* +* C Program to Count the Number of Unique Words +*/ +#include +#include +#include +int main() +{ + int i = 0, e, j, d, k, space = 0; + char a[50], b[15][20], c[15][20]; + printf("Read a string: + "); + fflush(stdin); + scanf("%[^ + ]s", a); + for (i = 0; a[i] != ''; i++) //loop to count no of words + { + if (a[i] = = ' ') + space++; + } + i = 0; + for (j = 0; j<(space + 1); i++, j++) //loop to store each word into an 2D array + { + k = 0; + while (a[i] != '') + { + if (a[i] == ' ') + { + break; + } + else + { + b[j][k++] = a[i]; + i++; + } + } + b[j][k] = ''; + } + i = 0; + strcpy(c[i], b[i]); + for (e = 1; e <= j; e++) //loop to check whether the string is already present in the 2D array or not + { + for (d = 0; d <= i; d++) + { + if (strcmp(c[i], b[e]) == 0) + break; + else + { + i++; + strcpy(c[i], b[e]); + break; + } + } + } + printf(" + Number of unique words in %s are:%d", a, i); + return 0; +} + + +Read a string: +Welcome to Illuminate's C-programming class, Welcome again to C class! +The length of input string is:70 + +Number of unique words in Welcome to ILLuminate's C-programming class, Welcome again to C class! are:12 \ No newline at end of file diff --git a/c/Basic/C Program to Count the Occurrences of each C Keyword using Array Structure.c b/c/Basic/C Program to Count the Occurrences of each C Keyword using Array Structure.c new file mode 100644 index 0000000..dc4f61b --- /dev/null +++ b/c/Basic/C Program to Count the Occurrences of each C Keyword using Array Structure.c @@ -0,0 +1,104 @@ +/* +* C Program to Count the Occurrences of each C Keyword +* using Array Structure +*/ +#include +#include +#include +#define KEYMAX 32 + +struct keyword +{ + char word[10]; + int occur; +}; + +int binarysearch(char [], struct keyword[]); + +int main() +{ + int i = 0, j = 0, pos; + char string[100], unit[20], c; + struct keyword key[32] = {"auto", 0, "break", 0, "case", 0, + "char", 0, "const", 0, "continue", 0, + "default", 0, "do", 0, "double", 0, + "else", 0, "enum", 0, "extern", 0, + "float", 0, "for", 0, "goto", 0, + "if", 0, "int", 0, "long", 0, + "register", 0, "return", 0, "short", 0, + "signed", 0, "sizeof", 0, "static", 0, + "struct", 0, "switch", 0, "typedef", 0, + "union", 0, "unsigned", 0, "void", 0, + "volatile", 0, "while", 0, + }; + printf("Enter string: "); + do + { + fflush(stdin); + c = getchar(); + string[i++] = c; + } + while (c != ' + '); + string[i - 1] = ''; + printf("The string entered is: %s + ", string); + for (i = 0; i < strlen(string); i++) + { + while (i < strlen(string) && string[i] != ' ' && isalpha(string[i])) + { + unit[j++] = tolower(string[i++]); + } + if (j != 0) + { + unit[j] = ''; + pos = binarysearch(unit, key); + j = 0; + if (pos != -1) + { + key[pos].occur++; + } + } + } + printf("*********************** + Keyword Count + *********************** + "); + for (i = 0; i < KEYMAX; i++) + { + if (key[i].occur) + { + printf(" %s %d + ", key[i].word, key[i].occur); } + } + return 0; + } + int binarysearch(char *word, struct keyword key[]) + { + int low, high, mid; + low = 0; + high = KEYMAX - 1; + while (low <= high) + { + mid = (low + high) / 2; + if (strcmp(word, key[mid].word) < 0) + { + high = mid - 1; + } + else if (strcmp(word, key[mid].word) > 0) + { + low = mid + 1; + } + else + { + return mid; + } + } + return -1; + } + Enter string: break, float and double are c keywords. float and double are primitive data types. The string entered is: break, float and double are c keywords. float and double are primitive data types. *********************** + Keyword Count + *********************** + break 1 + double 2 + float 2 \ No newline at end of file diff --git a/c/Basic/C Program to Display Function without using the Main Function.c b/c/Basic/C Program to Display Function without using the Main Function.c new file mode 100644 index 0000000..341a41b --- /dev/null +++ b/c/Basic/C Program to Display Function without using the Main Function.c @@ -0,0 +1,11 @@ +/* + * C Program to display function without using the Main Function + */ +#include +#define decode(s,t,u,m,p,e,d) m##s##u##t +#define begin decode(a,n,i,m,a,t,e) + +int begin() +{ + printf(" helloworld "); +} \ No newline at end of file diff --git a/c/Basic/C Program to Display its own Source Code as its Output.c b/c/Basic/C Program to Display its own Source Code as its Output.c new file mode 100644 index 0000000..3761ab8 --- /dev/null +++ b/c/Basic/C Program to Display its own Source Code as its Output.c @@ -0,0 +1,19 @@ +/* + * C Program to Display its own Source Code as its Output + */ +#include + +int main() +{ + FILE *fp; + char ch; + fp = fopen(__FILE__,"r"); + do + { + ch = getc(fp); + putchar(ch); + } + while (ch != EOF); + fclose(fp); + return 0; +} \ No newline at end of file diff --git a/c/Basic/C Program to Display the ATM Transaction.c b/c/Basic/C Program to Display the ATM Transaction.c new file mode 100644 index 0000000..5bf2c56 --- /dev/null +++ b/c/Basic/C Program to Display the ATM Transaction.c @@ -0,0 +1,72 @@ +/* + * C Program to Display the ATM Transaction + */ +#include + +unsigned long amount=1000, deposit, withdraw; +int choice, pin, k; +char transaction ='y'; + +void main() +{ + while (pin != 1520) + { + printf("ENTER YOUR SECRET PIN NUMBER:"); + scanf("%d", &pin); + if (pin != 1520) + printf("PLEASE ENTER VALID PASSWORD\n"); + } + do + { + printf("********Welcome to ATM Service**************\n"); + printf("1. Check Balance\n"); + printf("2. Withdraw Cash\n"); + printf("3. Deposit Cash\n"); + printf("4. Quit\n"); + printf("******************?**************************?*\n\n"); + printf("Enter your choice: "); + scanf("%d", &choice); + switch (choice) + { + case 1: + printf("\n YOUR BALANCE IN Rs : %lu ", amount); + break; + case 2: + printf("\n ENTER THE AMOUNT TO WITHDRAW: "); + scanf("%lu", &withdraw); + if (withdraw % 100 != 0) + { + printf("\n PLEASE ENTER THE AMOUNT IN MULTIPLES OF 100"); + } + else if (withdraw >(amount - 500)) + { + printf("\n INSUFFICENT BALANCE"); + } + else + { + amount = amount - withdraw; + printf("\n\n PLEASE COLLECT CASH"); + printf("\n YOUR CURRENT BALANCE IS%lu", amount); + } + break; + case 3: + printf("\n ENTER THE AMOUNT TO DEPOSIT"); + scanf("%lu", &deposit); + amount = amount + deposit; + printf("YOUR BALANCE IS %lu", amount); + break; + case 4: + printf("\n THANK U USING ATM"); + break; + default: + printf("\n INVALID CHOICE"); + } + printf("\n\n\n DO U WISH TO HAVE ANOTHER TRANSCATION?(y/n): \n"); + fflush(stdin); + scanf("%c", &transaction); + if (transaction == 'n'|| transaction == 'N') + k = 1; + } + while (!k); + printf("\n\n THANKS FOR USING OUT ATM SERVICE"); +} \ No newline at end of file diff --git a/c/Basic/C Program to Display the IP Address of the System.c b/c/Basic/C Program to Display the IP Address of the System.c new file mode 100644 index 0000000..cd17094 --- /dev/null +++ b/c/Basic/C Program to Display the IP Address of the System.c @@ -0,0 +1,29 @@ +/* + * C Program to Get IP Address + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main() +{ + int n; + struct ifreq ifr; + char array[] = "eth0"; + n = socket(AF_INET, SOCK_DGRAM, 0); + //Type of address to retrieve - IPv4 IP address + ifr.ifr_addr.sa_family = AF_INET; + //Copy the interface name in the ifreq structure + strncpy(ifr.ifr_name, array, IFNAMSIZ - 1); + ioctl(n, SIOCGIFADDR, &ifr); + close(n); + //display result + printf("IP Address is %s - %s\n", array, inet_ntoa(( (struct sockaddr_in *)&ifr.ifr_addr )->sin_addr) ); + return 0; +} \ No newline at end of file diff --git a/c/Basic/C Program to Display the Inventory of Items in a Store.c b/c/Basic/C Program to Display the Inventory of Items in a Store.c new file mode 100644 index 0000000..2743de2 --- /dev/null +++ b/c/Basic/C Program to Display the Inventory of Items in a Store.c @@ -0,0 +1,62 @@ +/* + * C program to display the inventory of items in a store / shop + * The inventory maintains details such as name, price, quantity + * and manufacturing date of each item. + */ +#include + +void main() +{ + struct date + { + int day; + int month; + int year; + }; + struct details + { + char name[20]; + int price; + int code; + int qty; + struct date mfg; + }; + struct details item[50]; + int n, i; + printf("Enter number of items:"); + scanf("%d", &n); + fflush(stdin); + for (i = 0; i < n; i++) + { + fflush(stdin); + printf("Item name: \n"); + scanf("%s", item[i].name); + fflush(stdin); + printf("Item code: \n"); + scanf("%d", &item[i].code); + fflush(stdin); + printf("Quantity: \n"); + scanf("%d", &item[i].qty); + fflush(stdin); + printf("price: \n"); + scanf("%d", &item[i].price); + fflush(stdin); + printf("Manufacturing date(dd-mm-yyyy): \n"); + scanf("%d-%d-%d", &item[i].mfg.day, + &item[i].mfg.month, &item[i].mfg.year); + } + printf(" ***** INVENTORY ***** \n"); + printf("--------------------------------------------------------- + ---------\n"); + printf("S.N.| NAME | CODE | QUANTITY | PRICE + | MFG.DATE \n"); + printf("--------------------------------------------------------- + ---------\n"); + for (i = 0; i < n; i++) + printf("%d %-15s %-d %-5d %-5d + %d/%d/%d \n", i + 1, item[i].name, item[i].code, item[i].qty, + item[i].price, item[i].mfg.day, item[i].mfg.month, + item[i].mfg.year); + printf("--------------------------------------------------------- + ---------\n"); +} \ No newline at end of file diff --git a/c/Basic/C Program to Extract Last two Digits of a given Year.c b/c/Basic/C Program to Extract Last two Digits of a given Year.c new file mode 100644 index 0000000..264433f --- /dev/null +++ b/c/Basic/C Program to Extract Last two Digits of a given Year.c @@ -0,0 +1,14 @@ +/* + * C Program to Extract Last two Digits of a given Year + */ +#include + +int main() +{ + int year, yr; + printf("Enter the year "); + scanf("%d", &year); + yr = year % 100; + printf("Last two digits of year is: %02d", yr); + return 0; +} \ No newline at end of file diff --git a/c/Basic/C Program to Find Multiplication of two Binary Numbers.c b/c/Basic/C Program to Find Multiplication of two Binary Numbers.c new file mode 100644 index 0000000..ee3c77e --- /dev/null +++ b/c/Basic/C Program to Find Multiplication of two Binary Numbers.c @@ -0,0 +1,50 @@ +/* + * C Program to Find Multiplication of two Binary Numbers + */ +#include + +int binaryproduct(int, int); + +int main() +{ + long binary1, binary2, multiply = 0; + int digit, factor = 1; + printf("Enter the first binary number: "); + scanf("%ld", &binary1); + printf("Enter the second binary number: "); + scanf("%ld", &binary2); + while (binary2 != 0) + { + digit = binary2 % 10; + if (digit == 1) + { + binary1 = binary1 * factor; + multiply = binaryproduct(binary1, multiply); + } + else + binary1 = binary1 * factor; + binary2 = binary2 / 10; + factor = 10; + } + printf("Product of two binary numbers: %ld", multiply); + return 0; +} + +int binaryproduct(int binary1, int binary2) +{ + int i = 0, remainder = 0, sum[20]; + int binaryprod = 0; + while (binary1 != 0 || binary2 != 0) + { + sum[i++] =(binary1 % 10 + binary2 % 10 + remainder) % 2; + remainder =(binary1 % 10 + binary2 % 10 + remainder) / 2; + binary1 = binary1 / 10; + binary2 = binary2 / 10; + } + if (remainder != 0) + sum[i++] = remainder; + --i; + while (i >= 0) + binaryprod = binaryprod * 10 + sum[i--]; + return binaryprod; +} \ No newline at end of file diff --git a/c/Basic/C Program to Find Product of 2 Numbers without using Recursion.c b/c/Basic/C Program to Find Product of 2 Numbers without using Recursion.c new file mode 100644 index 0000000..dbfc6c0 --- /dev/null +++ b/c/Basic/C Program to Find Product of 2 Numbers without using Recursion.c @@ -0,0 +1,28 @@ +/* + * C Program to find Product of 2 Numbers without using Recursion + */ + +#include + +int product(int, int); + +int main() +{ + int a, b, result; + printf("Enter two numbers to find their product: "); + scanf("%d%d", &a, &b); + result = product(a, b); + printf("Product of %d and %d is %d\n", a, b, result); + return 0; +} + +int product(int a, int b) +{ + int temp = 0; + while (b != 0) + { + temp += a; + b--; + } + return temp; +} \ No newline at end of file diff --git a/c/Basic/C Program to Find Sum of Digits of a Number using Recursion.c b/c/Basic/C Program to Find Sum of Digits of a Number using Recursion.c new file mode 100644 index 0000000..69b3469 --- /dev/null +++ b/c/Basic/C Program to Find Sum of Digits of a Number using Recursion.c @@ -0,0 +1,28 @@ +/* + * C Program to find Sum of Digits of a Number using Recursion + */ +#include + +int sum (int a); + +int main() +{ + int num, result; + printf("Enter the number: "); + scanf("%d", &num); + result = sum(num); + printf("Sum of digits in %d is %d\n", num, result); + return 0; +} + +int sum (int num) +{ + if (num != 0) + { + return (num % 10 + sum (num / 10)); + } + else + { + return 0; + } +} \ No newline at end of file diff --git a/c/Basic/C Program to Find if a given Year is a Leap Year.c b/c/Basic/C Program to Find if a given Year is a Leap Year.c new file mode 100644 index 0000000..ca70afa --- /dev/null +++ b/c/Basic/C Program to Find if a given Year is a Leap Year.c @@ -0,0 +1,17 @@ +/* + * C program to find whether a given year is leap year or not + */ +void main() +{ + int year; + printf("Enter a year \n"); + scanf("%d", &year); + if ((year % 400) == 0) + printf("%d is a leap year \n", year); + else if ((year % 100) == 0) + printf("%d is a not leap year \n", year); + else if ((year % 4) == 0) + printf("%d is a leap year \n", year); + else + printf("%d is not a leap year \n", year); +} \ No newline at end of file diff --git a/c/Basic/C Program to Find the Biggest of 3 Numbers.c b/c/Basic/C Program to Find the Biggest of 3 Numbers.c new file mode 100644 index 0000000..ae98224 --- /dev/null +++ b/c/Basic/C Program to Find the Biggest of 3 Numbers.c @@ -0,0 +1,27 @@ +/* + * C program to find the biggest of three numbers + */ +#include + +void main() +{ + int num1, num2, num3; + printf("Enter the values of num1, num2 and num3\n"); + scanf("%d %d %d", &num1, &num2, &num3); + printf("num1 = %d\tnum2 = %d\tnum3 = %d\n", num1, num2, num3); + if (num1 > num2) + { + if (num1 > num3) + { + printf("num1 is the greatest among three \n"); + } + else + { + printf("num3 is the greatest among three \n"); + } + } + else if (num2 > num3) + printf("num2 is the greatest among three \n"); + else + printf("num3 is the greatest among three \n"); +} \ No newline at end of file diff --git a/c/Basic/C Program to Find the First Occurence of the any Character of String2 in string1 & also its Position.c b/c/Basic/C Program to Find the First Occurence of the any Character of String2 in string1 & also its Position.c new file mode 100644 index 0000000..1f35305 --- /dev/null +++ b/c/Basic/C Program to Find the First Occurence of the any Character of String2 in string1 & also its Position.c @@ -0,0 +1,51 @@ +/* +/* +* C Program to Find the First Occurence of the any Character of +* String2 in string1 & also its Position +*/ +#include + +void main() +{ + char s1[50], s2[10]; + int i, flag = 0; + char *ptr1, *ptr2; + printf(" + enter the string1:"); + scanf(" %[^ + ]s", s1); + printf(" + enter the string2:"); + scanf(" %[^ + ]s", s2); + /*COMPARING THE STRING1 CHARACTER BY CHARACTER WITH ALL CHARACTERS OF STRING1*/ + for (i = 0, ptr1 = s1; *ptr1 != ''; ptr1++) + { + i++; + for (ptr2 = s2; *ptr2 != ''; ptr2++) + { + if (*ptr1 == *ptr2) + { + flag = 1; + break; + } + } + if (flag == 1) + break; + } + if (flag == 1) + printf(" + first occurance of character of string2 in string1 is at position:%d and character is %c", i, *ptr2); + else + printf(" + none of the characters of string1 match with mone of characters of string2"); + } + + + enter the string1: + C Programming Class + + enter the string2: + rnp + + first occurance of character of string2 in string1 is at position:3 and character is p \ No newline at end of file diff --git a/c/Basic/C Program to Find the Number of Integers Divisible by 5.c b/c/Basic/C Program to Find the Number of Integers Divisible by 5.c new file mode 100644 index 0000000..fb186f5 --- /dev/null +++ b/c/Basic/C Program to Find the Number of Integers Divisible by 5.c @@ -0,0 +1,29 @@ +/* + * C program to find the number of integers divisible by + * 5 between the given range num1 and num2, where num1 < num2. + * + * Also find the sum of all these integer numbers which are divisible + * by 5 and display the total. + */ +#include + +void main() +{ + int i, num1, num2, count = 0, sum = 0; + printf("Enter the value of num1 and num2 \n"); + scanf("%d %d", &num1, &num2); + /* Count the number and compute their sum*/ + printf("Integers divisible by 5 are \n"); + for (i = num1; i < num2; i++) + { + if (i % 5 == 0) + { + printf("%3d,", i); + count++; + sum = sum + i; + } + } + printf("\n Number of integers divisible by 5 between %d and %d = + %d\n", num1, num2, count); + printf("Sum of all integers that are divisible by 5 = %d\n", sum); +} \ No newline at end of file diff --git a/c/Basic/C Program to Find the Size of a Union.c b/c/Basic/C Program to Find the Size of a Union.c new file mode 100644 index 0000000..c7b8b4e --- /dev/null +++ b/c/Basic/C Program to Find the Size of a Union.c @@ -0,0 +1,23 @@ +/* + * C program to find the size of a union + */ +#include + +void main() +{ + union sample + { + int m; + float n; + char ch; + }; + union sample u; + printf("The size of union = %d\n", sizeof(u)); + /* initialization */ + u.m = 25; + printf("%d %f %c\n", u.m, u.n, u.ch); + u.n = 0.2; + printf("%d %f %c\n", u.m, u.n, u.ch); + u.ch = 'p'; + printf("%d %f %c\n", u.m, u.n, u.ch); +} \ No newline at end of file diff --git a/c/Basic/C Program to Find the Sum of first 50 Natural Numbers using For Loop.c b/c/Basic/C Program to Find the Sum of first 50 Natural Numbers using For Loop.c new file mode 100644 index 0000000..90405f7 --- /dev/null +++ b/c/Basic/C Program to Find the Sum of first 50 Natural Numbers using For Loop.c @@ -0,0 +1,15 @@ +/* + * C program to find the sum of first 50 natural numbers + * using for loop + */ +#include + +void main() +{ + int num, sum = 0; + for (num = 1; num <= 50; num++) + { + sum = sum + num; + } + printf("Sum = %4d\n", sum); +} \ No newline at end of file diff --git a/c/Basic/C Program to Find the Sum of two Binary Numbers.c b/c/Basic/C Program to Find the Sum of two Binary Numbers.c new file mode 100644 index 0000000..b21c4f3 --- /dev/null +++ b/c/Basic/C Program to Find the Sum of two Binary Numbers.c @@ -0,0 +1,28 @@ +/* + * C Program to Find the Sum of two Binary Numbers + */ +#include + +int main() +{ + long binary1, binary2; + int i = 0, remainder = 0, sum[20]; + printf("Enter the first binary number: "); + scanf("%ld", &binary1); + printf("Enter the second binary number: "); + scanf("%ld", &binary2); + while (binary1 != 0 || binary2 != 0) + { + sum[i++] =(binary1 % 10 + binary2 % 10 + remainder) % 2; + remainder =(binary1 % 10 + binary2 % 10 + remainder) / 2; + binary1 = binary1 / 10; + binary2 = binary2 / 10; + } + if (remainder != 0) + sum[i++] = remainder; + --i; + printf("Sum of two binary numbers: "); + while (i >= 0) + printf("%d", sum[i--]); + return 0; +} \ No newline at end of file diff --git a/c/Basic/C Program to Find whether a Number is Prime or Not using Recursion.c b/c/Basic/C Program to Find whether a Number is Prime or Not using Recursion.c new file mode 100644 index 0000000..42f2d56 --- /dev/null +++ b/c/Basic/C Program to Find whether a Number is Prime or Not using Recursion.c @@ -0,0 +1,42 @@ +/* + * C Program to find whether a Number is Prime or Not using Recursion + */ +#include + +int primeno(int, int); + +int main() +{ + int num, check; + printf("Enter a number: "); + scanf("%d", &num); + check = primeno(num, num / 2); + if (check == 1) + { + printf("%d is a prime number\n", num); + } + else + { + printf("%d is not a prime number\n", num); + } + return 0; +} + +int primeno(int num, int i) +{ + if (i == 1) + { + return 1; + } + else + { + if (num % i == 0) + { + return 0; + } + else + { + return primeno(num, i - 1); + } + } +} \ No newline at end of file diff --git a/c/Basic/C Program to Generate Fibonacci Series.c b/c/Basic/C Program to Generate Fibonacci Series.c new file mode 100644 index 0000000..4a41836 --- /dev/null +++ b/c/Basic/C Program to Generate Fibonacci Series.c @@ -0,0 +1,24 @@ +/* + * C program to generate Fibonacci Series. Fibonacci Series + * is 0 1 1 2 3 5 8 13 21 ... + */ +#include + +void main() +{ + int fib1 = 0, fib2 = 1, fib3, limit, count = 0; + printf("Enter the limit to generate the Fibonacci Series \n"); + scanf("%d", &limit); + printf("Fibonacci Series is ...\n"); + printf("%d\n", fib1); + printf("%d\n", fib2); + count = 2; + while (count < limit) + { + fib3 = fib1 + fib2; + count++; + printf("%d\n", fib3); + fib1 = fib2; + fib2 = fib3; + } +} \ No newline at end of file diff --git a/c/Basic/C Program to Illustrate Pass by Reference.c b/c/Basic/C Program to Illustrate Pass by Reference.c new file mode 100644 index 0000000..9606030 --- /dev/null +++ b/c/Basic/C Program to Illustrate Pass by Reference.c @@ -0,0 +1,19 @@ +/* + * C Program to Illustrate Pass by Reference + */ +#include + +void cube( int *x); + +int main() +{ + int num = 10; + cube(&num); + printf("the cube of the given number is %d", num); + return 0; +} + +void cube(int *x) +{ + *x = (*x) * (*x) * (*x); +} \ No newline at end of file diff --git a/c/Basic/C Program to Illustrate Pass by Value.c b/c/Basic/C Program to Illustrate Pass by Value.c new file mode 100644 index 0000000..943bc16 --- /dev/null +++ b/c/Basic/C Program to Illustrate Pass by Value.c @@ -0,0 +1,21 @@ +/* + * C Program to Illustrate Pass by Value. + */ +#include + +void swap(int a, int b) +{ + int temp; + temp = a; + a = b; + b = temp; +} + +int main() +{ + int num1 = 10, num2 = 20; + printf("Before swapping num1 = %d num2 = %d\n", num1, num2); + swap(num1, num2); + printf("After swapping num1 = %d num2 = %d \n", num2, num1); + return 0; +} \ No newline at end of file diff --git a/c/Basic/C Program to Illustrate how User Authentication is Done.c b/c/Basic/C Program to Illustrate how User Authentication is Done.c new file mode 100644 index 0000000..a860cb5 --- /dev/null +++ b/c/Basic/C Program to Illustrate how User Authentication is Done.c @@ -0,0 +1,29 @@ +/* + * C program is to illustrate how user authentication is done. + * Program asks for the user name and password and displays + * the password as '*' character + */ +#include + +void main() +{ + char password[10], username[10], ch; + int i; + printf("Enter User name: "); + gets(username); + printf("Enter the password < any 8 characters>: "); + for (i = 0; i < 8; i++) + { + ch = getchar(); + password[i] = ch; + ch = '*' ; + printf("%c", ch); + } + password[i] = '\0'; + /* Original password can be printed, if needed */ + printf("\n Your password is :"); + for (i = 0; i < 8; i++) + { + printf("%c", password[i]); + } +} \ No newline at end of file diff --git a/c/Basic/C Program to Illustrate the Concept of Unions.c b/c/Basic/C Program to Illustrate the Concept of Unions.c new file mode 100644 index 0000000..3902e90 --- /dev/null +++ b/c/Basic/C Program to Illustrate the Concept of Unions.c @@ -0,0 +1,20 @@ +/* + * C program to illustrate the concept of unions + */ +#include + +void main() +{ + union number + { + int n1; + float n2; + }; + union number x; + printf("Enter the value of n1: "); + scanf("%d", &x.n1); + printf("Value of n1 = %d", x.n1); + printf("\nEnter the value of n2: "); + scanf("%f", &x.n2); + printf("Value of n2 = %f\n", x.n2); +} \ No newline at end of file diff --git a/c/Basic/C Program to Implements Regular Expression Matching.c b/c/Basic/C Program to Implements Regular Expression Matching.c new file mode 100644 index 0000000..e6e5a26 --- /dev/null +++ b/c/Basic/C Program to Implements Regular Expression Matching.c @@ -0,0 +1,295 @@ +/* +* C Program to Implements Regular Expression Matching +*/ +#include +#include +#define MATCH printf(" +The Text Matches The Regular Expression"); +#define NOTMATCH printf(" +The Text Doesn't match the Regular Expression"); + +char reg[20], text[20]; +int main() +{ + int i, rlen, tlen, f = 0; + char ans; + do + { + printf(" + Enter the Regular Expression + "); + scanf(" %[^ + ]s", reg); + for (rlen = 0; reg[rlen] != ''; rlen++); + printf(" + Enter the text + "); + scanf(" %[^ + ]s", text); + for (tlen = 0; text[tlen] != '' ; tlen++); + if (reg[0] == '*') + { + printf(" + Invalid regular expression"); + } + /* + *If the regular expression starts with Alphabet + */ + if ((reg[0] >= 65 && reg[0] <= 90) || (reg[0] >= 97 && reg[0] <=122)) + { + if (reg[0] == text [0]) + { + switch (reg[1]) + { + case '.' : + switch (reg[2]) + { + case '*': + if (tlen != 1) + { + if (reg[3] == text[tlen-1]) + { + MATCH; + } + else + { + NOTMATCH; + } + } + else + { + NOTMATCH; + } + break; + case '+': + if (text[1] != reg[3]) + { + if (reg[3] == text[tlen - 1]) + { + MATCH; + } + else + { + NOTMATCH; + } + } + break; + case '?': + if (text[1] == reg[3] || text[2] == reg[3]) + { + if (text[1] == reg[3] || text[2] == reg[3]) + { + MATCH; + } + else + { + NOTMATCH; + } + } + else + { + NOTMATCH; + } + break; + } + break; + case '*': + if (reg[rlen-1] == text[tlen-1]) + { + for (i = 0; i <= tlen-2; i++) + { + if(text[i] == reg[0]) + { + f = 1; + } + else + { + f = 0; + } + } + if ( f == 1) + { + MATCH; + } + else + { + NOTMATCH; + } + } + else + { + NOTMATCH; + } + break; + case '+' : + if (tlen <= 2) + { + NOTMATCH; + } + else if (reg[rlen-1] == text[tlen-1]) + { + for (i = 0; i < tlen-2; i++) + { + if (text[i] == reg[0]) + { + f = 1; + } + else + { + f = 0; + } + } + if (f == 1) + { + MATCH; + } + else + { + NOTMATCH; + } + } + break; + case '?': + if (reg[rlen -1] == text[tlen-1]) + { + MATCH; + } + else + { + NOTMATCH; + } + break; + } + } + else + printf("Does not match"); + } + /* + *If Regular Expression starts with '^' + */ + else if (reg[0] == '^') + { + if (reg[1] == text[0]) + { + MATCH; + } + else + { + NOTMATCH; + } + } + /* + *If Regular Expression Ends with '$' + */ + else if (reg[rlen-1] == '$') + { + if (reg[rlen-2] == text[rlen-1]) + { + MATCH; + } + else + { + NOTMATCH; + } + } + else + printf("Not Implemented"); + printf(" + Do you want to continue?(Y/N)"); + scanf(" %c", &ans); + } + while (ans == 'Y' || ans == 'y'); +} + + +Enter the Regular Expression +C.*g + +Enter the text +Cprogramming + +The Text Matches The Regular Expression +Do you want to continue?(Y/N)y + +Enter the Regular Expression +C*g + +Enter the text +Cprogramming + +The Text Doesn't match the Regular Expression +Do you want to continue?(Y/N)y + +Enter the Regular Expression +C?.*g + +Enter the text +Cprogramming + +The Text Matches The Regular Expression +Do you want to continue?(Y/N)y + +Enter the Regular Expression +C.?g + +Enter the text +Cprogramming + +The Text Doesn't match the Regular Expression +Do you want to continue?(Y/N)y + +Enter the Regular Expression +C.+g + +Enter the text +Cprogramming + +The Text Matches The Regular Expression +Do you want to continue?(Y/N)y + +Enter the Regular Expression +C+g + +Enter the text +Cprogramming + +The Text Doesn't match the Regular Expression +Do you want to continue?(Y/N)y + +Enter the Regular Expression + +^C.* + +Enter the text +Cprogramming + + +The Text Matches The Regular Expression +Do you want to continue?(Y/N)y + +Enter the Regular Expression +^p.* + +Enter the text +Cprogramming + +The Text Doesn't match the Regular Expression +Do you want to continue?(Y/N)y + +Enter the Regular Expression +C.*g$ + +Enter the text +Cprogramming + +The Text Matches The Regular Expression +Do you want to continue?(Y/N)y + +Enter the Regular Expression +C.*n$ + +Enter the text +Cprogramming + +The Text Doesn't match the Regular Expression +Do you want to continue?(Y/N)n \ No newline at end of file diff --git a/c/Basic/C Program to Input 2 Binary Strings and Print their Binary Sum.c b/c/Basic/C Program to Input 2 Binary Strings and Print their Binary Sum.c new file mode 100644 index 0000000..0ad47e1 --- /dev/null +++ b/c/Basic/C Program to Input 2 Binary Strings and Print their Binary Sum.c @@ -0,0 +1,117 @@ +/* +* C Program to Input 2 Binary Strings and Print their Binary +* Sum +*/ +#include +#include +#include + +int bin_verify(char []); +void sum(char [], char [], char []); + +int main() +{ + char bin1[33], bin2[33], result[33]; + int len1, len2, check; + printf("Enter binary number 1: "); + scanf("%s", bin1); + printf("Enter binary number 2: "); + scanf("%s", bin2); + check = bin_verify(bin1); + if (check) + { + printf("Invalid binary number %s. + ", bin1); + exit(0); + } + check = bin_verify(bin2); + if (check) + { + printf("Invalid binary number %s. + ", bin2); + exit(0); + } + sum(bin1, bin2, result); + printf("%s + %s = %s + ", bin1, bin2, result); + return 0; +} + +int bin_verify(char str[]) +{ + int i; + for (i = 0; i < strlen(str); i++) + { + if ((str[i] - '0' != 1 ) && (str[i] - '0' != 0)) + { + return 1; + } + } + return 0; +} + +void sum(char bin1[], char bin2[], char result[]) +{ + int i = strlen(bin1) - 1; + int j = strlen(bin2) - 1; + int carry = 0, temp, num1, num2; + while (i > -1 && j > -1) + { + num1 = bin1[i] - '0'; + num2 = bin2[j] - '0'; + temp = num1 + num2 + carry; + if (temp / 2 == 1) + { + carry = 1; + temp %= 2; + } + if (i > j) + { + result[i + 1] = temp + '0'; + result[strlen(bin1) + 1] = ''; + } + else + { + result[j +1] = temp + '0'; + result[strlen(bin2) + 1] = ''; + } + i--; + j--; + } + while (i > -1) + { + temp = bin1[i] + carry - '0'; + if (temp / 2 == 1) + { + carry = 1; + temp %= 2; + } + result[i + 1] = temp + '0'; + i--; + } + while (j > -1) + { + temp = bin2[j] + carry - '0'; + if (temp / 2 == 1) + { + carry = 1; + temp %= 2; + } + result[j + 1] = temp + '0'; + j--; + } + if (carry) + { + result[0] = '1'; + } + else + { + result[0] = '0'; + } +} + + + +Enter binary number 1: 0110 +Enter binary number 2: 1011 +0110 + 1011 = 10001 diff --git a/c/Basic/C Program to Input 3 Arguments and Operate Appropriately on the Numbers.c b/c/Basic/C Program to Input 3 Arguments and Operate Appropriately on the Numbers.c new file mode 100644 index 0000000..7ef0d69 --- /dev/null +++ b/c/Basic/C Program to Input 3 Arguments and Operate Appropriately on the Numbers.c @@ -0,0 +1,35 @@ +/* + * C Program to Input 3 Arguments and Operate Appropriately on the + * Numbers + */ +#include + +void main(int argc, char * argv[]) +{ + int a, b, result; + char ch; + printf("arguments entered: \n"); + a = atoi(argv[1]); + b = atoi(argv[2]); + ch = *argv[3]; + printf("%d %d %c", a, b, ch); + switch (ch) + { + case '+': + result = a + b; + break; + case '-': + result = a - b; + break; + case 'x': + result = a * b; + break; + case '/': + result = a / b; + break; + default: + printf("Enter a valid choice"); + } + printf("\nThe result of the operation is %d", result); + printf("\n"); +} \ No newline at end of file diff --git a/c/Basic/C Program to Maintain an Inventory of items in Online Store.c b/c/Basic/C Program to Maintain an Inventory of items in Online Store.c new file mode 100644 index 0000000..478d584 --- /dev/null +++ b/c/Basic/C Program to Maintain an Inventory of items in Online Store.c @@ -0,0 +1,47 @@ + #include + #include + void main() { + struct date { + int day; + int month; + int year; + }; + struct details { + char name[20]; + int price; + int code; + int qty; + struct date mfg; + }; + struct details item[50]; + int n,i; + clrscr(); + printf("Enter number of items:"); + scanf("%d",&n); + fflush(stdin); + for (i=0;i + +void main() +{ + long number, tempnum; + printf("Enter an integer \n"); + scanf("%ld", &number); + tempnum = number; + /* left shift by two bits */ + number = number << 2; + printf("%ld x 4 = %ld\n", tempnum, number); +} \ No newline at end of file diff --git a/c/Basic/C Program to Print Armstrong Number from 1 to 1000.c b/c/Basic/C Program to Print Armstrong Number from 1 to 1000.c new file mode 100644 index 0000000..263eb55 --- /dev/null +++ b/c/Basic/C Program to Print Armstrong Number from 1 to 1000.c @@ -0,0 +1,23 @@ +/* + * C Program to Print Armstrong Number from 1 to 1000 + */ +#include + +main() +{ + int number, temp, digit1, digit2, digit3; + printf("Print all Armstrong numbers between 1 and 1000:\n"); + number = 001; + while (number <= 900) + { + digit1 = number - ((number / 10) * 10); + digit2 = (number / 10) - ((number / 100) * 10); + digit3 = (number / 100) - ((number / 1000) * 10); + temp = (digit1 * digit1 * digit1) + (digit2 * digit2 * digit2) + (digit3 * digit3 * digit3); + if (temp == number) + { + printf("\n Armstrong no is:%d", temp); + } + number++; + } +} \ No newline at end of file diff --git a/c/Basic/C Program to Print Binary Equivalent of an Integer using Recursion.c b/c/Basic/C Program to Print Binary Equivalent of an Integer using Recursion.c new file mode 100644 index 0000000..5e26e51 --- /dev/null +++ b/c/Basic/C Program to Print Binary Equivalent of an Integer using Recursion.c @@ -0,0 +1,28 @@ +/* + * C Program to Print Binary Equivalent of an Integer using Recursion + */ +#include + +int binary_conversion(int); + +int main() +{ + int num, bin; + printf("Enter a decimal number: "); + scanf("%d", &num); + bin = binary_conversion(num); + printf("The binary equivalent of %d is %d\n", num, bin); +} + +int binary_conversion(int num) +{ + if (num == 0) + { + return 0; + } + else + { + return (num % 2) + 10 * binary_conversion(num / 2); + } +} +} \ No newline at end of file diff --git a/c/Basic/C Program to Print Combination of two Words of two given Strings without any Repetition.c b/c/Basic/C Program to Print Combination of two Words of two given Strings without any Repetition.c new file mode 100644 index 0000000..ea4b4f0 --- /dev/null +++ b/c/Basic/C Program to Print Combination of two Words of two given Strings without any Repetition.c @@ -0,0 +1,48 @@ +/* +* C Program to Print Combination of two Words of two +* given Strings without any Repetition +*/ +#include +#include + +void main() +{ + char string[100], str[10], c[10]; + int z, occ = 0, i = 0, j = 0, count = 0, len = 0; + printf("Enter a string:"); + scanf("%[^ + ]s", string); + printf("Enter the word to check its occurence:"); + scanf("%s", str); + len = strlen(str); + for (i = 0; string[i] != ''; i++) + { + count = 0; + for (j = 0, z = i; j < len; j++, z++) + { + c[j] = string[z]; + if (c[j] == str[j]) + { + count++; /* Incrementing the count if the characters of the main string match with the characters of the given word */ + } + } + if (count == len && string[z] == ' ') + { + occ++; /* Incrementing the occ if word matches completely and next character in string is space */ + } + } + printf("The number of occ is %d + ", occ); +} + +Enter a string: +welcome to illumin8's c programming class, welcome again to c class +Enter the word to check its occurence: +welcome +The number of occ is 2 + +Enter a string: +welcome to illumin8's c programming class, welcome again to c class +Enter the word to check its occurence: +c +The number of occ is 2 diff --git a/c/Basic/C Program to Print Diamond Pattern.c b/c/Basic/C Program to Print Diamond Pattern.c new file mode 100644 index 0000000..1687a5d --- /dev/null +++ b/c/Basic/C Program to Print Diamond Pattern.c @@ -0,0 +1,42 @@ +/* + * C Program to Print Diamond Pattern + */ +#include + +int main() +{ + int number, i, k, count = 1; + printf("Enter number of rows\n"); + scanf("%d", &number); + count = number - 1; + for (k = 1; k <= number; k++) + { + for (i = 1; i <= count; i++) + printf(" "); + count--; + for (i = 1; i <= 2 * k - 1; i++) + printf("*"); + printf("\n"); + } + count = 1; + for (k = 1; k <= number - 1; k++) + { + for (i = 1; i <= count; i++) + printf(" "); + count++; + for (i = 1 ; i <= 2 *(number - k)- 1; i++) + printf("*"); + printf("\n"); + } + return 0; +} + +/* + * + *** + ***** + ******* +********* + ******* + ***** + *** \ No newline at end of file diff --git a/c/Basic/C Program to Print a Semicolon without using a Semicolon anywhere in the Code.c b/c/Basic/C Program to Print a Semicolon without using a Semicolon anywhere in the Code.c new file mode 100644 index 0000000..6bb4f8d --- /dev/null +++ b/c/Basic/C Program to Print a Semicolon without using a Semicolon anywhere in the Code.c @@ -0,0 +1,14 @@ +/* + * C Program to Print a Semicolon without using a Semicolon + * anywhere in the code + */ +#include + +int main(void) +{ + //59 is the ascii value of semicolumn + if (printf("%c ", 59)) + { + } + return 0; +} \ No newline at end of file diff --git a/c/Basic/C Program to Print any Print Statement without using Semicolon.c b/c/Basic/C Program to Print any Print Statement without using Semicolon.c new file mode 100644 index 0000000..1c6472d --- /dev/null +++ b/c/Basic/C Program to Print any Print Statement without using Semicolon.c @@ -0,0 +1,11 @@ +/* + * C Program to Print any Print Statement without using Semicolon + */ +#include + +void main() +{ + if(printf("Hi.. Welcome to sanfoundry")) + { + } +} \ No newline at end of file diff --git a/c/Basic/C Program to Print the Program Name and All its Arguments.c b/c/Basic/C Program to Print the Program Name and All its Arguments.c new file mode 100644 index 0000000..af6f1cd --- /dev/null +++ b/c/Basic/C Program to Print the Program Name and All its Arguments.c @@ -0,0 +1,14 @@ +/* + * C Program to Print the Program Name and All its Arguments + */ +#include + +void main(int argc, char *argv[]) /* command line Arguments */ +{ + int i; + for (i = 0; i < argc; i++) + { + printf("%s ", argv[i]); /* Printing the string */ + } + printf("\n"); +} \ No newline at end of file diff --git a/c/Basic/C Program to Print the Words Ending with Letter S.c b/c/Basic/C Program to Print the Words Ending with Letter S.c new file mode 100644 index 0000000..46a8dc3 --- /dev/null +++ b/c/Basic/C Program to Print the Words Ending with Letter S.c @@ -0,0 +1,38 @@ +/* + * C Program to Print the Words Ending with Letter S +*/ +#include +#include + +char str[100]; + +void main() +{ + int i, t, j, len; + printf("Enter a string : "); + scanf("%[^ + ]s", str); + len = strlen(str); + str[len] = ' '; + for (t = 0, i = 0; i < strlen(str); i++) + { + if ((str[i] == ' ') && (str[i - 1] == 's')) + { + for (j = t; j < i; j++) + printf("%c", str[j]); + t = i + 1; + printf(" + "); + } + else + { + if (str[i] == ' ') + { + t = i + 1; + } + } + } +} + +Enter a string : +Welcome to Illumin8's C Programming Class, Welcome Again to C Class ! Illumin8's Class \ No newline at end of file diff --git a/c/Basic/C Program to Read Two Integers M and N & Swap their Values.c b/c/Basic/C Program to Read Two Integers M and N & Swap their Values.c new file mode 100644 index 0000000..715268e --- /dev/null +++ b/c/Basic/C Program to Read Two Integers M and N & Swap their Values.c @@ -0,0 +1,25 @@ +/* + * C program to read two integers M and N and to swap their values. + * Use a user-defined function for swapping. Output the values of M + * and N before and after swapping. + */ +#include +void swap(float *ptr1, float *ptr2); + +void main() +{ + float m, n; + printf("Enter the values of M and N \n"); + scanf("%f %f", &m, &n); + printf("Before Swapping:M = %5.2ftN = %5.2f\n", m, n); + swap(&m, &n); + printf("After Swapping:M = %5.2ftN = %5.2f\n", m, n); +} +/* Function swap - to interchanges the contents of two items */ +void swap(float *ptr1, float *ptr2) +{ + float temp; + temp = *ptr1; + *ptr1 = *ptr2; + *ptr2 = temp; +} \ No newline at end of file diff --git a/c/Basic/C Program to Read a Grade & Display the Equivalent Description.c b/c/Basic/C Program to Read a Grade & Display the Equivalent Description.c new file mode 100644 index 0000000..04a4516 --- /dev/null +++ b/c/Basic/C Program to Read a Grade & Display the Equivalent Description.c @@ -0,0 +1,43 @@ +/* + * C Program to accept a grade and declare the equivalent description + * if code is S, then print SUPER + * if code is A, then print VERY GOOD + * if code is B, then print FAIR + * if code is Y, then print ABSENT + * if code is F, then print FAILS + */ +#include +#include +#include + +void main() +{ + char remark[15]; + char grade; + printf("Enter the grade \n"); + scanf("%c", &grade); + /* lower case letter to upper case */ + grade = toupper(grade); + switch(grade) + { + case 'S': + strcpy(remark, " SUPER"); + break; + case 'A': + strcpy(remark, " VERY GOOD"); + break; + case 'B': + strcpy(remark, " FAIR"); + break; + case 'Y': + strcpy(remark, " ABSENT"); + break; + case 'F': + strcpy(remark, " FAILS"); + break; + default : + strcpy(remark, "ERROR IN GRADE \n"); + break; + } + printf("RESULT : %s\n", remark); +} \ No newline at end of file diff --git a/c/Basic/C Program to Reverse a Given Number.c b/c/Basic/C Program to Reverse a Given Number.c new file mode 100644 index 0000000..93af145 --- /dev/null +++ b/c/Basic/C Program to Reverse a Given Number.c @@ -0,0 +1,20 @@ +/* + * C program to accept an integer and reverse it + */ +#include + +void main() +{ + long num, reverse = 0, temp, remainder; + printf("Enter the number\n"); + scanf("%ld", &num); + temp = num; + while (num > 0) + { + remainder = num % 10; + reverse = reverse * 10 + remainder; + num /= 10; + } + printf("Given number = %ld\n", temp); + printf("Its reverse is = %ld\n", reverse); +} \ No newline at end of file diff --git a/c/Basic/C Program to Reverse a Number & Check if it is a Palindrome.c b/c/Basic/C Program to Reverse a Number & Check if it is a Palindrome.c new file mode 100644 index 0000000..e793701 --- /dev/null +++ b/c/Basic/C Program to Reverse a Number & Check if it is a Palindrome.c @@ -0,0 +1,27 @@ +/* + * C program to reverse a given integer number and check + * whether it is a palindrome. Display the given number + * with appropriate message + */ +#include + +void main() +{ + int num, temp, remainder, reverse = 0; + printf("Enter an integer \n"); + scanf("%d", &num); + /* original number is stored at temp */ + temp = num; + while (num > 0) + { + remainder = num % 10; + reverse = reverse * 10 + remainder; + num /= 10; + } + printf("Given number is = %d\n", temp); + printf("Its reverse is = %d\n", reverse); + if (temp == reverse) + printf("Number is a palindrome \n"); + else + printf("Number is not a palindrome \n"); +} \ No newline at end of file diff --git a/c/Basic/C Program to Search a Word & Replace it with the Specified Word.c b/c/Basic/C Program to Search a Word & Replace it with the Specified Word.c new file mode 100644 index 0000000..d32ec6f --- /dev/null +++ b/c/Basic/C Program to Search a Word & Replace it with the Specified Word.c @@ -0,0 +1,72 @@ +/* +* C Program to Search a Word & Replace it with the Specified Word +*/ +#include +#include +#include + +/*Function to replace a string with another string*/ + +char *rep_str(const char *s, const char *old, const char *new1) +{ + char *ret; + int i, count = 0; + int newlen = strlen(new1); + int oldlen = strlen(old); + for (i = 0; s[i] != ''; i++) + { + if (strstr(&s[i], old) == &s[i]) + { + count++; + i += oldlen - 1; + } + } + ret = (char *)malloc(i + count * (newlen - oldlen)); + if (ret == NULL) + exit(EXIT_FAILURE); + i = 0; + while (*s) + { + if (strstr(s, old) == s) //compare the substring with the newstring + { + strcpy(&ret[i], new1); + i += newlen; //adding newlength to the new string + s += oldlen;//adding the same old length the old string + } + else + ret[i++] = *s++; + } + ret[i] = ''; + return ret; +} + +int main(void) +{ + char mystr[100], c[10], d[10]; + printf("Enter a string along with characters to be rep_strd: + "); + gets(mystr); + printf("Enter the character to be rep_strd: + "); + scanf(" %s",c); + printf("Enter the new character: + "); + scanf(" %s",d); + char *newstr = NULL; + puts(mystr); + newstr = rep_str(mystr, c,d); + printf("%s + ", newstr); + free(newstr); + return 0; +} + + + Enter a string along with characters to be rep_strd: + prrrogram C prrrogramming + Enter the character to be rep_strd: + rr + Enter the new character: + mmm + prrrogram C prrrogramming + pmmmrogram C pmmmrogramming \ No newline at end of file diff --git a/c/Basic/C Program to Shutdown or Turn Off the Computer in Linux.c b/c/Basic/C Program to Shutdown or Turn Off the Computer in Linux.c new file mode 100644 index 0000000..a88db5b --- /dev/null +++ b/c/Basic/C Program to Shutdown or Turn Off the Computer in Linux.c @@ -0,0 +1,10 @@ +/* + * C Program to Shutdown or Turn Off the Computer in Linux. + */ +#include + +int main() +{ + system("shutdown -P now"); + return 0; +} \ No newline at end of file diff --git a/c/Basic/C Program to Swap the Contents of two Numbers using Bitwise XOR Operation.c b/c/Basic/C Program to Swap the Contents of two Numbers using Bitwise XOR Operation.c new file mode 100644 index 0000000..09f7b13 --- /dev/null +++ b/c/Basic/C Program to Swap the Contents of two Numbers using Bitwise XOR Operation.c @@ -0,0 +1,18 @@ +/* + * C program to swap the contents of two numbers using bitwise XOR + * operation. Don't use either the temporary variable or arithmetic + * operators + */ +#include + +void main() +{ + long i, k; + printf("Enter two integers \n"); + scanf("%ld %ld", &i, &k); + printf("\n Before swapping i= %ld and k = %ld", i, k); + i = i ^ k; + k = i ^ k; + i = i ^ k; + printf("\n After swapping i= %ld and k = %ld", i, k); +} \ No newline at end of file diff --git a/c/Basic/C Program to Use Bitwise Operations to Count the Number of Leading Zero's in a Number x.c b/c/Basic/C Program to Use Bitwise Operations to Count the Number of Leading Zero's in a Number x.c new file mode 100644 index 0000000..84eeefc --- /dev/null +++ b/c/Basic/C Program to Use Bitwise Operations to Count the Number of Leading Zero's in a Number x.c @@ -0,0 +1,114 @@ +/* +* C Program to Use Bitwise Operations to Count the Number of +* Leading Zero's in a Number x +*/ +#include +#include +#define NUM_BITS_INT (sizeof(int)*8) +int find(int); + +void main() +{ + int n, i, a, count = 0, flag = 1, m = 1, j, cmp; + printf("Enter the number + "); + scanf("%d", &n); + a = n >> 31 & 1; + if (a == 0) + { + for (i = (NUM_BITS_INT)-1; i >= 0; i--) + { + a = (n >> i)& 1; + if (a == 0) + { + count++; + } + else + { + for (j = n + 1;; j++) + { + cmp = find(j); + if (cmp == (((NUM_BITS_INT)-1) - count) + 1) + { + printf("next higher power -> %d + ", j); + break; + } + } + break; + } + } + } + else + { + for (i = (NUM_BITS_INT)-1; i >= 0; i--) + { + a = (n >> i)& 1; + if (a == 1) + { + count++; + } + else + { + for (j = n + 1;; j++) + { + cmp = find(j); + if (cmp == (((NUM_BITS_INT)- 1) - count)) + { + printf("next higher power -> %d + ", j); + break; + } + } + break; + } + } + } +} + +/* To find trailing zero's */ +int find(int n) +{ + int count = 0, a, flag = 1, i; + for (i = 0; i <= (NUM_BITS_INT) - 1; i++) + { + a = (n >> i) & 1; + if (a == 1 && flag == 1) + { + return count; + } + else + { + count++; + flag = 1; + } + } +} + + +Enter the number +9 +next higher power -> 16 + +Enter the number +-20 +next higher power -> -16 +Enter the number +44 +next higher power -> 64 + +Enter the number +-7 +next higher power -> -4 + +Enter the number +-31 +next higher power -> -16 + +Enter the number +-56 +next higher power -> -32 + +Enter the number +34 +next higher power -> 64 diff --git a/c/Basic/C Program to calculate the total execution time of a program.c b/c/Basic/C Program to calculate the total execution time of a program.c new file mode 100644 index 0000000..4f64895 --- /dev/null +++ b/c/Basic/C Program to calculate the total execution time of a program.c @@ -0,0 +1,19 @@ + #include + #include + int main() { + int i; + double total_time; + clock_t start, end; + start = clock(); + //time count starts + srand(time(NULL)); + for (i = 0; i < 25000; i++) { + printf("random_number[%d]= %d\n", i + 1, rand()); + } + end = clock(); + //time count stops + total_time = ((double) (end - start)) / CLK_TCK; + //calulate total time + printf("\nTime taken to print 25000 random number is: %f", total_time); + return 0; + } \ No newline at end of file diff --git a/c/Basic/C Program to find Product of 2 Numbers using Recursion.c b/c/Basic/C Program to find Product of 2 Numbers using Recursion.c new file mode 100644 index 0000000..f1b754a --- /dev/null +++ b/c/Basic/C Program to find Product of 2 Numbers using Recursion.c @@ -0,0 +1,32 @@ +/* + * C Program to find Product of 2 Numbers using Recursion + */ +#include + +int product(int, int); + +int main() +{ + int a, b, result; + printf("Enter two numbers to find their product: "); + scanf("%d%d", &a, &b); + result = product(a, b); + printf("Product of %d and %d is %d\n", a, b, result); + return 0; +} + +int product(int a, int b) +{ + if (a < b) + { + return product(b, a); + } + else if (b != 0) + { + return (a + product(a, b - 1)); + } + else + { + return 0; + } +} \ No newline at end of file diff --git a/c/Basic/C Program to find Reverse of a Number using Recursion.c b/c/Basic/C Program to find Reverse of a Number using Recursion.c new file mode 100644 index 0000000..303ad1f --- /dev/null +++ b/c/Basic/C Program to find Reverse of a Number using Recursion.c @@ -0,0 +1,36 @@ +/* + * C program to find the reverse of a number using recursion + */ +#include +#include + +int rev(int, int); + +int main() +{ + int num, result; + int length = 0, temp; + printf("Enter an integer number to reverse: "); + scanf("%d", &num); + temp = num; + while (temp != 0) + { + length++; + temp = temp / 10; + } + result = rev(num, length); + printf("The reverse of %d is %d.\n", num, result); + return 0; +} + +int rev(int num, int len) +{ + if (len == 1) + { + return num; + } + else + { + return (((num % 10) * pow(10, len - 1)) + rev(num / 10, --len)); + } +} \ No newline at end of file diff --git a/c/Basic/C Program to find Sum of N Numbers using Recursion.c b/c/Basic/C Program to find Sum of N Numbers using Recursion.c new file mode 100644 index 0000000..a610461 --- /dev/null +++ b/c/Basic/C Program to find Sum of N Numbers using Recursion.c @@ -0,0 +1,31 @@ +/* + * C Program to find Sum of N Numbers using Recursion + */ +#include + +void display(int); + +int main() +{ + int num, result; + printf("Enter the Nth number: "); + scanf("%d", &num); + display(num); + return 0; +} + +void display(int num) +{ + static int i = 1; + if (num == i) + { + printf("%d \n", num); + return; + } + else + { + printf("%d ", i); + i++; + display(num); + } +} \ No newline at end of file diff --git a/c/Basic/C Program to next higher value of n with same 1's.c b/c/Basic/C Program to next higher value of n with same 1's.c new file mode 100644 index 0000000..dc956db --- /dev/null +++ b/c/Basic/C Program to next higher value of n with same 1's.c @@ -0,0 +1,63 @@ +/* + +* C Program to next higher value of n with same 1's +*/ +#define NUM_BITS_INT 32 +#include +int newcount(int); + +void main() +{ + int count1 = 0, k = 0, j, t, n, bit, i = 1, count = 0; + printf("Enter a number : "); + scanf("%d", &n); + t = n; + while(t != 0) + { + bit = t & 0x80000000; + if (bit == -0x80000000) + { + bit = 1; + } + if (bit == 1) + count++; + t = t << 1; + } + for (k = n + 1;; k++) + { + count1 = newcount(k); + if (count1 == count) + { + printf("The next highest number is : %d ", k); + break; + } + } +} + +/* To count the no. of 1's in the no. */ +int newcount(int k) +{ + int bit, count = 0; + while (k != 0) + { + bit = k & 0x80000000; + if (bit == -0x80000000) + { + bit = 1; + } + if (bit == 1) + count++; + k = k << 1; + } + return(count); +} + + +Enter a number : 128 +The next highest number is : 256 +Enter a number : 127 +The next highest number is : 191 +Enter a number : 6 +The next highest number is : 9 +Enter a number : 12 +The next highest number is : 17 \ No newline at end of file diff --git a/c/Basic/C Program to replace first letter of every word with caps.c b/c/Basic/C Program to replace first letter of every word with caps.c new file mode 100644 index 0000000..77abf20 --- /dev/null +++ b/c/Basic/C Program to replace first letter of every word with caps.c @@ -0,0 +1,61 @@ +/* +* C Program to replace first letter of every word with caps +*/ +#include +#include +void main(int argc, char *argv[]) +{ + FILE *fp1; + int return_val; + if ((fp1 = fopen(argv[1],"r+")) = = NULL) + { + printf("file cant be opened"); + exit(0); + } + return_val = init_cap_file(fp1); + if (return_val == 1) + { + printf(" + success"); + } + else + { + printf(" + failure"); + } +} +int init_cap_file(FILE *fp1) +{ + char ch; + ch = fgetc(fp1); + if (ch >= 97 && ch <= 122) + { + fseek(fp1, -1L, 1); + fputc(ch - 32, fp1); + } + while (ch != EOF) + { + if (ch = = ' '|| ch == ' + ') + { + ch = fgetc(fp1); + if (ch >= 97 && ch <= 122) + { + fseek(fp1, -1L, 1); + fputc(ch - 32, fp1); + } + } + else + ch = fgetc(fp1); + } + return 1; +} +chandana ravella +chanikya ravella +sree lakshmi ravella +sree ramulu ravella +cat file5test +Chandana Ravella +Chanikya Ravella +Sree Lakshmi Ravella +Sree Ramulu Ravella \ No newline at end of file diff --git a/c/Basic/C Program to sort string ignoring whitespaces and repeating characters only once.c b/c/Basic/C Program to sort string ignoring whitespaces and repeating characters only once.c new file mode 100644 index 0000000..c609be5 --- /dev/null +++ b/c/Basic/C Program to sort string ignoring whitespaces and repeating characters only once.c @@ -0,0 +1,64 @@ + +/* +* C Program to sort string ignoring whitespaces and repeating characters only once +*/ +#include +#include + +#define SIZE 50 + +void main() +{ + char string[SIZE], string1[SIZE], string2[SIZE]; + int i, j = 0, a = 0, temp, len = 0, len1 = 0, k = 0; + printf(" + Enter a string:"); + scanf("%[^ + ]s", string1); + /* Code to remove whitespaces */ + for (i = 0; string1[i] != ''; i++) + { + if (string1[i] == ' ') + { + continue; + } + string[j++] = string1[i]; + } + /* Code to sort the string */ for (i = 0; string[i] != ''; i++) + { + for (j = i + 1; string[j] != ''; j++) + { + if (string[i] > string[j]) + { + temp = string[i]; + string[i] = string[j]; + string[j] = temp; + } + } + } + string[i] = ''; + len = strlen(string); + /* Code to remove redundant characters */ + for (i = 0; string[i] != ''; i++) + { + if (string[i] == string[i + 1] && string[i + 1] != '') + { + k++; + continue; + } + string2[a++] = string[i]; + string[a] = ''; + } + len1 = len - k; + printf("The sorted string is:"); + for (temp = 0; temp < len1; temp++) + { + printf("%c", string2[temp]); + } +} + + +Enter a string: +abcdel bcdl abcdefg +The sorted string is: +abcdefgl diff --git a/c/Basic/C program for Binary to decimal conversion.c b/c/Basic/C program for Binary to decimal conversion.c new file mode 100644 index 0000000..19ab181 --- /dev/null +++ b/c/Basic/C program for Binary to decimal conversion.c @@ -0,0 +1,16 @@ +/*binary to decimal conversion:*/ +#include +void main() +{ + long int bn,dn=0,j=1,remainder; + printf("Enter any number any binary number: "); + scanf("%ld",&bn); + while(bn!=0) + { + remainder=bn%10; + dn=dn+remainder*j; + j=j*2; + bn=bn/10; + } + printf("Equivalent decimal value: %ld",dn); +} \ No newline at end of file diff --git a/c/Basic/C program for decimal to octal converter.c b/c/Basic/C program for decimal to octal converter.c new file mode 100644 index 0000000..e0a294b --- /dev/null +++ b/c/Basic/C program for decimal to octal converter.c @@ -0,0 +1,17 @@ +#include +void main() +{ + long int dn,remainder,q; + int on[100],i=1,j; + printf("Enter any decimal number"); + scanf("%ld",&dn); + q = dn; + while(q!=0) + { + on[i++]= q % 8; + q = q/ 8; + } + printf("Equivalent octal value %d: ",dn); + for(j = i -1 ; j> 0; j--) + printf("%d",on[j]); +} \ No newline at end of file diff --git a/c/Basic/C program for hexadecimal to binary conversion.c b/c/Basic/C program for hexadecimal to binary conversion.c new file mode 100644 index 0000000..91b1d80 --- /dev/null +++ b/c/Basic/C program for hexadecimal to binary conversion.c @@ -0,0 +1,85 @@ +#include +#define MAX 1000 +void main() +{ + char hd[MAX]; + long int i=0; + printf("Enter any hexadecimal number: "); + scanf("%s",hd); + printf("\nEquivalent binary value: "); + while(hd[i]) + { + switch(hd[i]) + { + case '0': + printf("0000"); + break; + case '1': + printf("0001"); + break; + case '2': + printf("0010"); + break; + case '3': + printf("0011"); + break; + case '4': + printf("0100"); + break; + case '5': + printf("0101"); + break; + case '6': + printf("0110"); + break; + case '7': + printf("0111"); + break; + case '8': + printf("1000"); + break; + case '9': + printf("1001"); + break; + case 'A': + printf("1010"); + break; + case 'B': + printf("1011"); + break; + case 'C': + printf("1100"); + break; + case 'D': + printf("1101"); + break; + case 'E': + printf("1110"); + break; + case 'F': + printf("1111"); + break; + case 'a': + printf("1010"); + break; + case 'b': + printf("1011"); + break; + case 'c': + printf("1100"); + break; + case 'd': + printf("1101"); + break; + case 'e': + printf("1110"); + break; + case 'f': + printf("1111"); + break; + default: + printf("\nInvalid hexadecimal digit %c ",hd[i]); + } + i++; + } +} \ No newline at end of file diff --git a/c/Basic/C program to Convert Decimal to Hexadecimal.c b/c/Basic/C program to Convert Decimal to Hexadecimal.c new file mode 100644 index 0000000..f75b9e5 --- /dev/null +++ b/c/Basic/C program to Convert Decimal to Hexadecimal.c @@ -0,0 +1,27 @@ +/* + * C program to Convert Decimal to Hexadecimal + */ +#include + +int main() +{ + long decimalnum, quotient, remainder; + int i, j = 0; + char hexadecimalnum[100]; + printf("Enter decimal number: "); + scanf("%ld", &decimalnum); + quotient = decimalnum; + while (quotient != 0) + { + remainder = quotient % 16; + if (remainder < 10) + hexadecimalnum[j++] = 48 + remainder; + else + hexadecimalnum[j++] = 55 + remainder; + quotient = quotient / 16; + } + // display integer into character + for (i = j; i >= 0; i--) + printf("%c", hexadecimalnum[i]); + return 0; +} \ No newline at end of file diff --git a/c/Basic/C program to Convert Decimal to Octal.c b/c/Basic/C program to Convert Decimal to Octal.c new file mode 100644 index 0000000..0fe7667 --- /dev/null +++ b/c/Basic/C program to Convert Decimal to Octal.c @@ -0,0 +1,22 @@ +/* + * C program to Convert Decimal to Octal + */ +#include + +int main() +{ + long decimalnum, remainder, quotient; + int octalNumber[100], i = 1, j; + printf("Enter the decimal number: "); + scanf("%ld", &decimalnum); + quotient = decimalnum; + while (quotient != 0) + { + octalNumber[i++] = quotient % 8; + quotient = quotient / 8; + } + printf("Equivalent octal value of decimal no %d: ", decimalnum); + for (j = i - 1; j > 0; j--) + printf("%d", octalNumber[j]); + return 0; +} \ No newline at end of file diff --git a/c/Basic/C program to Increase 1 to all of the given Integer Digit.c b/c/Basic/C program to Increase 1 to all of the given Integer Digit.c new file mode 100644 index 0000000..25055d3 --- /dev/null +++ b/c/Basic/C program to Increase 1 to all of the given Integer Digit.c @@ -0,0 +1,19 @@ +/* + * C program to Increase 1 to all of the given Integer Digit + */ +#include + +int main() +{ + int number, sum = 0, remainder, count; + printf("Enter a number: "); + scanf("%d", &number); + while (number) + { + remainder = number % 10; + sum = sum + (remainder + 1); + number /= 10; + } + printf("increasing 1 to all digits: %d", sum); + return 0; +} \ No newline at end of file diff --git a/c/Basic/C program to accept N numbers sorted in ascending order and to search for a given number using binary search..c b/c/Basic/C program to accept N numbers sorted in ascending order and to search for a given number using binary search..c new file mode 100644 index 0000000..193d94c --- /dev/null +++ b/c/Basic/C program to accept N numbers sorted in ascending order and to search for a given number using binary search..c @@ -0,0 +1,121 @@ +/* +* C program to accept N numbers sorted in ascending order +* and to search for a given number using binary search. +* Report success or failure. +*/ +#include + +void main() +{ + int array[10]; + int i, j, num, temp, keynum; + int low, mid, high; + printf("Enter the value of num + "); + scanf("%d", &num); + printf("Enter the elements one by one + "); + for (i = 0; i < num; i++) + { + scanf("%d", &array[i]); + } + printf("Input array elements + "); + for (i = 0; i < num; i++) + { + printf("%d + ", array[i]); + } +/* Bubble sorting begins */ +for (i = 0; i < num; i++) + { + for (j = 0; j < (num - i - 1); j++) + { + if (array[j] > array[j + 1]) + { + temp = array[j]; + array[j] = array[j + 1]; + array[j + 1] = temp; + } + } + } + printf("Sorted array is... + "); + for (i = 0; i < num; i++) + { + printf("%d + ", array[i]); + } +printf("Enter the element to be searched + "); + scanf("%d", &keynum); + /* Binary searching begins */ + low = 1; + high = num; + do + { + mid = (low + high) / 2; + if (keynum < array[mid]) + high = mid - 1; + else if (keynum > array[mid]) + low = mid + 1; + } + while (keynum != array[mid] && low <= high); + if (keynum == array[mid]) + { + printf("SEARCH SUCCESSFUL + "); + } + else + { + printf("SEARCH FAILED + "); + } +} + + +Enter the value of num +5 +Enter the elements one by one +23 +90 +56 +15 +58 +Input array elements +23 + +90 +56 +15 +58 +Sorted array is... +15 +23 +56 +58 +90 +Enter the element to be searched +58 +SEARCH SUCCESSFUL + +Enter the value of num +4 +Enter the elements one by one +1 +98 +65 +45 +Input array elements +1 +98 +65 +45 +Sorted array is... +1 +45 +65 +98 +Enter the element to be searched +6 +SEARCH FAILED \ No newline at end of file diff --git a/c/Basic/C program to accept an array of 10 elements and swap 3rd element with 4th element using pointers and display the results..c b/c/Basic/C program to accept an array of 10 elements and swap 3rd element with 4th element using pointers and display the results..c new file mode 100644 index 0000000..71692c5 --- /dev/null +++ b/c/Basic/C program to accept an array of 10 elements and swap 3rd element with 4th element using pointers and display the results..c @@ -0,0 +1,47 @@ +/* * C program to accept an array of 10 elements and swap 3rd element * with 4th element using pointers and display the results. */ +#include +void swap34(float *ptr1, float *ptr2); +void main() +{ + float x[10]; + int i, n; + printf("How many Elements... + "); + scanf("%d", &n); + printf("Enter Elements one by one + "); + for (i = 0; i < n; i++) + { + scanf("%f", x + i); + } + /* Function call:Interchanging 3rd element by 4th */ + swap34(x + 2, x + 3); + printf(" + Resultant Array... + "); + for (i = 0; i < n; i++) + { + printf("X[%d] = %f + ", i, x[i]); + } +} +/* Function to swap the 3rd element with the 4th element in the array */ +void swap34(float *ptr1, float *ptr2 ) +{ + float temp; + temp = *ptr1; + *ptr1 = *ptr2; + *ptr2 = temp; +} +How many Elements... +4 +Enter Elements one by one +23 +67 +45 +15 +Resultant Array... +X[0] = 23.000000 + X[1] = 67.000000 + X[2] = 15.000000 + X[3] = 45.000000 \ No newline at end of file diff --git a/c/Basic/C program to find the length of a string without using the built-in function also check whether it is a palindrome.c b/c/Basic/C program to find the length of a string without using the built-in function also check whether it is a palindrome.c new file mode 100644 index 0000000..0333342 --- /dev/null +++ b/c/Basic/C program to find the length of a string without using the built-in function also check whether it is a palindrome.c @@ -0,0 +1,47 @@ +/* + * C program to find the length of a string without using the + * built-in function also check whether it is a palindrome + */ +#include +#include + +void main() +{ + char string[25], reverse_string[25] = {''}; + int i, length = 0, flag = 0; + printf("Enter a string + "); + gets(string); + /* keep going through each character of the string till its end */ + for (i = 0; string[i] != ''; i++) + { + length++; + } +printf("The length of the string '%s' = %d + ", string, length); + for (i = length - 1; i >= 0 ; i--) + { + reverse_string[length - i - 1] = string[i]; + } + /* Check if the string is a Palindrome */ + for (flag = 1, i = 0; i < length ; i++) + { + if (reverse_string[i] != string[i]) + flag = 0; + } + if (flag == 1) + printf ("%s is a palindrome ", string); + else + printf("%s is not a palindrome ", string); + } + + +Enter a string +how are you +The length of the string 'how are you' = 12 + how are you is not a palindrome + + Enter a string + madam + The length of the string 'madam' = 5 + madam is a palindrome \ No newline at end of file diff --git a/c/Basic/C program to find the number of occurences of a given number in a list.c b/c/Basic/C program to find the number of occurences of a given number in a list.c new file mode 100644 index 0000000..9610b47 --- /dev/null +++ b/c/Basic/C program to find the number of occurences of a given number in a list.c @@ -0,0 +1,50 @@ +/* +* C program to find the number of occurences of a given number in a +* list +*/ +#include + +void occur(int [], int, int, int, int *); + +int main() +{ + int size, key, count = 0; + int list[20]; + int i; + printf("Enter the size of the list: "); + scanf("%d", &size); + printf("Printing the list: + "); + for (i = 0; i < size; i++) + { + list[i] = rand() % size; + printf("%d ", list[i]); + } + printf(" + Enter the key to find it's occurence: "); + scanf("%d", &key); + occur(list, size, 0, key, &count); + printf("%d occurs for %d times. + ", key, count); + return 0; +} + + void occur(int list[], int size, int index, int key, int *count) +{ + if (size == index) + { + return; + } + if (list[index] == key) + { + *count += 1; + } + occur(list, size, index + 1, key, count); +} + + +Enter the size of the list: 7 +Printing the list: +1 4 2 5 1 3 3 +Enter the key to find it's occurence: 3 +3 occurs for 2 times. diff --git a/c/Basic/C program to print hello world without using semicolon.c b/c/Basic/C program to print hello world without using semicolon.c new file mode 100644 index 0000000..3f92150 --- /dev/null +++ b/c/Basic/C program to print hello world without using semicolon.c @@ -0,0 +1,5 @@ + #include + void main(){ + if(printf("Hello world")){ + } + } \ No newline at end of file diff --git a/c/Basic/C program to read an English sentence and replace lowercase characters by uppercase and vice-versa..c b/c/Basic/C program to read an English sentence and replace lowercase characters by uppercase and vice-versa..c new file mode 100644 index 0000000..93d82ae --- /dev/null +++ b/c/Basic/C program to read an English sentence and replace lowercase characters by uppercase and vice-versa..c @@ -0,0 +1,41 @@ +/* + * C program to read an English sentence and replace + * lowercase characters by uppercase and vice-versa. + * Output the given sentence as well as the converted + * sentence on two different lines. + */ +#include +#include + +void main() +{ + char sentence[100]; + int count, ch, i; + printf("Enter a sentence + "); + for (i = 0; (sentence[i] = getchar()) != ' + '; i++) + { + ; + } + sentence[i] = ''; + /* shows the number of chars accepted in a sentence */ + count = i; + printf("The given sentence is : %s", sentence); + printf(" + Case changed sentence is: "); + for (i = 0; i < count; i++) + { + ch = islower(sentence[i])? toupper(sentence[i]) : + tolower(sentence[i]); + putchar(ch); + } +} + + +Enter a sentence +gETTING iLLUMIN8ED +The given sentence is : +gETTING iLLUMIN8ED +Case changed sentence is: +GETTING ILLUMIN8ED \ No newline at end of file diff --git a/c/Basic/C program to sort n given numbers using pointers.c b/c/Basic/C program to sort n given numbers using pointers.c new file mode 100644 index 0000000..3f70e14 --- /dev/null +++ b/c/Basic/C program to sort n given numbers using pointers.c @@ -0,0 +1,37 @@ +#include +#include +#include +void main() +{ + int n,*p,i,j,temp; + clrscr(); + printf("\nHOW MANY NUMBER: "); + scanf("%d",&n); + p=(int *) malloc(n*2); + if(p==NULL) + { + printf("\nMEMORY ALLOCATION UNSUCCESSFUL"); + exit(); + } + for(i=0;i + #include + #include + int main(int argc, char** argv) { + char** new_argv; + int i; + /* Since argv[0] through argv[argc] are all valid, the + program needs to allocate room for argc+1 pointers. */ + new_argv = (char**) calloc(argc+1, sizeof (char*)); + /* or malloc((argc+1) * sizeof (char*)) */ + printf("allocated room for %d pointers starting at %P\n", argc+1, new_argv); + /* now copy all the strings themselves + (argv[0] through argv[argc-1]) */ + for (i = 0; i < argc; ++i) { + /* make room for '' at end, too */ + new_argv[i] = (char*) malloc(strlen(argv[i]) + 1); + strcpy(new_argv[i], argv[i]); + printf(" + allocated %d bytes for new_argv[%d] at %P, " + " + copied \" + %s\" + \n" + , + strlen(argv[i]) + 1, i, new_argv[i], new_argv[i]); + } + new_argv[argc] = NULL; + /* To deallocate everything, get rid of the strings (in any + order), then the array of pointers. If you free the array + of pointers first, you lose all reference to the copied + strings. */ + for (i = 0; i < argc; ++i) { + free(new_argv[i]); + printf(" + freed new_argv[%d] at %P\n" + , i, new_argv[i]); + argv[i] = NULL; + } + free(new_argv); + printf(" + freed new_argv itself at %P\n" + , new_argv); + return 0; + } \ No newline at end of file diff --git a/c/Basic/Create and Use Your Own Header File in C Programming.c b/c/Basic/Create and Use Your Own Header File in C Programming.c new file mode 100644 index 0000000..0584bd9 --- /dev/null +++ b/c/Basic/Create and Use Your Own Header File in C Programming.c @@ -0,0 +1,8 @@ + #include + #include "myfirstheader.h" + + void main() { + int num1 = 10, num2 = 10, num3; + num3 = add(num1, num2); + printf("Addition of Two numbers : %d", num3); + } \ No newline at end of file diff --git a/c/Basic/Get Address of an array using Arrays and Pointers.c b/c/Basic/Get Address of an array using Arrays and Pointers.c new file mode 100644 index 0000000..d7ad924 --- /dev/null +++ b/c/Basic/Get Address of an array using Arrays and Pointers.c @@ -0,0 +1,14 @@ + #include + + int main(void) + { + char multiple[] = "My string"; + + char *p = &multiple[0]; + printf("\nThe address of the first array element : %p", p); + + p = multiple; + printf("\nThe address obtained from the array name: %p\n", p); + + return 0; + } \ No newline at end of file diff --git a/c/Basic/Print mark-sheet of students.c b/c/Basic/Print mark-sheet of students.c new file mode 100644 index 0000000..920ab9b --- /dev/null +++ b/c/Basic/Print mark-sheet of students.c @@ -0,0 +1,43 @@ + #include + #include + #include + #include + void main() { + /*variable declaration part */ + int rl,s1,s2,s3,t; + float per; + char nm[25],div[10]; + clrscr(); + /*reading part */ + printf("Enter the Roll No : "); + scanf("%d",&rl); + printf("Enter Name : "); + fflush(stdin); + gets(nm); + printf("Enter Three Subject Marks :\n"); + scanf("%d%d%d",&s1,&s2,&s3); + /* processing part */ + t=s1+s2+s3; + per=t/3.0; + if(per>=75) + strcpy(div,"Honour"); else if( per>=60) + strcpy(div,"First"); else if( per>=48) + strcpy(div,"Second"); else if (per>=36) + strcpy(div,"Pass"); else + strcpy(div,"Fail"); + /* display part */ + printf("\t\tUniversity of Rajasthan\n"); + printf("\n\n"); + printf("Roll No: %d \t Name : %s\n",rl,nm); + printf("---------------------------------------------------\n"); + printf("Subject Max Min Obt.Marks\n"); + printf("---------------------------------------------------\n"); + printf("Hist 100 36 %d\n",s1); + printf("socio. 100 36 %d\n",s2); + printf("Hindi 100 36 %d\n",s3); + printf("---------------------------------------------------\n"); + printf(" Total %d\n",t); + printf("per %f\t\t\t div: %s \n",per,div); + printf("---------------------------------------------------\n"); + getch(); + } \ No newline at end of file diff --git a/c/Basic/Reverse a string using pointers.c b/c/Basic/Reverse a string using pointers.c new file mode 100644 index 0000000..993008d --- /dev/null +++ b/c/Basic/Reverse a string using pointers.c @@ -0,0 +1,15 @@ + #include + #include + void main() + { + char *s; + int len,i; + clrscr(); + printf("\nENTER A STRING: "); + gets(s); + len=strlen(s); + printf("\nTHE REVERSE OF THE STRING IS:"); + for(i=len;i>=0;i--) + printf("%c",*(s+i)); + getch(); + } \ No newline at end of file diff --git a/c/Basic/Reverse the order of each word of the string using pointers.c b/c/Basic/Reverse the order of each word of the string using pointers.c new file mode 100644 index 0000000..3d59fc9 --- /dev/null +++ b/c/Basic/Reverse the order of each word of the string using pointers.c @@ -0,0 +1,28 @@ + #include + #include + void main() + { + char *s; + int len,i,j,sp=0,start,end; + clrscr(); + printf("\nENTER A STRING: "); + gets(s); + printf("\nTHE STRING AFTER CHANGING THE ORDER OF EACH WORD:\n"); + len=strlen(s); + end=len-1; + for(i=len-1;i>=0;i--) + { + if(s[i]==32 || i==0) + { + if(i==0) + start=0; + else + start=i+1; + for(j=start;j<=end;j++) + printf("%c",s[j]); + end=i-1; + printf(" "); + } + } + getch(); + } \ No newline at end of file diff --git a/c/Basic/Show the ticking of Clock.c b/c/Basic/Show the ticking of Clock.c new file mode 100644 index 0000000..41ed0ae --- /dev/null +++ b/c/Basic/Show the ticking of Clock.c @@ -0,0 +1,104 @@ + #include + #include + #include + #include + #include + // Calculates new co-ordinates of a figure after + // rotating it at an angle about a point (cx,cy) + void rotate( int figure[], int edges, double angle, int cx, int cy ) { + double x, y; + angle = -1 * (angle*3.14/180); + double cos_a = cos(angle); + double sin_a = sin(angle); + for (int i=0; i < edges; i++) { + x = figure[2*i] - cx; + y = figure[2*i+1] - cy; + figure[2*i] = floor( (x * cos_a) - (y * sin_a) + cx + 0.5 ); + figure[2*i+1] = floor( (x * sin_a)+(y * cos_a) + cy + 0.5 ); + } + } + void drawClock(int,int,int); + void main() { + int second_hand[4],minute_hand[4], hour_hand[4], edges = 2 ; + double angle; + int cx=300, cy=200; + int gd = DETECT, gm; + initgraph( &gd, &gm, "" ); + int max_y = getmaxy(); + clrscr(); + cleardevice(); + angle = -6; + // Set the initial position of the second, minute and the hour hands. + second_hand[0] = cx ; + second_hand[1] = max_y - cy; + second_hand[2] = cx; + second_hand[3] = max_y - 320; + hour_hand[0] = cx; + hour_hand[1] = max_y - cy; + hour_hand[2] = cx + 90; + hour_hand[3] = max_y - 200; + minute_hand[0] = cx; + minute_hand[1] = max_y - cy; + minute_hand[2] = cx; + minute_hand[3] = max_y - 310; + cleardevice(); + setbkcolor(WHITE); + // Draw the clock + drawClock(cx,max_y - cy,150); + setlinestyle(SOLID_FILL,0,1); + // Draw the minute and the hour hand + drawpoly(2,minute_hand); + drawpoly(2,hour_hand); + int i=0; + while(!kbhit()) { + setcolor(RED); + drawpoly(2,second_hand); + setcolor(GREEN); + drawpoly(2,minute_hand); + setcolor(BLUE); + drawpoly(2,hour_hand); + delay(1000); + // set delay(10) to tick the clock fast + setcolor(15); + drawpoly(2,second_hand); + rotate(second_hand,edges,angle,cx,max_y - cy); + i++; + // Reset the second hand and move the minute hand + // when the second hand has moved 60 times. + if(i%60 == 0) { + second_hand[0] = cx ; + second_hand[1] = max_y - cy; + second_hand[2] = cx; + second_hand[3] = max_y - 320; + drawpoly(2,minute_hand); + rotate(minute_hand,edges,angle,cx,max_y - cy); + } + // Move the minute hand + // when the second hand has moved 720 (60*12) times. + if(i%720 == 0) { + i = 0; + drawpoly(2,hour_hand); + rotate(hour_hand,edges,angle,cx,max_y - cy); + } + } + getch(); + } + // Function to draw the clock + void drawClock(int cx, int cy, int r) { + setcolor(GREEN); + setlinestyle(SOLID_FILL,0,3); + circle(cx,cy,r); + int max_y = getmaxy(); + int center[2] = { + cx, max_y - 340 + } + ; + for (int i=0; i<60; i++) { + if(i%5 == 0) { + circle(center[0],center[1],2); + } else { + circle(center[0],center[1],1); + } + rotate(center,1,-6,cx,cy); + } + } \ No newline at end of file diff --git a/c/Basic/Time functions in c.c b/c/Basic/Time functions in c.c new file mode 100644 index 0000000..1e22ad8 --- /dev/null +++ b/c/Basic/Time functions in c.c @@ -0,0 +1,36 @@ + #include + #include + #include + void main() + { + time_t now; + clrscr(); + now = time((time_t *)NULL); + + printf("%s", ctime(&now)); + + time(&now); + + printf("%s", ctime(&now)); + { + struct tm *l_time; + + l_time = localtime(&now); + printf("%s", asctime(l_time)); + } + + time(&now); + printf("%s", asctime(localtime( &now ))); + { + + struct tm *l_time; + char string[20]; + + time(&now); + l_time = localtime(&now); + strftime(string, sizeof string, "%d-%b-%y\n", l_time); + printf("%s", string); + } + + getch(); + } \ No newline at end of file diff --git a/c/Basic/To compute the average of n given numbers using pointers.c b/c/Basic/To compute the average of n given numbers using pointers.c new file mode 100644 index 0000000..d277e16 --- /dev/null +++ b/c/Basic/To compute the average of n given numbers using pointers.c @@ -0,0 +1,26 @@ + #include + #include + void main() + { + int n,*p,sum=0,i; + float avg; + clrscr(); + printf("\nHOW MANY NUMBERS: "); + scanf("%d",&n); + p=(int *) malloc(n*2); + if(p==NULL) + { + printf("\nMEMORY ALLOCATION UNSUCCCESSFUL"); + exit(); + } + for(i=0;i + #include + void main() + { + long unsigned age,sec; + clrscr(); + printf("\nENTER YOUR AGE: "); + scanf("%lu",&age); + sec=age*365*24*60*60; + printf("\nAGE IN SECONDS: %lu",sec); + getch(); + } \ No newline at end of file diff --git a/c/Basic/To find the maximum number within n given numbers using pointers.c b/c/Basic/To find the maximum number within n given numbers using pointers.c new file mode 100644 index 0000000..821f02f --- /dev/null +++ b/c/Basic/To find the maximum number within n given numbers using pointers.c @@ -0,0 +1,28 @@ + #include + #include + void main() + { + int n,*p,i,h=0; + clrscr(); + printf("\nHOW MANY NUMBERS: "); + scanf("%d",&n); + p=(int *) malloc(n*2); + if(p==NULL) + { + printf("\nMEMORY ALLOCATION UNSUCCCESSFUL"); + exit(); + } + for(i=0;ih) + h=*(p+i); + } + printf("\nTHE HIGHEST NUMBER IS %d",h); + getch(); + } \ No newline at end of file diff --git a/c/Basic/To swap the address of two variables using pointer.c b/c/Basic/To swap the address of two variables using pointer.c new file mode 100644 index 0000000..4c99b7b --- /dev/null +++ b/c/Basic/To swap the address of two variables using pointer.c @@ -0,0 +1,20 @@ + #include + #include + void swap(int *,int *); + void main() + { + int a=10,b=20; + clrscr(); + printf("\nVALUES OF a AND b BEFORE SWAPING ARE %d %d",a,b); + swap(&a,&b); + printf("\nVALUES OF a AND b AFTER SWAPING ARE %d %d",a,b); + getch(); + } + void swap(x,y) + int *x,*y; + { + int t; + t=*x; + *x=*y; + *y=t; + } \ No newline at end of file diff --git a/c/Basic/What happens if you free a pointer twice.c b/c/Basic/What happens if you free a pointer twice.c new file mode 100644 index 0000000..0e28b67 --- /dev/null +++ b/c/Basic/What happens if you free a pointer twice.c @@ -0,0 +1,21 @@ + #include + #include + int main(int argc, char** argv) { + char** new_argv1; + char** new_argv2; + new_argv1 = calloc(argc+1, sizeof(char*)); + free(new_argv1); + /* freed once */ + new_argv2 = (char**) calloc(argc+1, sizeof(char*)); + if (new_argv1 == new_argv2) { + /* new_argv1 accidentally points to freeable memory */ + free(new_argv1); + /* freed twice */ + } else { + free(new_argv2); + } + new_argv1 = calloc(argc+1, sizeof(char*)); + free(new_argv1); + /* freed once again */ + return 0; + } \ No newline at end of file diff --git a/c/Basic/Write a c program to check given string is palindrome number or not.c b/c/Basic/Write a c program to check given string is palindrome number or not.c new file mode 100644 index 0000000..2fdf3ef --- /dev/null +++ b/c/Basic/Write a c program to check given string is palindrome number or not.c @@ -0,0 +1,18 @@ + #include + #include + void main() { + char *a; + int i,len,flag=0; + clrscr(); + printf("\nENTER A STRING: "); + gets(a); + len=strlen(a); + for (i=0;i + struct circ_list { + char value[ 3 ]; + /* e.g., "st" (incl '') */ + struct circ_list *next; + } + ; + struct circ_list suffixes[] = { + "th", & suffixes[ 1 ], + /* 0th */ + "st", & suffixes[ 2 ], + /* 1st */ + "nd", & suffixes[ 3 ], + /* 2nd */ + "rd", & suffixes[ 4 ], + /* 3rd */ + "th", & suffixes[ 5 ], + /* 4th */ + "th", & suffixes[ 6 ], + /* 5th */ + "th", & suffixes[ 7 ], + /* 6th */ + "th", & suffixes[ 8 ], + /* 7th */ + "th", & suffixes[ 9 ], + /* 8th */ + "th", & suffixes[ 0 ], + /* 9th */ + } + ; + #define MAX 20 + int main() { + int i = 0; + struct circ_list *p = suffixes; + while (i value ); + ++i; + p = p->next; + } + return 0; + } \ No newline at end of file diff --git a/c/Basic/null pointer in c.c b/c/Basic/null pointer in c.c new file mode 100644 index 0000000..fee473f --- /dev/null +++ b/c/Basic/null pointer in c.c @@ -0,0 +1,15 @@ + /* A simple program that prints all its arguments. + It doesn't use argc ("argument count"); instead, + it takes advantage of the fact that the last value + in argv ("argument vector") is a null pointer. */ + #include + #include + int + main( int argc, char **argv) { + int i; + printf("program name = \"%s\"\n", argv[0]); + for (i=1; argv[i] != NULL; ++i) + printf("argv[%d] = \"%s\"\n", i, argv[i]); + assert(i == argc); + return 0; + } \ No newline at end of file diff --git a/c/README.md b/c/README.md new file mode 100644 index 0000000..f7c3d8b --- /dev/null +++ b/c/README.md @@ -0,0 +1,3 @@ +# C programming language + +C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations. \ No newline at end of file diff --git a/css/README.md b/css/README.md new file mode 100644 index 0000000..0fad647 --- /dev/null +++ b/css/README.md @@ -0,0 +1,3 @@ +# Cascading Style Sheets (CSS) + +CSS is a style sheet language used for describing the presentation of a document written in a markup language like HTML. CSS is a cornerstone technology of the World Wide Web, alongside HTML and JavaScript. \ No newline at end of file diff --git a/html/Basics/01-skeleton (Basic Javascript Animation).html b/html/Basics/01-skeleton (Basic Javascript Animation).html new file mode 100644 index 0000000..ecfce13 --- /dev/null +++ b/html/Basics/01-skeleton (Basic Javascript Animation).html @@ -0,0 +1,16 @@ + + + + + + + + + + + + diff --git a/html/Basics/02-event-demo (Basic Javascript Animation).html b/html/Basics/02-event-demo (Basic Javascript Animation).html new file mode 100644 index 0000000..e8aa6cf --- /dev/null +++ b/html/Basics/02-event-demo (Basic Javascript Animation).html @@ -0,0 +1,29 @@ + + + + + Event Demo + + + +
+ Example from Foundation HTML5 Animation with JavaScript +
+ + + + + + diff --git a/html/Basics/03-mouse-events (Basic Javascript Animation).html b/html/Basics/03-mouse-events (Basic Javascript Animation).html new file mode 100644 index 0000000..0121302 --- /dev/null +++ b/html/Basics/03-mouse-events (Basic Javascript Animation).html @@ -0,0 +1,34 @@ + + + + + Mouse Events + + + +
+ Example from Foundation HTML5 Animation with JavaScript +
+ + + + + + diff --git a/html/Basics/04-mouse-position (Basic Javascript Animation).html b/html/Basics/04-mouse-position (Basic Javascript Animation).html new file mode 100644 index 0000000..0b2dadc --- /dev/null +++ b/html/Basics/04-mouse-position (Basic Javascript Animation).html @@ -0,0 +1,27 @@ + + + + + Mouse Position + + + +
+ Example from Foundation HTML5 Animation with JavaScript +
+ + + + + + + diff --git a/html/Basics/05-touch-events (Basic Javascript Animation).html b/html/Basics/05-touch-events (Basic Javascript Animation).html new file mode 100644 index 0000000..8eed4c6 --- /dev/null +++ b/html/Basics/05-touch-events (Basic Javascript Animation).html @@ -0,0 +1,30 @@ + + + + + Touch Events + + + + +
+ Example from Foundation HTML5 Animation with JavaScript +
+ + + + + + diff --git a/html/Basics/06-keyboard-events (Basic Javascript Animation).html b/html/Basics/06-keyboard-events (Basic Javascript Animation).html new file mode 100644 index 0000000..d519ca8 --- /dev/null +++ b/html/Basics/06-keyboard-events (Basic Javascript Animation).html @@ -0,0 +1,26 @@ + + + + + Keyboard Events + + + +
+ Example from Foundation HTML5 Animation with JavaScript +
+ + + + + diff --git a/html/Basics/07-key-codes (Basic Javascript Animation).html b/html/Basics/07-key-codes (Basic Javascript Animation).html new file mode 100644 index 0000000..e094d5b --- /dev/null +++ b/html/Basics/07-key-codes (Basic Javascript Animation).html @@ -0,0 +1,40 @@ + + + + + Key Codes + + + +
+ Example from Foundation HTML5 Animation with JavaScript +
+ + + + + diff --git a/html/Basics/08-key-names (Basic Javascript Animation).html b/html/Basics/08-key-names (Basic Javascript Animation).html new file mode 100644 index 0000000..d41236b --- /dev/null +++ b/html/Basics/08-key-names (Basic Javascript Animation).html @@ -0,0 +1,41 @@ + + + + + Key Names + + + +
+ Example from Foundation HTML5 Animation with JavaScript +
+ + + + + + diff --git a/html/Basics/A simple HTML document.html b/html/Basics/A simple HTML document.html new file mode 100644 index 0000000..3508585 --- /dev/null +++ b/html/Basics/A simple HTML document.html @@ -0,0 +1,9 @@ + + + + Simple HTML document + + +

Hello World!

+ + \ No newline at end of file diff --git a/html/Basics/Abbreviations and acronyms.html b/html/Basics/Abbreviations and acronyms.html new file mode 100644 index 0000000..e99bb99 --- /dev/null +++ b/html/Basics/Abbreviations and acronyms.html @@ -0,0 +1,11 @@ + + + + Example of HTML abbreviations + + +

The HTML is the publishing language of the World Wide Web.

+

The HTML is the publishing language of the World Wide Web.

+

Warning: The <acronym> tag has been removed in HTML5 and shouldn't be used anymore. Use the <abbr> tag instead.

+ + \ No newline at end of file diff --git a/html/Basics/Aligning images.html b/html/Basics/Aligning images.html new file mode 100644 index 0000000..ec0d946 --- /dev/null +++ b/html/Basics/Aligning images.html @@ -0,0 +1,11 @@ + + + +Example image alignment + + +

This image Smiley is aligned vertically top of the text.

+

This image Smiley is aligned vertically center of the text.

+

This image Smiley is aligned to the baseline of the text.

+ + \ No newline at end of file diff --git a/html/Basics/Apply transformation while rendering text on web pages using SVG.html b/html/Basics/Apply transformation while rendering text on web pages using SVG.html new file mode 100644 index 0000000..3f2f357 --- /dev/null +++ b/html/Basics/Apply transformation while rendering text on web pages using SVG.html @@ -0,0 +1,24 @@ + + + + +Rotate and Render Text with HTML5 SVG + + + + + + + Welcome to Our Website! + + + Here you will find lots of useful information. + + + + + \ No newline at end of file diff --git a/html/Basics/Checkboxes and radio buttons.html b/html/Basics/Checkboxes and radio buttons.html new file mode 100644 index 0000000..0c0b1dd --- /dev/null +++ b/html/Basics/Checkboxes and radio buttons.html @@ -0,0 +1,26 @@ + + + + Example of HTML checkboxes and radio buttons + + +
+
+ Hobbies + + + + + + +
+
+ Gender + + + + +
+
+ + \ No newline at end of file diff --git a/html/Basics/Column groups - The col and colgroup elements.html b/html/Basics/Column groups - The col and colgroup elements.html new file mode 100644 index 0000000..f11defd --- /dev/null +++ b/html/Basics/Column groups - The col and colgroup elements.html @@ -0,0 +1,22 @@ + + + + Example of HTML table column groups + + + + + + + + + + + + + + + +
row 1, cell 1row 1, cell 2
row 2, cell 1row 2, cell 2
+ + \ No newline at end of file diff --git a/html/Basics/Computer output tags.html b/html/Basics/Computer output tags.html new file mode 100644 index 0000000..ca82192 --- /dev/null +++ b/html/Basics/Computer output tags.html @@ -0,0 +1,13 @@ + + + + Example of HTML computer output tags + + +

Computer code

+

Keyboard input

+

Sample text

+

Computer variable

+

Note: These tags are often used to represents a fragment of computer code.

+ + \ No newline at end of file diff --git a/html/Basics/Create hyperlink.html b/html/Basics/Create hyperlink.html new file mode 100644 index 0000000..8ffea09 --- /dev/null +++ b/html/Basics/Create hyperlink.html @@ -0,0 +1,11 @@ + + + + Example of HTML a tag + + +

Tutorial Republic

+

Hot Air Ballons

+

Google Search

+ + \ No newline at end of file diff --git a/html/Basics/Creating HTML5 color input type.html b/html/Basics/Creating HTML5 color input type.html new file mode 100644 index 0000000..4918cbf --- /dev/null +++ b/html/Basics/Creating HTML5 color input type.html @@ -0,0 +1,13 @@ + + + +HTML5 Color Input Type + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Creating HTML5 date input type.html b/html/Basics/Creating HTML5 date input type.html new file mode 100644 index 0000000..5e3c9fa --- /dev/null +++ b/html/Basics/Creating HTML5 date input type.html @@ -0,0 +1,13 @@ + + + +HTML5 Date Input Type + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Creating HTML5 datetime input type.html b/html/Basics/Creating HTML5 datetime input type.html new file mode 100644 index 0000000..be0df4f --- /dev/null +++ b/html/Basics/Creating HTML5 datetime input type.html @@ -0,0 +1,13 @@ + + + +HTML5 Datetime Input Type + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Creating HTML5 datetime-local input type.html b/html/Basics/Creating HTML5 datetime-local input type.html new file mode 100644 index 0000000..8c8bc12 --- /dev/null +++ b/html/Basics/Creating HTML5 datetime-local input type.html @@ -0,0 +1,13 @@ + + + +HTML5 Datetime-local Input Type + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Creating HTML5 email input type.html b/html/Basics/Creating HTML5 email input type.html new file mode 100644 index 0000000..f3e7757 --- /dev/null +++ b/html/Basics/Creating HTML5 email input type.html @@ -0,0 +1,21 @@ + + + +HTML5 Email Input Type + + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Creating HTML5 month input type.html b/html/Basics/Creating HTML5 month input type.html new file mode 100644 index 0000000..ccf12ca --- /dev/null +++ b/html/Basics/Creating HTML5 month input type.html @@ -0,0 +1,13 @@ + + + +HTML5 Month Input Type + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Creating HTML5 number input type.html b/html/Basics/Creating HTML5 number input type.html new file mode 100644 index 0000000..168772b --- /dev/null +++ b/html/Basics/Creating HTML5 number input type.html @@ -0,0 +1,22 @@ + + + +HTML5 Number Input Type + + + +
+ +
+

Note: If you try to enter the number out of the range (1-10) or text character it will show error.

+ + \ No newline at end of file diff --git a/html/Basics/Creating HTML5 range input type.html b/html/Basics/Creating HTML5 range input type.html new file mode 100644 index 0000000..dca69e3 --- /dev/null +++ b/html/Basics/Creating HTML5 range input type.html @@ -0,0 +1,13 @@ + + + +HTML5 Range Input Type + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Creating HTML5 search input type.html b/html/Basics/Creating HTML5 search input type.html new file mode 100644 index 0000000..ef3141e --- /dev/null +++ b/html/Basics/Creating HTML5 search input type.html @@ -0,0 +1,13 @@ + + + +HTML5 Search Input Type + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Creating HTML5 tel input type.html b/html/Basics/Creating HTML5 tel input type.html new file mode 100644 index 0000000..09826ed --- /dev/null +++ b/html/Basics/Creating HTML5 tel input type.html @@ -0,0 +1,13 @@ + + + +HTML5 Tel Input Type + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Creating HTML5 time input type.html b/html/Basics/Creating HTML5 time input type.html new file mode 100644 index 0000000..c57b906 --- /dev/null +++ b/html/Basics/Creating HTML5 time input type.html @@ -0,0 +1,13 @@ + + + +HTML5 Time Input Type + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Creating HTML5 url input type.html b/html/Basics/Creating HTML5 url input type.html new file mode 100644 index 0000000..059d657 --- /dev/null +++ b/html/Basics/Creating HTML5 url input type.html @@ -0,0 +1,22 @@ + + + +HTML5 URL Input Type + + + +
+ +
+

Note: Enter URL in the form like http://www.google.com

+ + \ No newline at end of file diff --git a/html/Basics/Creating HTML5 week input type.html b/html/Basics/Creating HTML5 week input type.html new file mode 100644 index 0000000..abafec2 --- /dev/null +++ b/html/Basics/Creating HTML5 week input type.html @@ -0,0 +1,13 @@ + + + +HTML5 Week Input Type + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Creating a circle using SVG.html b/html/Basics/Creating a circle using SVG.html new file mode 100644 index 0000000..bbfe5fc --- /dev/null +++ b/html/Basics/Creating a circle using SVG.html @@ -0,0 +1,17 @@ + + + + +Create a Circle with HTML5 SVG + + + + + + + + \ No newline at end of file diff --git a/html/Basics/Creating a definition list.html b/html/Basics/Creating a definition list.html new file mode 100644 index 0000000..9edffa1 --- /dev/null +++ b/html/Basics/Creating a definition list.html @@ -0,0 +1,16 @@ + + + + + Example of HTML Definition List + + +

HTML Definition List

+
+
Bread
+
A baked food made of flour.
+
Coffee
+
A drink made from roasted coffee beans.
+
+ + \ No newline at end of file diff --git a/html/Basics/Creating a line using SVG.html b/html/Basics/Creating a line using SVG.html new file mode 100644 index 0000000..cbc3bd3 --- /dev/null +++ b/html/Basics/Creating a line using SVG.html @@ -0,0 +1,17 @@ + + + + +Create a Line with HTML5 SVG + + + + + + + + \ No newline at end of file diff --git a/html/Basics/Creating a mailto link - A link that sends an e-mail.html b/html/Basics/Creating a mailto link - A link that sends an e-mail.html new file mode 100644 index 0000000..becc859 --- /dev/null +++ b/html/Basics/Creating a mailto link - A link that sends an e-mail.html @@ -0,0 +1,12 @@ + + + + Example of HTML email link + + +

This is an email link: + Send Mail +

+

Note: Spaces between words should be replaced by %20 to ensure that the browser will display the text correctly.

+ + \ No newline at end of file diff --git a/html/Basics/Creating a nested list - Multi level.html b/html/Basics/Creating a nested list - Multi level.html new file mode 100644 index 0000000..a31ae8f --- /dev/null +++ b/html/Basics/Creating a nested list - Multi level.html @@ -0,0 +1,32 @@ + + + + Example of HTML nested list + + +

HTML Nested List

+
    +
  • Item 1
  • +
  • Item 2 +
      +
    • Item 2.1
    • +
    • Item 2.2
    • +
    • Item 2.3
    • +
    +
  • +
  • Item 3 +
      +
    • Item 3.1
    • +
    • Item 3.2 +
        +
      • Item 3.2.1
      • +
      • Item 3.2.2
      • +
      • Item 3.2.3
      • +
      +
    • +
    • Item 3.3
    • +
    +
  • +
+ + \ No newline at end of file diff --git a/html/Basics/Creating a nested list - Single level.html b/html/Basics/Creating a nested list - Single level.html new file mode 100644 index 0000000..1ae3e6d --- /dev/null +++ b/html/Basics/Creating a nested list - Single level.html @@ -0,0 +1,20 @@ + + + + Example of HTML nested list + + +

HTML Nested List

+
    +
  • Item 1
  • +
  • Item 2 +
      +
    • Item 2.1
    • +
    • Item 2.2
    • +
    • Item 2.3
    • +
    +
  • +
  • Item 3
  • +
+ + \ No newline at end of file diff --git a/html/Basics/Creating a rectangle using SVG.html b/html/Basics/Creating a rectangle using SVG.html new file mode 100644 index 0000000..41ff664 --- /dev/null +++ b/html/Basics/Creating a rectangle using SVG.html @@ -0,0 +1,17 @@ + + + + +Create a Rectangle with HTML5 SVG + + + + + + + + \ No newline at end of file diff --git a/html/Basics/Creating an image-map - An image with clickable regions.html b/html/Basics/Creating an image-map - An image with clickable regions.html new file mode 100644 index 0000000..c64d65d --- /dev/null +++ b/html/Basics/Creating an image-map - An image with clickable regions.html @@ -0,0 +1,16 @@ + + + +Example of HTML image map + + +

Click on a shape to see how it works:

+ Geometrical Shapes + + Circle + Triangle + Rectangle + Pentagon + + + \ No newline at end of file diff --git a/html/Basics/Creating an ordered list.html b/html/Basics/Creating an ordered list.html new file mode 100644 index 0000000..4aa351e --- /dev/null +++ b/html/Basics/Creating an ordered list.html @@ -0,0 +1,15 @@ + + + + + Example of HTML Ordered List + + +

HTML Ordered List

+
    +
  1. Mix ingredients
  2. +
  3. Bake in oven for an hour
  4. +
  5. Allow to stand for ten minutes
  6. +
+ + \ No newline at end of file diff --git a/html/Basics/Creating an unordered list.html b/html/Basics/Creating an unordered list.html new file mode 100644 index 0000000..e9e7813 --- /dev/null +++ b/html/Basics/Creating an unordered list.html @@ -0,0 +1,15 @@ + + + + + Example of HTML Unordered List + + +

HTML Unordered List

+
    +
  • Chocolate Cake
  • +
  • Black Forest Cake
  • +
  • Pineapple Cake
  • +
+ + \ No newline at end of file diff --git a/html/Basics/Creating buttons.html b/html/Basics/Creating buttons.html new file mode 100644 index 0000000..c753bd2 --- /dev/null +++ b/html/Basics/Creating buttons.html @@ -0,0 +1,11 @@ + + + + Example of HTML button + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Creating links to other HTML documents or Web resources.html b/html/Basics/Creating links to other HTML documents or Web resources.html new file mode 100644 index 0000000..77af77f --- /dev/null +++ b/html/Basics/Creating links to other HTML documents or Web resources.html @@ -0,0 +1,12 @@ + + + + + Example of HTML Links + + +

Tutorial Republic

+

kites

+

Google Search

+ + \ No newline at end of file diff --git a/html/Basics/Creating password input fields.html b/html/Basics/Creating password input fields.html new file mode 100644 index 0000000..29e46bf --- /dev/null +++ b/html/Basics/Creating password input fields.html @@ -0,0 +1,13 @@ + + + + Example of HTML Password Field + + + +
+ + +
+ + \ No newline at end of file diff --git a/html/Basics/Creating text input fields.html b/html/Basics/Creating text input fields.html new file mode 100644 index 0000000..475adc8 --- /dev/null +++ b/html/Basics/Creating text input fields.html @@ -0,0 +1,12 @@ + + + + Example of HTML Text Field + + +
+ + +
+ + \ No newline at end of file diff --git a/html/Basics/Defining alternative sources for audio element.html b/html/Basics/Defining alternative sources for audio element.html new file mode 100644 index 0000000..7aad6c2 --- /dev/null +++ b/html/Basics/Defining alternative sources for audio element.html @@ -0,0 +1,14 @@ + + + + + The HTML5 audio Element + + + + + \ No newline at end of file diff --git a/html/Basics/Defining alternative sources for video element.html b/html/Basics/Defining alternative sources for video element.html new file mode 100644 index 0000000..bec6cf9 --- /dev/null +++ b/html/Basics/Defining alternative sources for video element.html @@ -0,0 +1,10 @@ + + + + + Example of Inserting Video Using object Element + + + + + \ No newline at end of file diff --git a/html/Basics/Drawing a circle onto the canvas.html b/html/Basics/Drawing a circle onto the canvas.html new file mode 100644 index 0000000..a9aad9a --- /dev/null +++ b/html/Basics/Drawing a circle onto the canvas.html @@ -0,0 +1,23 @@ + + + + +Drawing a Circle on Canvas + + + + + + + \ No newline at end of file diff --git a/html/Basics/Drawing a line onto the canvas.html b/html/Basics/Drawing a line onto the canvas.html new file mode 100644 index 0000000..b301df3 --- /dev/null +++ b/html/Basics/Drawing a line onto the canvas.html @@ -0,0 +1,24 @@ + + + + +Drawing a Line on Canvas + + + + + + + \ No newline at end of file diff --git a/html/Basics/Drawing a rectangle onto the canvas.html b/html/Basics/Drawing a rectangle onto the canvas.html new file mode 100644 index 0000000..0d03dba --- /dev/null +++ b/html/Basics/Drawing a rectangle onto the canvas.html @@ -0,0 +1,23 @@ + + + + +Drawing a Rectangle on Canvas + + + + + + + \ No newline at end of file diff --git a/html/Basics/Drawing an arc onto the canvas.html b/html/Basics/Drawing an arc onto the canvas.html new file mode 100644 index 0000000..b6e0fde --- /dev/null +++ b/html/Basics/Drawing an arc onto the canvas.html @@ -0,0 +1,23 @@ + + + + +Drawing an Arc on Canvas + + + + + + + \ No newline at end of file diff --git a/html/Basics/Embedding SVG into HTML documents.html b/html/Basics/Embedding SVG into HTML documents.html new file mode 100644 index 0000000..f5b86eb --- /dev/null +++ b/html/Basics/Embedding SVG into HTML documents.html @@ -0,0 +1,15 @@ + + + + +Embedding SVG Into HTML Pages + + + + + Your browser support SVG. + + Sorry, your browser does not support SVG. + + + \ No newline at end of file diff --git a/html/Basics/Embedding audio in HTML documents.html b/html/Basics/Embedding audio in HTML documents.html new file mode 100644 index 0000000..00e69c3 --- /dev/null +++ b/html/Basics/Embedding audio in HTML documents.html @@ -0,0 +1,12 @@ + + + + + The HTML5 audio Element + + + + + \ No newline at end of file diff --git a/html/Basics/Embedding canvas into HTML documents.html b/html/Basics/Embedding canvas into HTML documents.html new file mode 100644 index 0000000..21bb886 --- /dev/null +++ b/html/Basics/Embedding canvas into HTML documents.html @@ -0,0 +1,17 @@ + + + + +HTML5 Canvas + + + + + + \ No newline at end of file diff --git a/html/Basics/Embedding the YouTube video in HTML documents.html b/html/Basics/Embedding the YouTube video in HTML documents.html new file mode 100644 index 0000000..b296e46 --- /dev/null +++ b/html/Basics/Embedding the YouTube video in HTML documents.html @@ -0,0 +1,12 @@ + + + + + The HTML5 video element + + + + + \ No newline at end of file diff --git a/html/Basics/Embedding video in HTML documents.html b/html/Basics/Embedding video in HTML documents.html new file mode 100644 index 0000000..eaffa6e --- /dev/null +++ b/html/Basics/Embedding video in HTML documents.html @@ -0,0 +1,14 @@ + + + + + The HTML5 video element + + + + + \ No newline at end of file diff --git a/html/Basics/Enable multiple selection inside a select box.html b/html/Basics/Enable multiple selection inside a select box.html new file mode 100644 index 0000000..1b3b77c --- /dev/null +++ b/html/Basics/Enable multiple selection inside a select box.html @@ -0,0 +1,21 @@ + + + + Example of HTML select box with multiple selection + + +
+ +
+

Note: Press control or shift key on the keyboard while clicking on the other options to enable multiple selections.

+ + \ No newline at end of file diff --git a/html/Basics/File select field.html b/html/Basics/File select field.html new file mode 100644 index 0000000..1476b44 --- /dev/null +++ b/html/Basics/File select field.html @@ -0,0 +1,12 @@ + + + + Example of file select form control + + +
+ + +
+ + \ No newline at end of file diff --git a/html/Basics/Filling color inside a circular shape on canvas.html b/html/Basics/Filling color inside a circular shape on canvas.html new file mode 100644 index 0000000..6ade4c4 --- /dev/null +++ b/html/Basics/Filling color inside a circular shape on canvas.html @@ -0,0 +1,27 @@ + + + + +Example of Filling Color inside a Circle + + + + + + + \ No newline at end of file diff --git a/html/Basics/Filling color inside a rectangle shape on canvas.html b/html/Basics/Filling color inside a rectangle shape on canvas.html new file mode 100644 index 0000000..8e9c80e --- /dev/null +++ b/html/Basics/Filling color inside a rectangle shape on canvas.html @@ -0,0 +1,27 @@ + + + + +Example of Filling Color inside a Rectangle + + + + + + + \ No newline at end of file diff --git a/html/Basics/Filling linear gradient inside canvas shapes.html b/html/Basics/Filling linear gradient inside canvas shapes.html new file mode 100644 index 0000000..9d37c17 --- /dev/null +++ b/html/Basics/Filling linear gradient inside canvas shapes.html @@ -0,0 +1,28 @@ + + + + +Example of Filling Linear Gradient inside Canvas Shapes + + + + + + + \ No newline at end of file diff --git a/html/Basics/Filling radial gradient inside canvas shapes.html b/html/Basics/Filling radial gradient inside canvas shapes.html new file mode 100644 index 0000000..8e45e5c --- /dev/null +++ b/html/Basics/Filling radial gradient inside canvas shapes.html @@ -0,0 +1,28 @@ + + + + +Example of Filling Radial Gradient inside Canvas Shapes + + + + + + + \ No newline at end of file diff --git a/html/Basics/Grouping of options inside a select box.html b/html/Basics/Grouping of options inside a select box.html new file mode 100644 index 0000000..86a2af8 --- /dev/null +++ b/html/Basics/Grouping of options inside a select box.html @@ -0,0 +1,20 @@ + + + + Example of HTML optgroup tag + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Grouping similar form fields.html b/html/Basics/Grouping similar form fields.html new file mode 100644 index 0000000..c193493 --- /dev/null +++ b/html/Basics/Grouping similar form fields.html @@ -0,0 +1,17 @@ + + + + Example of HTML fieldset tag + + +
+
+ Gender + + + + +
+
+ + \ No newline at end of file diff --git a/html/Basics/Headings - h1 to h6.html b/html/Basics/Headings - h1 to h6.html new file mode 100644 index 0000000..de03ee6 --- /dev/null +++ b/html/Basics/Headings - h1 to h6.html @@ -0,0 +1,15 @@ + + + + + Example of HTML headings tag + + +

Heading level 1

+

Heading level 2

+

Heading level 3

+

Heading level 4

+
Heading level 5
+
Heading level 6
+ + \ No newline at end of file diff --git a/html/Basics/Insert contact information.html b/html/Basics/Insert contact information.html new file mode 100644 index 0000000..7d62908 --- /dev/null +++ b/html/Basics/Insert contact information.html @@ -0,0 +1,14 @@ + + + + Example of HTML address tag (check) + + +
+ Written by Jon Doe.
+ Contact us at:
+ Post Box 210, Hollywood
+ USA +
+ + \ No newline at end of file diff --git a/html/Basics/Inserting audio in HTML documents using the embed element.html b/html/Basics/Inserting audio in HTML documents using the embed element.html new file mode 100644 index 0000000..21b8485 --- /dev/null +++ b/html/Basics/Inserting audio in HTML documents using the embed element.html @@ -0,0 +1,11 @@ + + + + + Example of Inserting Audio Using object Element + + + + + + \ No newline at end of file diff --git a/html/Basics/Inserting audio in HTML documents using the object element.html b/html/Basics/Inserting audio in HTML documents using the object element.html new file mode 100644 index 0000000..21b8485 --- /dev/null +++ b/html/Basics/Inserting audio in HTML documents using the object element.html @@ -0,0 +1,11 @@ + + + + + Example of Inserting Audio Using object Element + + + + + + \ No newline at end of file diff --git a/html/Basics/Inserting comments.html b/html/Basics/Inserting comments.html new file mode 100644 index 0000000..f2e899d --- /dev/null +++ b/html/Basics/Inserting comments.html @@ -0,0 +1,13 @@ + + + + Example of HTML comments + + + + +

This is a heading

+

This is a paragraph.

+ + \ No newline at end of file diff --git a/html/Basics/Inserting horizontal lines.html b/html/Basics/Inserting horizontal lines.html new file mode 100644 index 0000000..292beb3 --- /dev/null +++ b/html/Basics/Inserting horizontal lines.html @@ -0,0 +1,11 @@ + + + + Example of HTML hr tag + + +

This is the first paragraph of text.

+
+

This is second paragraph of text.

+ + \ No newline at end of file diff --git a/html/Basics/Inserting images into the HTML document.html b/html/Basics/Inserting images into the HTML document.html new file mode 100644 index 0000000..2fae3ed --- /dev/null +++ b/html/Basics/Inserting images into the HTML document.html @@ -0,0 +1,14 @@ + + + + + Example of HTML Images + + +
+ Flying Kites + Cloudy Sky + Hot Air Balloons +
+ + \ No newline at end of file diff --git a/html/Basics/Inserting paragraphs of text content.html b/html/Basics/Inserting paragraphs of text content.html new file mode 100644 index 0000000..96996d1 --- /dev/null +++ b/html/Basics/Inserting paragraphs of text content.html @@ -0,0 +1,11 @@ + + + + + Example of HTML Paragraphs + + +

This is a paragraph.

+

This is another paragraph.

+ + \ No newline at end of file diff --git a/html/Basics/Inserting video in HTML documents using the embed element.html b/html/Basics/Inserting video in HTML documents using the embed element.html new file mode 100644 index 0000000..d7f71f3 --- /dev/null +++ b/html/Basics/Inserting video in HTML documents using the embed element.html @@ -0,0 +1,11 @@ + + + + + Example of Embedding a YouTube Video + + + +

Source: http://www.youtube.com/watch?v=YE7VzlLtp-4

+ + \ No newline at end of file diff --git a/html/Basics/Inserting video in HTML documents using the object element.html b/html/Basics/Inserting video in HTML documents using the object element.html new file mode 100644 index 0000000..d739bdf --- /dev/null +++ b/html/Basics/Inserting video in HTML documents using the object element.html @@ -0,0 +1,10 @@ + + + + + Example of Inserting Video Using embed Element + + + + + \ No newline at end of file diff --git a/html/Basics/Linking the audio files.html b/html/Basics/Linking the audio files.html new file mode 100644 index 0000000..6d148e2 --- /dev/null +++ b/html/Basics/Linking the audio files.html @@ -0,0 +1,11 @@ + + + + + Example of Linking Audio Files + + +

Track 1

+

Track 2

+ + \ No newline at end of file diff --git a/html/Basics/Long and short quotations.html b/html/Basics/Long and short quotations.html new file mode 100644 index 0000000..18dbe4b --- /dev/null +++ b/html/Basics/Long and short quotations.html @@ -0,0 +1,12 @@ + + + + Example of HTML quotations + + +
+

This is an example of a long quotation.

+
+

This is an example of short inline quotation.

+ + \ No newline at end of file diff --git a/html/Basics/Make a hyperlink of an image.html b/html/Basics/Make a hyperlink of an image.html new file mode 100644 index 0000000..9a8db12 --- /dev/null +++ b/html/Basics/Make a hyperlink of an image.html @@ -0,0 +1,9 @@ + + + + Example of linking images + + +

Hot Air Ballons

+ + \ No newline at end of file diff --git a/html/Basics/Making a simple table - The most basic form of a table.html b/html/Basics/Making a simple table - The most basic form of a table.html new file mode 100644 index 0000000..03e22fe --- /dev/null +++ b/html/Basics/Making a simple table - The most basic form of a table.html @@ -0,0 +1,35 @@ + + + + + Example of HTML Table + + + + + + + + + + + + + + + + + + + + + + + + + + + +
No.NameEmail
1John Carterjohncarter@mail.com
2Peter Parkerpeterparker@mail.com
3John Rambojohnrambo@mail.com
+ + \ No newline at end of file diff --git a/html/Basics/Marking deleted and inserted text.html b/html/Basics/Marking deleted and inserted text.html new file mode 100644 index 0000000..fb3a256 --- /dev/null +++ b/html/Basics/Marking deleted and inserted text.html @@ -0,0 +1,15 @@ + + + + Example of HTML deleted and inserted text + + +

To Do

+
    +
  • Buy some cookies
  • +
  • Do some cleaning
  • +
  • Relaxation time
  • +
  • Visit a doctor
  • +
+ + \ No newline at end of file diff --git a/html/Basics/Move outside of an iframe.html b/html/Basics/Move outside of an iframe.html new file mode 100644 index 0000000..c888b5d --- /dev/null +++ b/html/Basics/Move outside of an iframe.html @@ -0,0 +1,9 @@ + + + + Example of moving outside of an iframe + + +

Want to move outside the iframe and go to the home page: Click here!

+ + \ No newline at end of file diff --git a/html/Basics/Navigate inside page - Jump link.html b/html/Basics/Navigate inside page - Jump link.html new file mode 100644 index 0000000..ac497a8 --- /dev/null +++ b/html/Basics/Navigate inside page - Jump link.html @@ -0,0 +1,10 @@ + + + + Example of jump link + + +

Jump Link

+

Maecenas non leo sed velit sodales scelerisque sed id felis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed tempus eros vitae lacus pulvinar faucibus. Aliquam erat volutpat. Nunc nec orci massa, a sagittis mi. Donec non arcu nec lacus bibendum varius. In pharetra diam ut mauris suscipit ac congue lectus fringilla. Cras vehicula elit in tortor luctus sodales. Etiam nunc sapien, consequat ac vulputate non, vulputate in sapien. Etiam arcu tortor, volutpat eu malesuada id, interdum laoreet tellus. Nulla eros est, semper in cursus a, elementum ac sem.

+ + \ No newline at end of file diff --git a/html/Basics/Open link in a new browser window.html b/html/Basics/Open link in a new browser window.html new file mode 100644 index 0000000..54c705c --- /dev/null +++ b/html/Basics/Open link in a new browser window.html @@ -0,0 +1,9 @@ + + + + Example of linking images + + +

W3C This is a link to a website on the World Wide Web.

+ + \ No newline at end of file diff --git a/html/Basics/Paragraph and line breaks.html b/html/Basics/Paragraph and line breaks.html new file mode 100644 index 0000000..38bec41 --- /dev/null +++ b/html/Basics/Paragraph and line breaks.html @@ -0,0 +1,11 @@ + + + + + Example of Inserting Line Breaks in HTML + + +

This is a paragraph
with line break.

+

This is
another paragraph
with line breaks.

+ + \ No newline at end of file diff --git a/html/Basics/Preformatted text (Preserve line breaks and spaces).html b/html/Basics/Preformatted text (Preserve line breaks and spaces).html new file mode 100644 index 0000000..4932dc5 --- /dev/null +++ b/html/Basics/Preformatted text (Preserve line breaks and spaces).html @@ -0,0 +1,13 @@ + + + + Example of HTML pre tag + + +
+    The pre
+        element preserves      spaces,
+            line-breaks, tabs...
+    
+ + \ No newline at end of file diff --git a/html/Basics/Rendering text on web pages using SVG.html b/html/Basics/Rendering text on web pages using SVG.html new file mode 100644 index 0000000..82b0b4e --- /dev/null +++ b/html/Basics/Rendering text on web pages using SVG.html @@ -0,0 +1,22 @@ + + + + +Render Text with HTML5 SVG + + + + + + Welcome to Our Website! + + + Here you will find lots of useful information. + + + + \ No newline at end of file diff --git a/html/Basics/Select box with a pre-selected value.html b/html/Basics/Select box with a pre-selected value.html new file mode 100644 index 0000000..b88b780 --- /dev/null +++ b/html/Basics/Select box with a pre-selected value.html @@ -0,0 +1,15 @@ + + + + Example of HTML select box + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Select boxes - A drop-down list.html b/html/Basics/Select boxes - A drop-down list.html new file mode 100644 index 0000000..b015b49 --- /dev/null +++ b/html/Basics/Select boxes - A drop-down list.html @@ -0,0 +1,15 @@ + + + + Example of HTML select box + + +
+ +
+ + \ No newline at end of file diff --git a/html/Basics/Sets the distance between table cells - The cellspacing attribute.html b/html/Basics/Sets the distance between table cells - The cellspacing attribute.html new file mode 100644 index 0000000..b25715f --- /dev/null +++ b/html/Basics/Sets the distance between table cells - The cellspacing attribute.html @@ -0,0 +1,20 @@ + + + + Example of HTML table cellspacing + + + + + + + + + + + + +
User Information
NameEmail
Johnjohn@mail.com
+

Note: The CSS margin property is the better way to control spacing between table cells.

+ + \ No newline at end of file diff --git a/html/Basics/Sets the padding of table cells - The cellpadding attribute.html b/html/Basics/Sets the padding of table cells - The cellpadding attribute.html new file mode 100644 index 0000000..067d1eb --- /dev/null +++ b/html/Basics/Sets the padding of table cells - The cellpadding attribute.html @@ -0,0 +1,20 @@ + + + + Example of HTML table cellpadding + + + + + + + + + + + + +
User Information
NameEmail
Johnjohn@mail.com
+

Note: The CSS padding property is the better way to control paddings of table cells.

+ + \ No newline at end of file diff --git a/html/Basics/Setting text direction of an element.html b/html/Basics/Setting text direction of an element.html new file mode 100644 index 0000000..1feb239 --- /dev/null +++ b/html/Basics/Setting text direction of an element.html @@ -0,0 +1,9 @@ + + + + Example of HTML bdo tag + + +

The sequence "1-2-3-4-5" was reversed as: 1-2-3-4-5

+ + \ No newline at end of file diff --git a/html/Basics/Setting the cap style for the stroke on canvas.html b/html/Basics/Setting the cap style for the stroke on canvas.html new file mode 100644 index 0000000..18f8052 --- /dev/null +++ b/html/Basics/Setting the cap style for the stroke on canvas.html @@ -0,0 +1,26 @@ + + + + +Example of Setting Stroke Cap Style + + + + + + + \ No newline at end of file diff --git a/html/Basics/Setting the dimension of a table.html b/html/Basics/Setting the dimension of a table.html new file mode 100644 index 0000000..3a90578 --- /dev/null +++ b/html/Basics/Setting the dimension of a table.html @@ -0,0 +1,19 @@ + + + + Example of setting HTML table dimensions + + + + + + + + + + + +
row 1, cell 1row 1, cell 2
row 2, cell 1row 2, cell 2
+

Note: The CSS width and height property is the better way to set dimensions of a table.

+ + \ No newline at end of file diff --git a/html/Basics/Setting the stroke color and width on canvas.html b/html/Basics/Setting the stroke color and width on canvas.html new file mode 100644 index 0000000..87e288b --- /dev/null +++ b/html/Basics/Setting the stroke color and width on canvas.html @@ -0,0 +1,26 @@ + + + + +Example of Setting Stroke Color and Width + + + + + + + \ No newline at end of file diff --git a/html/Basics/Setting width and height of the images.html b/html/Basics/Setting width and height of the images.html new file mode 100644 index 0000000..6c84b5b --- /dev/null +++ b/html/Basics/Setting width and height of the images.html @@ -0,0 +1,14 @@ + + + + + Example of Setting Dimensions for Images + + +
+ Flying Kites + Cloudy Sky + Hot Air Balloons +
+ + \ No newline at end of file diff --git a/html/Basics/Specify headings for the content.html b/html/Basics/Specify headings for the content.html new file mode 100644 index 0000000..de03ee6 --- /dev/null +++ b/html/Basics/Specify headings for the content.html @@ -0,0 +1,15 @@ + + + + + Example of HTML headings tag + + +

Heading level 1

+

Heading level 2

+

Heading level 3

+

Heading level 4

+
Heading level 5
+
Heading level 6
+ + \ No newline at end of file diff --git a/html/Basics/Specify the table caption.html b/html/Basics/Specify the table caption.html new file mode 100644 index 0000000..1715246 --- /dev/null +++ b/html/Basics/Specify the table caption.html @@ -0,0 +1,40 @@ + + + +Example of HTML caption Tag + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
User Details
No.NameEmail
1John Carterjohncarter@mail.com
2Peter Parkerpeterparker@mail.com
3John Rambojohnrambo@mail.com
+ + \ No newline at end of file diff --git a/html/Basics/Sub and Superscript text.html b/html/Basics/Sub and Superscript text.html new file mode 100644 index 0000000..bbb9b95 --- /dev/null +++ b/html/Basics/Sub and Superscript text.html @@ -0,0 +1,11 @@ + + + + Example of HTML subscript and superscript + + +

The chemical formula of Water is: H2O

+

The chemical formula of Carbon Dioxide is: CO2

+

The equation of mass-energy equivalence is: E=mc2

+ + \ No newline at end of file diff --git a/html/Basics/Submit or reset a form - The use of submit and reset button.html b/html/Basics/Submit or reset a form - The use of submit and reset button.html new file mode 100644 index 0000000..c794337 --- /dev/null +++ b/html/Basics/Submit or reset a form - The use of submit and reset button.html @@ -0,0 +1,14 @@ + + + + Example of HTML Submit and Reset Buttons + + +
+ + + + +
+ + \ No newline at end of file diff --git a/html/Basics/Table cells that span more than one rowcolumn - The rowspancolspan attribute.html b/html/Basics/Table cells that span more than one rowcolumn - The rowspancolspan attribute.html new file mode 100644 index 0000000..33c6fe4 --- /dev/null +++ b/html/Basics/Table cells that span more than one rowcolumn - The rowspancolspan attribute.html @@ -0,0 +1,50 @@ + + + + Example of HTML Table Rowspan and Colspan + + +

Example of Table Rowspan

+ + + + + + + + + + + + + + + + + + + +
Users Info
1John Carterjohncarter@mail.com
2Peter Parkerpeterparker@mail.com
3John Rambojohnrambo@mail.com
+

Example of Table Colspan

+ + + + + + + + + + + + + + + + + + + +
Users Info
1John Carterjohncarter@mail.com
2Peter Parkerpeterparker@mail.com
3John Rambojohnrambo@mail.com
+ + \ No newline at end of file diff --git a/html/Basics/Tables with borders - Adding the default table borders.html b/html/Basics/Tables with borders - Adding the default table borders.html new file mode 100644 index 0000000..f835e63 --- /dev/null +++ b/html/Basics/Tables with borders - Adding the default table borders.html @@ -0,0 +1,19 @@ + + + + Example of HTML tables default border + + + + + + + + + + + +
row 1, cell 1row 1, cell 2
row 2, cell 1row 2, cell 2
+

Note: The CSS border property is the better way to set borders for tables.

+ + \ No newline at end of file diff --git a/html/Basics/Text formatting.html b/html/Basics/Text formatting.html new file mode 100644 index 0000000..096a601 --- /dev/null +++ b/html/Basics/Text formatting.html @@ -0,0 +1,19 @@ + + + + + Example of HTML Paragraphs + + +

This text is bold

+

This is computer code

+

This text is emphasized

+

This text is italic

+

This text is small

+

This text is marked

+

This text is strongly emphasized

+

This is subscript and superscript

+

This text is inserted to the document

+

This text is deleted from the document

+ + \ No newline at end of file diff --git a/html/Basics/Textarea - A multi-line text input field.html b/html/Basics/Textarea - A multi-line text input field.html new file mode 100644 index 0000000..81495f5 --- /dev/null +++ b/html/Basics/Textarea - A multi-line text input field.html @@ -0,0 +1,12 @@ + + + + Example of HTML From Textarea + + +
+ + +
+ + \ No newline at end of file diff --git a/html/Basics/Using image as a link.html b/html/Basics/Using image as a link.html new file mode 100644 index 0000000..9a8db12 --- /dev/null +++ b/html/Basics/Using image as a link.html @@ -0,0 +1,9 @@ + + + + Example of linking images + + +

Hot Air Ballons

+ + \ No newline at end of file diff --git a/html/Basics/blockquote.html b/html/Basics/blockquote.html new file mode 100644 index 0000000..8fb91cb --- /dev/null +++ b/html/Basics/blockquote.html @@ -0,0 +1,12 @@ + + + +Html5 + + + +Seneca says:
+
Admire who tries,
+but fails
+ + \ No newline at end of file diff --git a/html/Basics/definition_list.html b/html/Basics/definition_list.html new file mode 100644 index 0000000..f5f987d --- /dev/null +++ b/html/Basics/definition_list.html @@ -0,0 +1,17 @@ + + + +Html5 + + + +
+
Term 1
+
Definition 1
+
Term 2
+
Definition 2
+
Term 3
+
Definition 3
+
+ + \ No newline at end of file diff --git a/html/Basics/drag-and-drop.html b/html/Basics/drag-and-drop.html new file mode 100644 index 0000000..5ebea80 --- /dev/null +++ b/html/Basics/drag-and-drop.html @@ -0,0 +1,128 @@ + + + + + Drag and Drop + + + +

Drag and Drop

+ +

+ + + +

+ +
Drag Me!
+ +
Drop Here!
+ +
    +
+ + + + \ No newline at end of file diff --git a/html/Basics/drag-handle.html b/html/Basics/drag-handle.html new file mode 100644 index 0000000..1e3cb75 --- /dev/null +++ b/html/Basics/drag-handle.html @@ -0,0 +1,46 @@ + + + + + Drag Handle + + + +

Drag Handle

+ +
+
+
+
+ + + + + \ No newline at end of file diff --git a/html/Basics/draggable.html b/html/Basics/draggable.html new file mode 100644 index 0000000..2d3f58c --- /dev/null +++ b/html/Basics/draggable.html @@ -0,0 +1,48 @@ + + + + + Draggable + + + +

Draggable

+ +
Drag Me!
+ + + + \ No newline at end of file diff --git a/html/Basics/home.html b/html/Basics/home.html new file mode 100644 index 0000000..c63d859 --- /dev/null +++ b/html/Basics/home.html @@ -0,0 +1,666 @@ + + + +Amazon.in Associates Central - Home + + + + + + + + + + + + + + + +
+ + + + +
+
+
+ + + +
+
+
+ +
+ +
+
+
+
+Total Fees +
+
+₹846.76 +
+
+Clicks +
+
+172 +
+
+
+ +
+
+
+
+Summary for This Month +
+ +
+
+
+
Total Items Shipped: +
3 +
Total Earnings: +
₹40.19 +
Total Ordered Items: +
3 +
Clicks +
73 +
Conversion: +
4.11% +
+Last update: Apr 14 2017 +
+
+Combined report for all tracking IDs +
+
+ +
+ +
+
+ +
+
+
+
+ Deal of the Day, Lightning Deals and more... +
+
+
+
+ DYK5Prime +
+
+ +
+ + + + +
+
+
+ +
+
+
+
+
+
+ + + + + + + + + +
+ + + + + \ No newline at end of file diff --git a/html/Basics/kanban.html b/html/Basics/kanban.html new file mode 100644 index 0000000..b8140a9 --- /dev/null +++ b/html/Basics/kanban.html @@ -0,0 +1,162 @@ + + + + + Kanban Board + + + +

Kanban Board

+ +
+
+

To Do

+
Make Killer App
+
Retire!
+
+
+

Doing

+
Learn HTML5
+
+
+

Done

+
+
+ + + + \ No newline at end of file diff --git a/html/Basics/nested_list.html b/html/Basics/nested_list.html new file mode 100644 index 0000000..281833b --- /dev/null +++ b/html/Basics/nested_list.html @@ -0,0 +1,23 @@ + + + +Html5 + + + +
    +
  1. Titles
  2. +
  3. Html5 lists +
      +
    • Sorted lists
    • +
    • Unsorted lists
    • +
    • Nested lists
    • +
    • Definition lists
    • +
    • Menu lists
    • +
    +
  4. +
  5. Html5 tables
  6. +
  7. Html5 forms
  8. +
+ + \ No newline at end of file diff --git a/html/Basics/paragraphs.html b/html/Basics/paragraphs.html new file mode 100644 index 0000000..a03da23 --- /dev/null +++ b/html/Basics/paragraphs.html @@ -0,0 +1,21 @@ + + + +Html5 + + + +

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod +tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, +quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo +consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse +cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non +proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

+

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod +tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, +quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo +consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse +cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non +proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

+ + \ No newline at end of file diff --git a/html/Basics/separators.html b/html/Basics/separators.html new file mode 100644 index 0000000..14a54f7 --- /dev/null +++ b/html/Basics/separators.html @@ -0,0 +1,12 @@ + + + +Html5 + + + +Chapter 1 +
+Chapter 2 + + \ No newline at end of file diff --git a/html/Basics/sortable.html b/html/Basics/sortable.html new file mode 100644 index 0000000..293ee1f --- /dev/null +++ b/html/Basics/sortable.html @@ -0,0 +1,103 @@ + + + + + Sortable Lists + + + +

Sortable Lists

+ +
    +
  • foo
  • +
  • bar
  • +
  • baz
  • +
  • quux
  • +
+ + + + \ No newline at end of file diff --git a/html/Basics/sorted_list.html b/html/Basics/sorted_list.html new file mode 100644 index 0000000..0c46860 --- /dev/null +++ b/html/Basics/sorted_list.html @@ -0,0 +1,17 @@ + + + +Html5 + + + +Html5 lists: +
    +
  1. Sorted lists
  2. +
  3. Unsorted lists
  4. +
  5. Nested lists
  6. +
  7. Definition lists
  8. +
  9. Menu lists
  10. +
+ + \ No newline at end of file diff --git a/html/Basics/title.html b/html/Basics/title.html new file mode 100644 index 0000000..1f4d31b --- /dev/null +++ b/html/Basics/title.html @@ -0,0 +1,15 @@ + + + +Html5 + + + +

Title of level 1

+

Title of level 2

+

Title of level 3

+

Title of level 4

+
Title of level 5
+
Title of level 6
+ + \ No newline at end of file diff --git a/html/Basics/title_css.html b/html/Basics/title_css.html new file mode 100644 index 0000000..32ecb44 --- /dev/null +++ b/html/Basics/title_css.html @@ -0,0 +1,16 @@ + + + +Html5 + + + + +

Title of level 3

+

Title of level 3

+ + + \ No newline at end of file diff --git a/html/Basics/unsorted_list.html b/html/Basics/unsorted_list.html new file mode 100644 index 0000000..838b380 --- /dev/null +++ b/html/Basics/unsorted_list.html @@ -0,0 +1,17 @@ + + + +Html5 + + + +Html5 lists: +
    +
  • Sorted lists
  • +
  • Unsorted lists
  • +
  • Nested lists
  • +
  • Definition lists
  • +
  • Menu lists
  • +
+ + \ No newline at end of file diff --git a/html/README.md b/html/README.md new file mode 100644 index 0000000..256282c --- /dev/null +++ b/html/README.md @@ -0,0 +1,3 @@ +# Hypertext Markup Language (HTML) + +HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScript. \ No newline at end of file diff --git a/java/Basics/A Ball Moving round the window.java b/java/Basics/A Ball Moving round the window.java new file mode 100644 index 0000000..e572dd5 --- /dev/null +++ b/java/Basics/A Ball Moving round the window.java @@ -0,0 +1,153 @@ +A Ball Moving round the window + +:/* + */ +import java.applet.*; +import java.awt.*; +public class screencircle2 extends Applet implements Runnable +{ + Thread t; + int i,j,k,l,flag=0,m,x1,y1,x2,y2,m1,x3,y3,m2,m3; + Color bg; + public void init() + { + } + public void start() + { + t=new Thread(this,"a"); + t.start(); + } + public void run() + { + paint1(); + } + public void paint1() + { + Graphics g=getGraphics(); + try + { + for(i=0;i<260;i++) + { + for(j=130;j<=260;j++) + { + g.setColor(Color.red); + g.fillOval(i,j,40,40); + Thread.sleep(50); + i=i+5; + j=j+5; + paint2(); + if(j>=260) + { + k=i; + l=j; + paint3(); + break; + } + } + } + } + catch(InterruptedException s) + { + //ShowStatus("error"); + } + } + public void paint3() + { + setBackground(Color.black); + Graphics h=getGraphics(); + try + { + for(x1=k;x1<=260;x1++) + { + for(y1=j;y1>1;y1--) + { + h.setColor(Color.red); + h.fillOval(x1,y1,40,40); + Thread.sleep(50); + x1=x1+6; + y1=y1-4; + paint2(); + if(x1>=260) + { + m=x1; + m1=y1; + paint4(); + } + } + } + } + catch(InterruptedException s1) + { + //ShowStatus("error"); + } + } + public void paint4() + { + Graphics h1=getGraphics(); + try + { + for(x2=m;x2>=40;x2--) + { + for(y2=m1;y2>=1;y1--) + { + h1.setColor(Color.red); + h1.fillOval(x2,y2,40,40); + Thread.sleep(50); + x2=x2-5; + y2=y2-6; + paint2(); + if(y2<=1) + { + m2=x2; + m3=y2; + paint5(); + } + } + } + } + catch(InterruptedException s1) + { + //ShowStatus("error"); + } + } + public void paint5() + { + setBackground(Color.black); + + Graphics h2=getGraphics(); + try + { + for(x3=m2;x3>=1;x3--) + { + for(y3=m3;y3<260;y3++) + { + h2.setColor(Color.red); + h2.fillOval(x3,y3,40,40); + Thread.sleep(50); + x3=x3-6; + y3=y3+4; + paint2(); + if(x3<=1) + { + m=x1; + m1=y1; + paint1(); + } + } + } + } + catch(InterruptedException s1) + { + //ShowStatus("error"); + } + } + + + public void paint2() + { + Graphics d=getGraphics(); + d.setColor(Color.white); + d.fillRect(0,0,300,300); + setBackground(Color.black); + } +} diff --git a/java/Basics/Account application.java b/java/Basics/Account application.java new file mode 100644 index 0000000..6e76e71 --- /dev/null +++ b/java/Basics/Account application.java @@ -0,0 +1,10 @@ +Account application + +package com.ack.learning.examples.account; + +public class AccountApplication { + public static void main( String[] args ) { + DepositAccount acc = new DepositAccount(); + System.out.println( acc.getName() ); + } +} diff --git a/java/Basics/Account this.java b/java/Basics/Account this.java new file mode 100644 index 0000000..e0bac64 --- /dev/null +++ b/java/Basics/Account this.java @@ -0,0 +1,23 @@ +Account this + +package com.ack.learning.examples.account; + +public class AccountThis { + public AccountThis() { + System.out.println( "created an account object" ); + } + + public AccountThis( String name ) { + this(); + System.out.println( "created account with name " + name ); + } + + public AccountThis( String name, double amount ) { + this( name ); + System.out.println( "create account with amount " + amount ); + } + + public static void main( String[] args ) { + AccountThis hsbc = new AccountThis( "jerry", 25d ); + } +} diff --git a/java/Basics/Account.java b/java/Basics/Account.java new file mode 100644 index 0000000..e2ea64c --- /dev/null +++ b/java/Basics/Account.java @@ -0,0 +1,23 @@ +Account + +package com.ack.learning.examples.account; + +public class Account { + public Account() { + System.out.println( "created an account object" ); + } + + public Account( String name ) { + System.out.println( "created account -> " + name ); + } + + public Account( String name, double amount ) { + System.out.println( "account " + name + " with " + amount ); + } + + public static void main( String[] args ) { + Account lloyds = new Account(); + Account tsg = new Account( "barry" ); + Account hsbc = new Account( "jerry", 25d ); + } +} diff --git a/java/Basics/An interface.java b/java/Basics/An interface.java new file mode 100644 index 0000000..13fdf85 --- /dev/null +++ b/java/Basics/An interface.java @@ -0,0 +1,57 @@ +An interface + + + +public interface AnInterface { + // can define constants in interfaces + public static final int MAX_VALUE = 300; + + // but really use interfaces for declaring methods + public void aMethod(); + + public int anotherMethod( String hey ) throws Exception; + + public void yetAnotherMethod() throws Exception, ArithmeticException; +} + +class ImplementInterfaceClass implements AnInterface { + + public void aMethod() { + + } + + // note that methods are matched on formal parameter types and + // method name. + public int anotherMethod( String yep ) throws Exception { + // note that when you implement an interface, its constants + // are brought into the defining class's scope + if( true ) { + return MAX_VALUE; + } + else { + // however, best to always prefix constants with the defining + // class or interface for readability purposes + return AnInterface.MAX_VALUE; + } + } + + /** + * this causes a duplication definition of anotherMethod because + * the method signature only differs by the return type. In Java, + * if two method differ only by the return type they are the same method + * from an inheritance perspective + * + public String anotherMethod(String yep) throws Exception + { + return null; + } + */ + + // finally, you can selectively choose which exception to declare + // on the throws clause of the implementing method, here we choose to omit + // Exception + public void yetAnotherMethod() throws ArithmeticException { + + } + +} diff --git a/java/Basics/ArithmeticProgression.java b/java/Basics/ArithmeticProgression.java new file mode 100644 index 0000000..f8c1b3a --- /dev/null +++ b/java/Basics/ArithmeticProgression.java @@ -0,0 +1,44 @@ +package com.jwetherell.algorithms.sequence; + +/** + * Compute the result of adding a sequence of numbers from N (startNumber) to N+X (startNumber+numberOfNumbersToCompute) + *

+ * https://en.wikipedia.org/wiki/Arithmetic_progression + *
+ * @author Justin Wetherell + */ +public class ArithmeticProgression { + + /** + * Compute the result of adding X (numberOfNumbersToCompute) together starting at N (startNumber). + *

+ * e.g. result = N + (N+1) + (N+2) + (N+3) + ..... + (N+X) + */ + public static final long sequenceTotalUsingLoop(int startNumber, int numberOfNumbersToCompute) { + int start = startNumber; + int length = numberOfNumbersToCompute; + long result = 0L; + while (length > 0) { + result += start++; + length--; + } + return result; + } + + /** + * Compute the result of adding X (numberOfNumbersToCompute) together starting at N (startNumber) using triangular numbers. + *

+ * e.g. result = N + (N+1) + (N+2) + (N+3) + ..... + (N+X)
+ *
+ * https://en.wikipedia.org/wiki/Triangular_number + */ + public static final long sequenceTotalUsingTriangularNumbers(int startNumber, int numberOfNumbersToCompute) { + // n*(n+1)/2 + final int start = startNumber; + final int length = numberOfNumbersToCompute; + + long result = length * (length + 1) / 2; + result += (start - 1) * length; + return result; + } +} diff --git a/java/Basics/Armstrong (Java).java b/java/Basics/Armstrong (Java).java new file mode 100644 index 0000000..05916ce --- /dev/null +++ b/java/Basics/Armstrong (Java).java @@ -0,0 +1,19 @@ +class ArmstrongExample +{ + public static void main(String[] args) + { + int c=0,a,temp; + int n=153;//It is the number to check armstrong + temp=n; + while(n>0) + { + a=n%10; + n=n/10; + c=c+(a*a*a); + } + if(temp==c) + System.out.println("armstrong number"); + else + System.out.println("Not armstrong number"); + } +} \ No newline at end of file diff --git a/java/Basics/Arrays and collections.java b/java/Basics/Arrays and collections.java new file mode 100644 index 0000000..536f83f --- /dev/null +++ b/java/Basics/Arrays and collections.java @@ -0,0 +1,27 @@ +Arrays and collections + + + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +public class ArraysAndCollections { + public static void main( String[] args ) { + // create a list of integers + List l = new LinkedList(); + for( int i = 1; i < 11; i++ ) { + l.add( new Integer( i ) ); + } + + // convert to array + Object[] integers = l.toArray(); + + // convert back to list + List ll = Arrays.asList( integers ); + + // output lists + System.out.println( l ); + System.out.println( ll ); + } +} diff --git a/java/Basics/Arrays of arrays.java b/java/Basics/Arrays of arrays.java new file mode 100644 index 0000000..bb4f708 --- /dev/null +++ b/java/Basics/Arrays of arrays.java @@ -0,0 +1,32 @@ +Arrays of arrays + + + +public class ArraysOfArrays { + public static void main( String[] args ) { + // creates an array of integer arrays + // note that the column sizes are jagged, that is, + // of different sizes + int[][] matrix = + { + {1, 2, 4}, + {2, 4}, + {5, 6, 7, 8, 9} + }; + + // cycle through the array, and output its contents + for( int i = 0; i < matrix.length; i++ ) { + for( int j = 0; j < matrix[i].length; j++ ) { + System.out.println( "matrix[" + i + "][" + j + "] = " + matrix[i][j] ); + } + } + + // specify array of strings + String[][] anotherMatrix = + { + {"hello"}, + new String[]{"hello", "world"}, /* note, embed new arrays here */ + {"the", "quick", "brown", "fox"}, /* note, comma can be added here */ + }; + } +} diff --git a/java/Basics/BasicDateFormatting.java b/java/Basics/BasicDateFormatting.java new file mode 100644 index 0000000..d524f15 --- /dev/null +++ b/java/Basics/BasicDateFormatting.java @@ -0,0 +1,38 @@ +BasicDateFormatting + +package com.ack.j2se.date; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +public class BasicDateFormatting { + public static void main( String[] args ) throws Exception { + // get today's date + Date today = Calendar.getInstance().getTime(); + + // create a short version date formatter + DateFormat shortFormatter + = SimpleDateFormat.getDateInstance( SimpleDateFormat.SHORT ); + + // create a long version date formatter + DateFormat longFormatter + = SimpleDateFormat.getDateInstance( SimpleDateFormat.LONG ); + + // create date time formatter, medium for day, long for time + DateFormat mediumFormatter + = SimpleDateFormat.getDateTimeInstance( SimpleDateFormat.MEDIUM, + SimpleDateFormat.LONG ); + + // use the formatters to output the dates + System.out.println( shortFormatter.format( today ) ); + System.out.println( longFormatter.format( today ) ); + System.out.println( mediumFormatter.format( today ) ); + + // convert form date -> text, and text -> date + String dateAsText = shortFormatter.format( today ); + Date textAsDate = shortFormatter.parse( dateAsText ); + System.out.println( textAsDate ); + } +} diff --git a/java/Basics/BinaryConverter (Java).java b/java/Basics/BinaryConverter (Java).java new file mode 100644 index 0000000..9704c81 --- /dev/null +++ b/java/Basics/BinaryConverter (Java).java @@ -0,0 +1,56 @@ + +public class BinaryConverter +{ + + public static void main(String[] args) + { + for(int i = -5; i < 33; i++) + { + System.out.println(i + ": " + toBinary(i)); + System.out.println(i); + //always another way + System.out.println(i + ": " + Integer.toBinaryString(i)); + } + } + + /* + * pre: none + * post: returns a String with base10Num in base 2 + */ + public static String toBinary(int base10Num) + { + boolean isNeg = base10Num < 0; + base10Num = Math.abs(base10Num); + String result = ""; + while(base10Num > 1) + { + result = (base10Num % 2) + result; + base10Num /= 2; + } + assert base10Num == 0 || base10Num == 1 : "value is not <= 1: " + base10Num; + result = base10Num + result; + assert all0sAnd1s(result); + if( isNeg ) + result = "-" + result; + return result; + } + + /* + * pre: cal != null + * post: return true if val consists only of characters 1 and 0, false otherwise + */ + public static boolean all0sAnd1s(String val) + { + assert val != null : "Failed precondition all0sAnd1s. parameter cannot be null"; + boolean all = true; + int i = 0; + char c; + while(all && i < val.length()) + { + c = val.charAt(i); + all = c == '0' || c == '1'; + i++; + } + return all; + } +} diff --git a/java/Basics/Break statements.java b/java/Basics/Break statements.java new file mode 100644 index 0000000..8a651fd --- /dev/null +++ b/java/Basics/Break statements.java @@ -0,0 +1,32 @@ +Break statements + + + +public class BreakStatements { + public static void main( String[] args ) { + + /** + * break out of a loop here + */ + for( int i = 0; i < 10; i++ ) { + System.out.println( i ); + if( i == 5 ) { + break; + } + } + + /** + * note, break only breaks you out of the current loop + */ + for( int i = 0; i < 10; i++ ) { + for( int j = 0; j < 10; j++ ) { + if( i == j ) { + System.out.println( "breaking out with i = " + i ); + break; + } + } + } + + boolean doneGetOut = false; + } +} diff --git a/java/Basics/BubbleSort (Java).java b/java/Basics/BubbleSort (Java).java new file mode 100644 index 0000000..2983922 --- /dev/null +++ b/java/Basics/BubbleSort (Java).java @@ -0,0 +1,37 @@ +public class BubbleSortExample +{ + static void bubbleSort(int[] arr) + { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++) + { + for(int j=1; j < (n-i); j++) + { + if(arr[j-1] > arr[j]) + { + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + } + } + } + public static void main(String[] args) + { + int arr[] = {3,60,35,2,45,320,5}; + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++) + { + System.out.print(arr[i] + " "); + } + System.out.println(); + bubbleSort(arr);//sorting array elements using bubble sort + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++) + { + System.out.print(arr[i] + " "); + } + } +} \ No newline at end of file diff --git a/java/Basics/CLock CAN TAlk REALLy.java b/java/Basics/CLock CAN TAlk REALLy.java new file mode 100644 index 0000000..f811b9d --- /dev/null +++ b/java/Basics/CLock CAN TAlk REALLy.java @@ -0,0 +1,88 @@ +CLock CAN TAlk REALLy + +import java.util.*; +public class CLockTAlk +{ + public static void main(String[]args) + { + // get current time and date + Calendar now = Calendar.getInstance(); + int hour = now.get(Calendar.HOUR_OF_DAY); + int minute = now.get(Calendar.MINUTE); + int month = now.get(Calendar.MONTH)+ 1; + int day = now.get(Calendar.DAY_OF_MONTH); + int year = now.get(Calendar.YEAR); + + // display gretting + if (hour < 12) + System.out.println("Good morning Sir! +Have you ate breakfast +yet?"); + else if (hour < 18) + System.out.println("Good afternoon Sir! +Have you ate lunch +yet?"); + else + System.out.println("Good evening Sir! +Have you ate dinner +yet?"); + + // begin time message by showing the minutes + System.out.print("It is"); + if (minute != 0) + { + System.out.print(" " + minute + " "); + System.out.print( (minute != 1) ? "minutes" : "minute"); + System.out.print(" past"); + } + + // display the hour + System.out.print(" "); + System.out.print( (hour > 12) ? (hour - 12) : hour ); + System.out.print(" 0'clock on "); + + // display the name of the month + switch (month) + { + case 1: + System.out.print("January"); + break; + case 2: + System.out.print("February"); + break; + case 3: + System.out.print("March"); + break; + case 4: + System.out.print("April"); + break; + case 5: + System.out.print("May"); + break; + case 6: + System.out.print("June"); + break; + case 7: + System.out.print("July"); + break; + case 8: + System.out.print("August"); + break; + case 9: + System.out.print("September"); + break; + case 10: + System.out.print("October"); + break; + case 11: + System.out.print("November"); + break; + case 12: + System.out.print("December"); + } + + // display the date and year + System.out.println(" " + day + ", " + year + "."); + } + +} diff --git a/java/Basics/Calculating compound interest.java b/java/Basics/Calculating compound interest.java new file mode 100644 index 0000000..8d517f2 --- /dev/null +++ b/java/Basics/Calculating compound interest.java @@ -0,0 +1,29 @@ +Calculating compound interest + + import java.text.DecimalFormat; + import javax.swing.JOptionPane; + import javax.swing.JTextArea; + + public class Interest + { + public static void main( String args[] ) + { + double amount, principal = 1000.0, rate = .05; + + DecimalFormat precisionTwo = new DecimalFormat( "0.00" ); + JTextArea outputTextArea = new JTextArea( 11, 20 ); + + outputTextArea.append( "Year\tAmount on deposit\n" ); + + for ( int year = 1; year <= 10; year++ ) + { + amount = principal * Math.pow( 1.0 + rate, year ); + outputTextArea.append( year + "\t" + + precisionTwo.format( amount ) + "\n" ); + } + + JOptionPane.showMessageDialog( null, outputTextArea, "Compound Interest", JOptionPane.INFORMATION_MESSAGE ); + + System.exit( 0 ); // terminate the application + } + } diff --git a/java/Basics/Calculator In Java.java b/java/Basics/Calculator In Java.java new file mode 100644 index 0000000..a305e86 --- /dev/null +++ b/java/Basics/Calculator In Java.java @@ -0,0 +1,157 @@ +Calculator In Java + +import java.awt.*; +import java.awt.event.*; +import java.applet.*; + +public class CalculatorApplet extends Applet implements ActionListener +{ +private Button keysArray[]; +private Panel keyPad; +private TextField lcdField; +private double result; +private boolean first; +private boolean foundKey; +static boolean clearText; +private int prevOperator; + +public void init() +{ + lcdField = new TextField(20); + keyPad = new Panel (); + keysArray = new Button[17]; + result = 0.0; + prevOperator = 0; + first = true; + clearText = true; + + //Set frame layout manager setLayout(new BorderLayout()); + + lcdField.setEditable(false); + + //Create buttons + for (int i = 0; i <=9; i++) + keysArray[i] = new Button(String.valueOf(i)); + keysArray[10] = new Button("/"); + keysArray[11] = new Button("*"); + keysArray[12] = new Button("-"); + keysArray[13] = new Button("+"); + keysArray[14] = new Button("="); + keysArray[15] = new Button("."); + keysArray[16] = new Button("CLR"); + + //Set panel layout manager + keyPad.setLayout(new GridLayout (4,4)); + + //Add button to keyPad panel + for (int i = 7; i <=10; i++) //adds Button 7,8,9, and divide to +Panel + keyPad.add(keysArray[i]); + + for (int i = 4; i <6; i++) //adds buttons 4,5,6 to Panel + keyPad.add(keysArray[i]); + + keyPad.add(keysArray[11]); //adds multiply button to Panel + + for (int i = 1; i <= 3;i++) //adds buttons 1,2 and 3 to Panel + keyPad.add(keysArray[i]); + + keyPad.add(keysArray[12]);//adds minus button to Panel + + keyPad.add(keysArray[0]); //adds 0 key to Panel + + for (int i = 15; i >=13; i--) + keyPad.add(keysArray[i]); //adds decimal point, equal, and addition +ke +ys Panel + + add(lcdField, BorderLayout.NORTH); //adds text field to top of +Frame + add(keyPad, BorderLayout.CENTER); //adds Panel to center of Frame + add(keysArray[16], BorderLayout.EAST); //adds Clear key to right +side +of applet + + for(int i = 0; i < keysArray.length; i++) + keysArray[i].addActionListener(this); + } + + public void actionPerformed(ActionEvent e) + { + foundKey = false; + + //Search for the key pressed + for (int i = 0; i < keysArray.length && !foundKey; i++) + if(e.getSource() == keysArray[i]) //key match found + { + foundKey = true; + switch(i) + { + case 0: case 1: case 2: case 3: case 4: //number buttons + case 5: case 6: case 7: case 8: case 9: //0-9 + case 15: + if (clearText) + { + lcdField.setText(""); + clearText = false; + } + lcdField.setText(lcdField.getText() + + keysArray[i].getLabel()); + break; + + case 10:// divide button + case 11:// multiply button + case 12:// minus button + case 13:// plus button + case 14:// equal button + clearText = true; + if (first) // First operand + { + if(lcdField.getText().length()==0) + result = 0.0; + else + result = Double.valueOf(lcdField.getText()).doubleValue(); + + first = false; + prevOperator = i; //save previous operator + } + else //second operand already enter, so calculator total + { + switch(prevOperator) + { + case 10: //divide Button + result /= Double.valueOf(lcdField.getText()). + doubleValue(); + break; + case 11: //multiply Button + result *= Double.valueOf(lcdField.getText()). + doubleValue(); + break; + case 12: //minus button + result -= Double.valueOf(lcdField.getText()). + doubleValue(); + break; + case 13: //plus button + result += Double.valueOf(lcdField.getText()). + doubleValue(); + break; + } + lcdField.setText(Double.toString(result)); + if (i==14)//equal button + first = true; + else + prevOperator = i; //save previous opetator + } + break; + + case 16://Clear button + clearText = true; + first = true; + lcdField.setText(""); + result = 0.0; + prevOperator = 0; + break; + } + } + } + } diff --git a/java/Basics/Calculator with both Standard and Scientific Mode.java b/java/Basics/Calculator with both Standard and Scientific Mode.java new file mode 100644 index 0000000..cf70fa6 --- /dev/null +++ b/java/Basics/Calculator with both Standard and Scientific Mode.java @@ -0,0 +1,634 @@ +Calculator with both Standard and Scientific Mode + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.event.*; + +public class calculator extends JFrame implements ActionListener +{ + JTextField jtx; + double temp,temp1,result,a; + static double m1,m2; + int k=1,x=0,y=0,z=0; + char ch; + JButton +one,two,three,four,five,six,seven,eight,nine,zero,clr,pow2,pow3,exp; + JButton +plus,min,div,lg,rec,mul,eq,plmi,poin,mr,mc,mp,mm,sqrt,sin,cos,tan; + JMenuBar bar; + JMenu view; + JMenuItem exit; + JRadioButtonMenuItem standard,scientific; + JSeparator jp; + ButtonGroup bg; + Container cont; + JPanel textPanel,syntpanel,buttonpanel; + calculator() + { + cont=getContentPane(); + cont.setLayout(new BorderLayout()); + JPanel textpanel=new JPanel(); + Font font=new Font("Arial",Font.PLAIN,18); + jtx=new JTextField(25); + jtx.setFont(font); + jtx.setHorizontalAlignment(SwingConstants.RIGHT); + jtx.addKeyListener(new KeyAdapter() + { + public void keyTyped(KeyEvent keyevent) + { + char c=keyevent.getKeyChar(); + if(c>='0' && c<='9') + { + } + else + { + keyevent.consume(); + } + } + }); + textpanel.add(jtx); + buttonpanel=new JPanel(); + buttonpanel.setLayout(new GridLayout(5,4,2,2)); + boolean t=true; + syntpanel=new JPanel(); + syntpanel.setLayout(new GridLayout(5,1)); + bar=new JMenuBar(); + view=new JMenu("View"); + + standard =new JRadioButtonMenuItem("Standard",true); + standard.setMnemonic('S'); + standard.addItemListener(new radiohandler()); + scientific =new JRadioButtonMenuItem("Sceintific"); + standard.setMnemonic('c'); + scientific.addItemListener(new radiohandler()); + jp=new JSeparator(); + exit=new JMenuItem("Exit"); + standard.setMnemonic('E'); + exit.addActionListener(this); + bg=new ButtonGroup(); + bg.add(standard); + bg.add(scientific); + view.add(standard); + view.add(scientific); + view.add(jp); + view.add(exit); + bar.add(view); + setJMenuBar(bar); + + mr=new JButton("MR"); + buttonpanel.add(mr); + mr.addActionListener(this); + seven=new JButton("7"); + buttonpanel.add(seven); + seven.addActionListener(this); + eight=new JButton("8"); + buttonpanel.add(eight); + eight.addActionListener(this); + nine=new JButton("9"); + buttonpanel.add(nine); + nine.addActionListener(this); + clr=new JButton("AC"); + buttonpanel.add(clr); + clr.addActionListener(this); + + mc=new JButton("MC"); + buttonpanel.add(mc); + mc.addActionListener(this); + four=new JButton("4"); + buttonpanel.add(four); + four.addActionListener(this); + five=new JButton("5"); + buttonpanel.add(five); + five.addActionListener(this); + six=new JButton("6"); + buttonpanel.add(six); + six.addActionListener(this); + mul=new JButton("*"); + buttonpanel.add(mul); + mul.addActionListener(this); + + mp=new JButton("M+"); + buttonpanel.add(mp); + mp.addActionListener(this); + one=new JButton("1"); + buttonpanel.add(one); + one.addActionListener(this); + two=new JButton("2"); + buttonpanel.add(two); + two.addActionListener(this); + three=new JButton("3"); + buttonpanel.add(three); + three.addActionListener(this); + min=new JButton("-"); + buttonpanel.add(min); + min.addActionListener(this); + + mm=new JButton("M-"); + buttonpanel.add(mm); + mm.addActionListener(this); + zero=new JButton("0"); + buttonpanel.add(zero); + zero.addActionListener(this); + plmi=new JButton("+/-"); + buttonpanel.add(plmi); + plmi.addActionListener(this); + poin=new JButton("."); + buttonpanel.add(poin); + poin.addActionListener(this); + plus=new JButton("+"); + buttonpanel.add(plus); + plus.addActionListener(this); + + + rec=new JButton("1/x"); + buttonpanel.add(rec); + rec.addActionListener(this); + sqrt=new JButton("Sqrt"); + buttonpanel.add(sqrt); + sqrt.addActionListener(this); + lg=new JButton("log"); + buttonpanel.add(lg); + lg.addActionListener(this); + div=new JButton("/"); + div.addActionListener(this); + buttonpanel.add(div); + eq=new JButton("="); + buttonpanel.add(eq); + eq.addActionListener(this); + + sin=new JButton("SIN"); + syntpanel.add(sin); + sin.addActionListener(this); + cos=new JButton("COS"); + syntpanel.add(cos); + cos.addActionListener(this); + tan=new JButton("TAN"); + syntpanel.add(tan); + tan.addActionListener(this); + pow2=new JButton("x^2"); + syntpanel.add(pow2); + pow2.addActionListener(this); + pow3=new JButton("x^3"); + syntpanel.add(pow3); + pow3.addActionListener(this); + exp=new JButton("Exp"); + exp.addActionListener(this); + + cont.add("Center",buttonpanel); + cont.add("North",textpanel); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } +class radiohandler implements ItemListener +{ +public void itemStateChanged(ItemEvent ie) + { + AbstractButton button=(AbstractButton)ie.getItem(); + String label=button.getText(); + { + if(label.equals("Standard")) + { + cont.remove(syntpanel); + validate(); + } + if(label.equals("Sceintific")) + { + cont.add("West",syntpanel); + validate(); + } + } + } +} +public void actionPerformed(ActionEvent e) +{ + String s=e.getActionCommand(); + if(s.equals("Exit")) + { + System.exit(0); + } + if(s.equals("1")) + { + if(z==0) + { + jtx.setText(jtx.getText()+"1"); + } + else + { + jtx.setText(""); + jtx.setText(jtx.getText()+"1"); + z=0; + } + } + if(s.equals("2")) + { + if(z==0) + { + jtx.setText(jtx.getText()+"2"); + } + else + { + jtx.setText(""); + jtx.setText(jtx.getText()+"2"); + z=0; + } + } + if(s.equals("3")) + { + if(z==0) + { + jtx.setText(jtx.getText()+"3"); + } + else + { + jtx.setText(""); + jtx.setText(jtx.getText()+"3"); + z=0; + } + } + if(s.equals("4")) + { + if(z==0) + { + jtx.setText(jtx.getText()+"4"); + } + else + { + jtx.setText(""); + jtx.setText(jtx.getText()+"4"); + z=0; + } + } + if(s.equals("5")) + { + if(z==0) + { + jtx.setText(jtx.getText()+"5"); + } + else + { + jtx.setText(""); + jtx.setText(jtx.getText()+"5"); + z=0; + } + } + if(s.equals("6")) + { + if(z==0) + { + jtx.setText(jtx.getText()+"6"); + } + else + { + jtx.setText(""); + jtx.setText(jtx.getText()+"6"); + z=0; + } + } + if(s.equals("7")) + { + if(z==0) + { + jtx.setText(jtx.getText()+"7"); + } + else + { + jtx.setText(""); + jtx.setText(jtx.getText()+"7"); + z=0; + } + } + if(s.equals("8")) + { + if(z==0) + { + jtx.setText(jtx.getText()+"8"); + } + else + { + jtx.setText(""); + jtx.setText(jtx.getText()+"8"); + z=0; + } + } + if(s.equals("9")) + { + if(z==0) + { + jtx.setText(jtx.getText()+"9"); + } + else + { + jtx.setText(""); + jtx.setText(jtx.getText()+"9"); + z=0; + } + } + if(s.equals("0")) + { + if(z==0) + { + jtx.setText(jtx.getText()+"0"); + } + else + { + jtx.setText(""); + jtx.setText(jtx.getText()+"0"); + z=0; + } + } + if(s.equals("AC")) + { + jtx.setText(""); + x=0; + y=0; + z=0; + } + if(s.equals("log")) + { + if(jtx.getText().equals("")) + { + jtx.setText(""); + } + else + { + a=Math.log(Double.parseDouble(jtx.getText())); + jtx.setText(""); + jtx.setText(jtx.getText() + a); + } + } + if(s.equals("1/x")) + { + if(jtx.getText().equals("")) + { + jtx.setText(""); + } + else + { + a=1/Double.parseDouble(jtx.getText()); + jtx.setText(""); + jtx.setText(jtx.getText() + a); + } + } + if(s.equals("Exp")) + { + if(jtx.getText().equals("")) + { + jtx.setText(""); + } + else + { + a=Math.exp(Double.parseDouble(jtx.getText())); + jtx.setText(""); + jtx.setText(jtx.getText() + a); + } + } + if(s.equals("x^2")) + { + if(jtx.getText().equals("")) + { + jtx.setText(""); + } + else + { + a=Math.pow(Double.parseDouble(jtx.getText()),2); + jtx.setText(""); + jtx.setText(jtx.getText() + a); + } + } + if(s.equals("x^3")) + { + if(jtx.getText().equals("")) + { + jtx.setText(""); + } + else + { + a=Math.pow(Double.parseDouble(jtx.getText()),3); + jtx.setText(""); + jtx.setText(jtx.getText() + a); + } + } + if(s.equals("+/-")) + { + if(x==0) + { + jtx.setText("-"+jtx.getText()); + x=1; + } + else + { + jtx.setText(jtx.getText()); + } + } + if(s.equals(".")) + { + if(y==0) + { + jtx.setText(jtx.getText()+"."); + y=1; + } + else + { + jtx.setText(jtx.getText()); + } + } + if(s.equals("+")) + { + if(jtx.getText().equals("")) + { + jtx.setText(""); + temp=0; + ch='+'; + } + else + { + temp=Double.parseDouble(jtx.getText()); + jtx.setText(""); + ch='+'; + y=0; + x=0; + } + jtx.requestFocus(); + } + if(s.equals("-")) + { + if(jtx.getText().equals("")) + { + jtx.setText(""); + temp=0; + ch='-'; + } + else + { + x=0; + y=0; + temp=Double.parseDouble(jtx.getText()); + jtx.setText(""); + ch='-'; + } + jtx.requestFocus(); + } + if(s.equals("/")) + { + if(jtx.getText().equals("")) + { + jtx.setText(""); + temp=1; + ch='/'; + } + else + { + x=0; + y=0; + temp=Double.parseDouble(jtx.getText()); + ch='/'; + jtx.setText(""); + } + jtx.requestFocus(); + } + if(s.equals("*")) + { + if(jtx.getText().equals("")) + { + jtx.setText(""); + temp=1; + ch='*'; + } + else + { + x=0; + y=0; + temp=Double.parseDouble(jtx.getText()); + ch='*'; + jtx.setText(""); + } + jtx.requestFocus(); + } + if(s.equals("MC")) + { + m1=0; + jtx.setText(""); + } + if(s.equals("MR")) + { + jtx.setText(""); + jtx.setText(jtx.getText() + m1); + } + if(s.equals("M+")) + { + if(k==1) + { + m1=Double.parseDouble(jtx.getText()); + k++; + } + else + { + m1+=Double.parseDouble(jtx.getText()); + jtx.setText(""+m1); + } + } + if(s.equals("M-")) + { + if(k==1) + { + m1=Double.parseDouble(jtx.getText()); + k++; + } + else + { + m1-=Double.parseDouble(jtx.getText()); + jtx.setText(""+m1); + } + } + if(s.equals("Sqrt")) + { + if(jtx.getText().equals("")) + { + jtx.setText(""); + } + else + { + a=Math.sqrt(Double.parseDouble(jtx.getText())); + jtx.setText(""); + jtx.setText(jtx.getText() + a); + } + } + if(s.equals("SIN")) + { + if(jtx.getText().equals("")) + { + jtx.setText(""); + } + else + { + a=Math.sin(Double.parseDouble(jtx.getText())); + jtx.setText(""); + jtx.setText(jtx.getText() + a); + } + } + if(s.equals("COS")) + { + if(jtx.getText().equals("")) + { + jtx.setText(""); + } + else + { + a=Math.cos(Double.parseDouble(jtx.getText())); + jtx.setText(""); + jtx.setText(jtx.getText() + a); + } + } + if(s.equals("TAN")) + { + if(jtx.getText().equals("")) + { + jtx.setText(""); + } + else + { + a=Math.tan(Double.parseDouble(jtx.getText())); + jtx.setText(""); + jtx.setText(jtx.getText() + a); + } + } + if(s.equals("=")) + { + if(jtx.getText().equals("")) + { + jtx.setText(""); + } + else + { + temp1 = Double.parseDouble(jtx.getText()); + switch(ch) + { + case '+': + result=temp+temp1; + break; + case '-': + result=temp-temp1; + break; + case '/': + result=temp/temp1; + break; + case '*': + result=temp*temp1; + break; + } + jtx.setText(""); + jtx.setText(jtx.getText() + result); + z=1; + } + } + jtx.requestFocus(); + } +public static void main(String args[]) + { + calculator n=new calculator(); + n.setTitle("CALCULATOR"); + n.setSize(370,250); + n.setResizable(false); + n.setVisible(true); + } +} diff --git a/java/Basics/Calling Windows Runtime Commands.java b/java/Basics/Calling Windows Runtime Commands.java new file mode 100644 index 0000000..8426706 --- /dev/null +++ b/java/Basics/Calling Windows Runtime Commands.java @@ -0,0 +1,12 @@ +Calling Windows Runtime Commands + +import java.io.*; +public class Win +{ +public static void main(String[] Miller) throws IOException +{ + Process process = +Runtime.getRuntime().exec("/C:WINNTsystem32calculator.exe"); + process.waitFor(); +} +} diff --git a/java/Basics/Catching an exception.java b/java/Basics/Catching an exception.java new file mode 100644 index 0000000..ff4e006 --- /dev/null +++ b/java/Basics/Catching an exception.java @@ -0,0 +1,15 @@ +Catching an exception + + + +public class CatchingAnException { + public static void main( String[] args ) { + try { + // this throws a runtime exception, that is a divide by zero + int a = 3 / 0; + } + catch( ArithmeticException aex ) { + aex.printStackTrace(); + } + } +} diff --git a/java/Basics/Check The Equality Of Two Arrays In Java.java b/java/Basics/Check The Equality Of Two Arrays In Java.java new file mode 100644 index 0000000..c9f87d3 --- /dev/null +++ b/java/Basics/Check The Equality Of Two Arrays In Java.java @@ -0,0 +1,27 @@ + public class EqualityOfTwoArrays { + public static void main(String[] args) { + int[] arrayOne = { + 2, 5, 1, 7, 4 + } + ; + int[] arrayTwo = { + 2, 5, 1, 7, 4 + } + ; + boolean equalOrNot = true; + if(arrayOne.length == arrayTwo.length) { + for (int i = 0; i < arrayOne.length; i++) { + if(arrayOne[i] != arrayTwo[i]) { + equalOrNot = false; + } + } + } else { + equalOrNot = false; + } + if (equalOrNot) { + System.out.println("Two Arrays Are Equal"); + } else { + System.out.println("Two Arrays Are Not equal"); + } + } + } \ No newline at end of file diff --git a/java/Basics/Complex.java b/java/Basics/Complex.java new file mode 100644 index 0000000..48b1a83 --- /dev/null +++ b/java/Basics/Complex.java @@ -0,0 +1,60 @@ +package com.jwetherell.algorithms.numbers; + +/** + * A complex number is a number that can be expressed in the form a + bi, where a and b are real numbers and i is the + * imaginary unit, satisfying the equation i2 = −1.[1] In this expression, a is the real part and b is the imaginary + * part of the complex number. If z=a+bi z=a+bi, then Rz=a, Iz=b. + *

+ * http://en.wikipedia.org/wiki/Complex_number + *
+ * @author Mateusz Cianciara + * @author Justin Wetherell + */ +public class Complex { + + public double real; + public double imaginary; + + public Complex() { + this.real = 0.0; + this.imaginary = 0.0; + } + + public Complex(double r, double i) { + this.real = r; + this.imaginary = i; + } + + public Complex multiply(final Complex x) { + final Complex copy = new Complex(this.real, this.imaginary); + copy.real = this.real * x.real - this.imaginary * x.imaginary; + copy.imaginary = this.imaginary * x.real + this.real * x.imaginary; + return copy; + } + + public Complex add(final Complex x) { + final Complex copy = new Complex(this.real, this.imaginary); + copy.real += x.real; + copy.imaginary += x.imaginary; + return copy; + } + + public Complex sub(final Complex x) { + final Complex copy = new Complex(this.real, this.imaginary); + copy.real -= x.real; + copy.imaginary -= x.imaginary; + return copy; + } + + public double abs() { + return Math.sqrt(this.real * this.real + this.imaginary * this.imaginary); + } + + public String toString() { + return "(" + this.real + "," + this.imaginary + ")"; + } + + public static Complex polar(final double rho, final double theta) { + return (new Complex(rho * Math.cos(theta), rho * Math.sin(theta))); + } +} diff --git a/java/Basics/Constants.java b/java/Basics/Constants.java new file mode 100644 index 0000000..6dc7ad3 --- /dev/null +++ b/java/Basics/Constants.java @@ -0,0 +1,24 @@ +Constants + + + +public class Constants { + // define two class-level constants with static final + private static final int MAX_VALUE = 100; + private static final String LOCAL_URL = "http://localhost:8080/"; + + public static void main( String[] args ) { + // define MY_PIE as a local constant + final double MY_PIE = 3.14; + + System.out.println( Constants.MAX_VALUE ); + System.out.println( Constants.LOCAL_URL ); + System.out.println( MY_PIE ); + + // MY_PIE = 3.15 result in an error, because MY_PIE is a constant + } + + public static void execute( final int min, final int max ) { + // min and max cannot be altered within this method + } +} diff --git a/java/Basics/Constructors.java b/java/Basics/Constructors.java new file mode 100644 index 0000000..7e0093e --- /dev/null +++ b/java/Basics/Constructors.java @@ -0,0 +1,36 @@ +Constructors + + + +public class Constructors { + private static final String DEFAULT_MSG = "hey"; + private static final int DEFAULT_AMOUNT = 25; + + private String msg; + private int amount; + + public Constructors( String msg, int amount ) { + // use the 'this' keyword to reference to this object instance + // variables, with out, msg and amount refer to the formal parameters + this.msg = msg; + this.amount = amount; + } + + public Constructors( String msg ) { + // must be first line in a constructor and calls the constructor + // within this class with those formal parameters + this( msg, DEFAULT_AMOUNT ); + } + + public Constructors() { + // must be first line in a constructor and calls the constructor + // within this class with those formal parameters + this( DEFAULT_MSG ); + } + + public static void main( String[] args ) { + // here, we demonstrate how all three constructors + // can be called to construct an object + new Constructors(); + } +} diff --git a/java/Basics/Continue Statements.java b/java/Basics/Continue Statements.java new file mode 100644 index 0000000..eb80d97 --- /dev/null +++ b/java/Basics/Continue Statements.java @@ -0,0 +1,17 @@ +Continue Statements + + + +public class ContinueStatements { + public static void main( String[] args ) { + // when i is 5, got back to loop, test and increment + // in this chase the value 5 is not output + for( int i = 0; i < 10; i++ ) { + if( i == 5 ) { + continue; + } + System.out.println( i ); + } + + } +} diff --git a/java/Basics/Coprimes.java b/java/Basics/Coprimes.java new file mode 100644 index 0000000..0877ce4 --- /dev/null +++ b/java/Basics/Coprimes.java @@ -0,0 +1,42 @@ +package com.jwetherell.algorithms.mathematics; + +/** + * In number theory, two integers a and b are said to be relatively prime, mutually prime, or coprime (also spelled + * co-prime)[1] if the only positive integer that divides both of them is 1. That is, the only common positive factor + * of the two numbers is 1. This is equivalent to their greatest common divisor being 1. + *

+ * http://en.wikipedia.org/wiki/Coprime_integers + *
+ * @author Szymon Stankiewicz + * @author Justin Wetherell + */ +public class Coprimes { + + private Coprimes() { } + + /** + * + * Euler's totient function. Because this function is multiplicative such implementation is possible. + *

+ * Time complexity: O(sqrt(n)) + *

+ * @param n Long integer + * @return number of coprimes smaller or equal to n + */ + public static long getNumberOfCoprimes(long n) { + if(n < 1) + return 0; + long res = 1; + for(int i = 2; i*i <= n; i++) { + int times = 0; + while(n%i == 0) { + res *= (times > 0 ? i : i-1); + n /= i; + times++; + } + } + if(n > 1) + res *= n-1; + return res; + } +} diff --git a/java/Basics/Demonstrating the runnable interface.java b/java/Basics/Demonstrating the runnable interface.java new file mode 100644 index 0000000..5376adf --- /dev/null +++ b/java/Basics/Demonstrating the runnable interface.java @@ -0,0 +1,118 @@ +Demonstrating the runnable interface + + import java.awt.*; + import java.awt.event.*; + import javax.swing.*; + + public class RandomCharacters extends JApplet implements Runnable, ActionListener + { + private String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private JLabel outputs[]; + private JCheckBox checkboxes[]; + private final static int SIZE = 3; + + private Thread threads[]; + private boolean suspended[]; + + public void init() + { + outputs = new JLabel[ SIZE ]; + checkboxes = new JCheckBox[ SIZE ]; + threads = new Thread[ SIZE ]; + suspended = new boolean[ SIZE ]; + + Container c = getContentPane(); + c.setLayout( new GridLayout( SIZE, 2, 5, 5 ) ); + + for ( int i = 0; i < SIZE; i++ ) + { + outputs[ i ] = new JLabel(); + outputs[ i ].setBackground( Color.green ); + outputs[ i ].setOpaque( true ); + c.add( outputs[ i ] ); + + checkboxes[ i ] = new JCheckBox( "Suspended" ); + checkboxes[ i ].addActionListener( this ); + c.add( checkboxes[ i ] ); + } + } + + public void start() + { + // create threads and start every time start is called + for ( int i = 0; i < threads.length; i++ ) + { + threads[ i ] = new Thread( this, "Thread " + (i + 1) ); + threads[ i ].start(); + } + } + + public void run() + { + Thread currentThread = Thread.currentThread(); + int index = getIndex( currentThread ); + char displayChar; + + while ( threads[ index ] == currentThread ) + { + // sleep from 0 to 1 second + try + { + Thread.sleep( (int) ( Math.random() * 1000 ) ); + + synchronized( this ) + { + while ( suspended[ index ] && threads[ index ] == currentThread ) + wait(); + } + } + catch ( InterruptedException e ) + { + System.err.println( "sleep interrupted" ); + } + + displayChar = alphabet.charAt( (int) ( Math.random() * 26 ) ); + outputs[ index ].setText( currentThread.getName() + + ": " + displayChar ); + } + + System.err.println( currentThread.getName() + " terminating" ); + } + + private int getIndex( Thread current ) + { + for ( int i = 0; i < threads.length; i++ ) + if ( current == threads[ i ] ) + return i; + + return -1; + } + + public synchronized void stop() + { + // stop threads every time stop is called + // as the user browses another Web page + for ( int i = 0; i < threads.length; i++ ) + threads[ i ] = null; + + notifyAll(); + } + + public synchronized void actionPerformed( ActionEvent e ) + { + for ( int i = 0; i < checkboxes.length; i++ ) + { + if ( e.getSource() == checkboxes[ i ] ) + { + suspended[ i ] = !suspended[ i ]; + + outputs[ i ].setBackground( !suspended[ i ] ? Color.green : Color.red ); + + if ( !suspended[ i ] ) + notify(); + + return; + } + } + } + } diff --git a/java/Basics/Deposit Account.java b/java/Basics/Deposit Account.java new file mode 100644 index 0000000..754eff3 --- /dev/null +++ b/java/Basics/Deposit Account.java @@ -0,0 +1,32 @@ +Deposit Account + +package com.ack.learning.examples.account; + +public class DepositAccount { + private double amount; + private String name; + + public DepositAccount() { + } + + public DepositAccount( String theName, double theAmount ) { + name = theName; + amount = theAmount; + } + + public double getAmount() { + return amount; + } + + public String getName() { + return name; + } + + public static void main( String[] args ) { + DepositAccount hsbc = new DepositAccount( "barry", 345.45 ); + DepositAccount halifax = new DepositAccount( "hector", 45.76 ); + + System.out.println( hsbc.getName() ); + System.out.println( halifax.getName() ); + } +} diff --git a/java/Basics/Distance.java b/java/Basics/Distance.java new file mode 100644 index 0000000..ef8e47e --- /dev/null +++ b/java/Basics/Distance.java @@ -0,0 +1,31 @@ +package com.jwetherell.algorithms.mathematics; + +public class Distance { + + private Distance() { } + + /* + * Chess distance + */ + public static final long chebyshevDistance(long[] point1, long[] point2) { + long x1 = point1[0]; + long y1 = point1[1]; + long x2 = point2[0]; + long y2 = point2[1]; + return Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)); + } + + public static final double squaredDistance(double x1, double y1, double x2, double y2) { + double x = x1 - x2; + double y = y1 - y2; + double sqr = (x * x) + (y * y); + return sqr; + } + + public static final double euclideanDistance(double x1, double y1, double x2, double y2) { + double x = Math.pow((x1 - x2), 2); + double y = Math.pow((y1 - y2), 2); + double sqrt = Math.sqrt(x + y); + return sqrt; + } +} diff --git a/java/Basics/Division.java b/java/Basics/Division.java new file mode 100644 index 0000000..c133f74 --- /dev/null +++ b/java/Basics/Division.java @@ -0,0 +1,87 @@ +package com.jwetherell.algorithms.mathematics; + +public class Division { + + public static final long division(int a, int b) { + long result = ((long) a) / ((long) b); + return result; + } + + public static final long divisionUsingLoop(int a, int b) { + int absA = Math.abs(a); + int absB = Math.abs(b); + + long temp = absA; + long result = 0; + while (temp >= 0) { + temp -= absB; + if (temp >= 0) + result++; + } + return (a > 0 && b > 0 || a < 0 && b < 0) ? result : -result; + } + + public static final long divisionUsingRecursion(int a, int b) { + int absA = Math.abs(a); + int absB = Math.abs(b); + + long result = 1; + int diff = absA - absB; + if (diff > 0 && diff <= 1) { + return result; + } else if (diff < 0) { + return 0; + } + + result += divisionUsingRecursion(diff, absB); + return (a > 0 && b > 0 || a < 0 && b < 0) ? result : -result; + } + + public static final long divisionUsingMultiplication(int a, int b) { + int absA = Math.abs(a); + int absB = Math.abs(b); + + int temp = absB; + int counter = 0; + while (temp <= absA) { + temp = temp << 1; + counter++; + } + absA -= absB << (counter - 1); + long result = (long) Math.pow(2, counter - 1); + if (absB <= absA) + result += divisionUsingMultiplication(absA, absB); + return (a > 0 && b > 0 || a < 0 && b < 0) ? result : -result; + } + + public static final long divisionUsingShift(int a, int b) { + int absA = Math.abs(a); + int absB = Math.abs(b); + int tempA, tempB, counter; + + long result = 0L; + while (absA >= absB) { + tempA = absA >> 1; // Right shift "a" + tempB = absB; + counter = 1; + while (tempA >= tempB) { // Double "tempB" until it's larger than + // "tempA" + tempB <<= 1; + counter <<= 1; // Double the counter + } + absA -= tempB; // Subtract "tempB" from "a" + result += counter; // Add counter (2^number of left shifts) + } + return (a > 0 && b > 0 || a < 0 && b < 0) ? result : -result; + } + + public static final long divisionUsingLogs(int a, int b) { + long absA = Math.abs(a); + long absB = Math.abs(b); + double logBase10A = Math.log10(absA); + double logBase10B = Math.log10(absB); + double powOf10 = Math.pow(10, (logBase10A - logBase10B)); + long result = (long) Math.floor(powOf10); + return (a > 0 && b > 0 || a < 0 && b < 0) ? result : -result; + } +} diff --git a/java/Basics/Factorial (Java).java b/java/Basics/Factorial (Java).java new file mode 100644 index 0000000..db8abc1 --- /dev/null +++ b/java/Basics/Factorial (Java).java @@ -0,0 +1,13 @@ +class FactorialExample +{ + public static void main(String args[]) + { + int i,fact=1; + int number=5;//It is the number to calculate factorial + for(i=1; i<=number; i++) + { + fact=fact*i; + } + System.out.println("Factorial of "+number+" is: "+fact); + } +} \ No newline at end of file diff --git a/java/Basics/FastFourierTransform.java b/java/Basics/FastFourierTransform.java new file mode 100644 index 0000000..93dc412 --- /dev/null +++ b/java/Basics/FastFourierTransform.java @@ -0,0 +1,52 @@ +package com.jwetherell.algorithms.mathematics; + +import com.jwetherell.algorithms.numbers.Complex; + +/** + * A fast Fourier transform (FFT) algorithm computes the discrete Fourier transform (DFT) of a sequence, or its inverse. + * Fourier analysis converts a signal from its original domain (often time or space) to a representation in the frequency + * domain and vice versa. An FFT rapidly computes such transformations by factorizing the DFT matrix into a product of + * sparse (mostly zero) factors. + *

+ * http://en.wikipedia.org/wiki/Fast_Fourier_transform + *
+ * @author Mateusz Cianciara + * @author Justin Wetherell + */ +public class FastFourierTransform { + + private FastFourierTransform() { } + + /** + * The Cooley–Tukey algorithm, named after J.W. Cooley and John Tukey, is the most common fast Fourier transform + * (FFT) algorithm. It re-expresses the discrete Fourier transform (DFT) of an arbitrary composite size N = N1N2 + * in terms of N1 smaller DFTs of sizes N2, recursively, to reduce the computation time to O(N log N) for highly + * composite N (smooth numbers). + *

+ * http://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm + *
+ * @param coefficients size must be power of 2 + */ + public static void cooleyTukeyFFT(Complex[] coefficients) { + final int size = coefficients.length; + if (size <= 1) + return; + + final Complex[] even = new Complex[size / 2]; + final Complex[] odd = new Complex[size / 2]; + for (int i = 0; i < size; i++) { + if (i % 2 == 0) { + even[i / 2] = coefficients[i]; + } else { + odd[(i - 1) / 2] = coefficients[i]; + } + } + cooleyTukeyFFT(even); + cooleyTukeyFFT(odd); + for (int k = 0; k < size / 2; k++) { + Complex t = Complex.polar(1.0, -2 * Math.PI * k / size).multiply(odd[k]); + coefficients[k] = even[k].add(t); + coefficients[k + size / 2] = even[k].sub(t); + } + } +} diff --git a/java/Basics/Fibonacci (Java).java b/java/Basics/Fibonacci (Java).java new file mode 100644 index 0000000..d58dbec --- /dev/null +++ b/java/Basics/Fibonacci (Java).java @@ -0,0 +1,15 @@ +class Fibonacci +{ + public static void main(String args[]) + { + int n1=0,n2=1,n3,i,count=10; + System.out.print(n1+" "+n2);//printing 0 and 1 + for(i=2; i + * + * https://en.wikipedia.org/wiki/Fibonacci_number + *
+ * @author Justin Wetherell + */ +public class FibonacciSequence { + + private static final double INVERSE_SQUARE_ROOT_OF_5 = 1 / Math.sqrt(5); // Inverse of the square root of 5 + private static final double PHI = (1 + Math.sqrt(5)) / 2; // Golden ratio + + private FibonacciSequence() {} + + public static final long fibonacciSequenceUsingLoop(int n) { + final long[] array = new long[n + 1]; + int counter = 0; + while (counter <= n) { + long r = 0; + if (counter > 1) { + r = array[counter - 1] + array[counter - 2]; + } else if (counter == 1) { + r = 1; + } + // If r goes below zero then we have run out of bits in the long + if (r < 0) + throw new IllegalArgumentException("Run out of bits in long, n="+n); + array[counter] = r; + counter++; + } + + return array[n]; + } + + /** + * Recursion with memoization + */ + public static final long fibonacciSequenceUsingRecursion(int n) { + // Using the array to store values already computed + final long[] array = new long[n + 1]; + return fibonacciSequenceUsingRecursion(array,n); + } + + private static final long fibonacciSequenceUsingRecursion(long[] array, int n) { + if (n == 0 || n == 1) + return n; + + // If array already has a value then it has previously been computed + if (array[n] != 0) + return array[n]; + + final String exception = "Run out of bits in long, n="+n; + + final long r1 = fibonacciSequenceUsingRecursion(array, (n - 1)); + array[n-1] = r1; // memoization + // If r1 goes below zero then we have run out of bits in the long + if (r1 < 0) + throw new IllegalArgumentException(exception); + + final long r2 = fibonacciSequenceUsingRecursion(array, (n - 2)); + array[n-2] = r2; // memoization + // If r2 goes below zero then we have run out of bits in the long + if (r2 < 0) + throw new IllegalArgumentException(exception); + + final long r = r1 + r2; + // If r goes below zero then we have run out of bits in the long + if (r < 0) + throw new IllegalArgumentException("Run out of bits in long, n="+n); + + array[n] = r; // memoization + + return r; + } + + public static final long fibonacciSequenceUsingMatrixMultiplication(int n) { + // m = [ 1 , 1 ] + // [ 1 , 0 ] + final long[][] matrix = new long[2][2]; + matrix[0][0] = 1; + matrix[0][1] = 1; + matrix[1][0] = 1; + matrix[1][1] = 0; + + long[][] temp = new long[2][2]; + temp[0][0] = 1; + temp[0][1] = 1; + temp[1][0] = 1; + temp[1][1] = 0; + + int counter = n; + while (counter > 0) { + temp = multiplyMatrices(matrix, temp); + // Subtract an additional 1 the first time in the loop because the + // first multiplication is actually n -= 2 since it multiplying two matrices + counter -= (counter == n) ? 2 : 1; + } + final long r = temp[0][1]; + // If r goes below zero then we have run out of bits in the long + if (r < 0) + throw new IllegalArgumentException("Run out of bits in long, n="+n); + return r; + } + + private static final long[][] multiplyMatrices(long[][] A, long[][] B) { + final long a = A[0][0]; + final long b = A[0][1]; + final long c = A[1][0]; + final long d = A[1][1]; + + final long e = B[0][0]; + final long f = B[0][1]; + final long g = B[1][0]; + final long h = B[1][1]; + + B[0][0] = a * e + b * g; + B[0][1] = a * f + b * h; + B[1][0] = c * e + d * g; + B[1][1] = c * f + d * h; + + return B; + } + + public static final long fibonacciSequenceUsingBinetsFormula(int n) { + final long r = (long) Math.floor(Math.pow(PHI, n) * INVERSE_SQUARE_ROOT_OF_5 + 0.5); + // If r hits max value then we have run out of bits in the long + if (r == Long.MAX_VALUE) + throw new IllegalArgumentException("Run out of bits in long, n="+n); + return r; + } +} diff --git a/java/Basics/For Loops.java b/java/Basics/For Loops.java new file mode 100644 index 0000000..03d201d --- /dev/null +++ b/java/Basics/For Loops.java @@ -0,0 +1,26 @@ +For Loops + + + +public class ForLoops { + public static void main( String[] args ) { + // simple for loop + System.out.println( "loop #1" ); + for( int i = 0; i < 10; i++ ) { + System.out.println( i ); + } + + // loop with multiple iteration constants + System.out.println( "loop #2" ); + for( int i = 1,j = 2; i < 10 && j < 5; i += 2, j-- ) { + System.out.println( j ); + } + + // infinite loop + System.out.println( "infinite loop #3" ); + for( ; ; ) { + // but we are going to break out of it + break; + } + } +} diff --git a/java/Basics/GetTheCurrentTime.java b/java/Basics/GetTheCurrentTime.java new file mode 100644 index 0000000..8a12c2d --- /dev/null +++ b/java/Basics/GetTheCurrentTime.java @@ -0,0 +1,20 @@ +GetTheCurrentTime + +package com.ack.j2se.date; + +import java.util.Calendar; +import java.util.Date; + +public class GetTheCurrentTime { + public static void main( String[] args ) { + // one way + long currentTimeInMillis = System.currentTimeMillis(); + Date today = new Date( currentTimeInMillis ); + System.out.println( today ); + + // another way + Calendar cal = Calendar.getInstance(); + today = cal.getTime(); + System.out.println( today ); + } +} diff --git a/java/Basics/GreatestCommonDivisor.java b/java/Basics/GreatestCommonDivisor.java new file mode 100644 index 0000000..f12889e --- /dev/null +++ b/java/Basics/GreatestCommonDivisor.java @@ -0,0 +1,59 @@ +package com.jwetherell.algorithms.mathematics; + +/** + * In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not + * zero, is the largest positive integer that is a divisor of both numbers. + *

+ * http://en.wikipedia.org/wiki/Greatest_common_divisor + *
+ * @author Szymon Stankiewicz + * @author Justin Wetherell + */ +public class GreatestCommonDivisor { + + /** + * Calculate greatest common divisor of two numbers using recursion. + *

+ * Time complexity O(log(a+b)) + *
+ * @param a Long integer + * @param b Long integer + * @return greatest common divisor of a and b + */ + public static long gcdUsingRecursion(long a, long b) { + a = Math.abs(a); + b = Math.abs(b); + return a == 0 ? b : gcdUsingRecursion(b%a, a); + } + + /** + * A much more efficient method is the Euclidean algorithm, which uses a division algorithm such as long division + * in combination with the observation that the gcd of two numbers also divides their difference. + *

+ * http://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid.27s_algorithm + */ + public static final long gcdUsingEuclides(long x, long y) { + long greater = x; + long smaller = y; + if (y > x) { + greater = y; + smaller = x; + } + + long result = 0; + while (true) { + if (smaller == greater) { + result = smaller; // smaller == greater + break; + } + + greater -= smaller; + if (smaller > greater) { + long temp = smaller; + smaller = greater; + greater = temp; + } + } + return result; + } +} diff --git a/java/Basics/Hanoi Algorithm Recursion.java b/java/Basics/Hanoi Algorithm Recursion.java new file mode 100644 index 0000000..546cb4f --- /dev/null +++ b/java/Basics/Hanoi Algorithm Recursion.java @@ -0,0 +1,23 @@ +Hanoi Algorithm Recursion + + + + +public class HanoiAlgorithmRecursion { + public static void movetower( int height, int fromT, int toT, int usingT ) { + if( height > 0 ) { + movetower( height - 1, fromT, usingT, toT ); + moveDisk( fromT, toT ); + movetower( height - 1, usingT, toT, fromT ); + } + } + + public static void moveDisk( int takeoff, int puton ) { + System.out.println( takeoff + "->" + puton ); + } + + public static void main( String argv[] ) { + int numberOfDisks = 3; + movetower( numberOfDisks, 1, 3, 2 ); + } +} diff --git a/java/Basics/Horoscope.java b/java/Basics/Horoscope.java new file mode 100644 index 0000000..a3a92bd --- /dev/null +++ b/java/Basics/Horoscope.java @@ -0,0 +1,73 @@ +Horoscope + +import javax.swing.*; +import java.awt.event.*; +import java.awt.*; + +public class Factorial extends JFrame + { + private JTextField txtNum; + private JLabel lblNum, lblRes; + private JButton btnCompute; + + public static int ComputeFactorial(int number) + { + int n = number-1; + do + { + number = number*n; + n--; + }while(n>=1); + return number; + } + + public Factorial() + { + super("GUI Factorial"); + Container c = getContentPane(); + c.setLayout(new FlowLayout()); + lblNum = new JLabel("Enter an integer: "); + txtNum = new JTextField(10); + lblRes = new JLabel(); + btnCompute = new JButton("Compute"); + + btnCompute.addActionListener + ( + new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + String str = txtNum.getText(); + int tmp = Integer.parseInt(str); + tmp = ComputeFactorial(tmp); + lblRes.setText("The factorial of "+str+" is "+tmp); + } + } + ); + + c.add(lblNum); + c.add(txtNum); + c.add(btnCompute); + c.add(lblRes); + setSize(200,150); + show(); + } + + public static void main(String args[]) + { + Factorial app = new Factorial(); + app.setResizable(false); + app.setLocation(400,200); + app.addWindowListener + ( + new WindowAdapter() + { + public void windowClosing(WindowEvent e) + { + System.exit(0); + } + } + ); + } + +} diff --git a/java/Basics/How to add time(Days, years , seconds) to Date.java b/java/Basics/How to add time(Days, years , seconds) to Date.java new file mode 100644 index 0000000..94f6f7f --- /dev/null +++ b/java/Basics/How to add time(Days, years , seconds) to Date.java @@ -0,0 +1,15 @@ + import java.util.*; + public class Main { + public static void main(String[] args) throws Exception { + Date d1 = new Date(); + Calendar cl = Calendar. getInstance(); + cl.setTime(d1); + System.out.println("today is " + d1.toString()); + cl. add(Calendar.MONTH, 1); + System.out.println("date after a month will be " + cl.getTime().toString() ); + cl. add(Calendar.HOUR, 70); + System.out.println("date after 7 hrs will be " + cl.getTime().toString() ); + cl. add(Calendar.YEAR, 3); + System.out.println("date after 3 years will be " + cl.getTime().toString() ); + } + } \ No newline at end of file diff --git a/java/Basics/How to change(set) or Get the last modification time of a file in java .java b/java/Basics/How to change(set) or Get the last modification time of a file in java .java new file mode 100644 index 0000000..98d9762 --- /dev/null +++ b/java/Basics/How to change(set) or Get the last modification time of a file in java .java @@ -0,0 +1,11 @@ + import java.io.File; + import java.util.Date; + + public class Main { + public static void main(String[] args) { + File file = new File("Main.java"); + Long lastModified = file.lastModified(); + Date date = new Date(lastModified); + System.out.println(date); + } + } \ No newline at end of file diff --git a/java/Basics/How to compare two strings.java b/java/Basics/How to compare two strings.java new file mode 100644 index 0000000..ced522c --- /dev/null +++ b/java/Basics/How to compare two strings.java @@ -0,0 +1,10 @@ + public class StringCompareEmp { + public static void main(String args[]) { + String str = "Hello World"; + String anotherString = "hello world"; + Object objStr = str; + System.out.println( str.compareTo(anotherString) ); + System.out.println( str.compareToIgnoreCase(anotherString) ); + System.out.println( str.compareTo(objStr.toString())); + } + } \ No newline at end of file diff --git a/java/Basics/How to convert a string totally into upper case.java b/java/Basics/How to convert a string totally into upper case.java new file mode 100644 index 0000000..2f83a6e --- /dev/null +++ b/java/Basics/How to convert a string totally into upper case.java @@ -0,0 +1,8 @@ + public class StringToUpperCaseEmp { + public static void main(String[] args) { + String str = "string abc touppercase "; + String strUpper = str.toUpperCase(); + System.out.println("Original String: " + str); + System.out.println("String changed to upper case: "+ strUpper); + } + } \ No newline at end of file diff --git a/java/Basics/How to display date in different formats .java b/java/Basics/How to display date in different formats .java new file mode 100644 index 0000000..47e815c --- /dev/null +++ b/java/Basics/How to display date in different formats .java @@ -0,0 +1,16 @@ + import java.text.*; + import java.util.*; + public class Main { + public static void main(String[] args) { + Date dt = new Date(1000000000000L); + DateFormat[] dtformat = new DateFormat[6]; + dtformat[0] = DateFormat.getInstance(); + dtformat[1] = DateFormat.getDateInstance(); + dtformat[2] = DateFormat.getDateInstance(DateFormat.MEDIUM); + dtformat[3] = DateFormat.getDateInstance(DateFormat.FULL); + dtformat[4] = DateFormat.getDateInstance(DateFormat.LONG); + dtformat[5] = DateFormat.getDateInstance(DateFormat.SHORT); + for (DateFormat dateform : dtformat) + System.out.println(dateform.format(dt)); + } + } \ No newline at end of file diff --git a/java/Basics/How to display name of a month in (MMM) format.java b/java/Basics/How to display name of a month in (MMM) format.java new file mode 100644 index 0000000..c421859 --- /dev/null +++ b/java/Basics/How to display name of a month in (MMM) format.java @@ -0,0 +1,11 @@ + import java.util.Calendar; + import java.util.Formatter; + public class MainClass { + public static void main(String args[]) { + Formatter fmt = new Formatter(); + Calendar cal = Calendar.getInstance(); + fmt = new Formatter(); + fmt.format("%tB %tb %tm", cal, cal, cal); + System.out.println(fmt); + } + } \ No newline at end of file diff --git a/java/Basics/How to display name of the weekdays.java b/java/Basics/How to display name of the weekdays.java new file mode 100644 index 0000000..2dfa4e3 --- /dev/null +++ b/java/Basics/How to display name of the weekdays.java @@ -0,0 +1,11 @@ + import java.text.SimpleDateFormat; + import java.text.DateFormatSymbols; + public class Main { + public static void main(String[] args) { + String[] weekdays = new DateFormatSymbols().getWeekdays(); + for (int i = 2; i < (weekdays.length-1); i++) { + String weekday = weekdays[i]; + System.out.println("weekday = " + weekday); + } + } + } \ No newline at end of file diff --git a/java/Basics/How to display time in different countrys format.java b/java/Basics/How to display time in different countrys format.java new file mode 100644 index 0000000..48a7aad --- /dev/null +++ b/java/Basics/How to display time in different countrys format.java @@ -0,0 +1,11 @@ + import java.text.DateFormat; + import java.util.*; + public class Main { + public static void main(String[] args) throws Exception { + Date d1 = new Date(); + System.out.println("today is "+ d1.toString()); + Locale locItalian = new Locale("it","ch"); + DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, locItalian); + System.out.println("today is in Italian Language in Switzerland Format : "+ df.format(d1)); + } + } \ No newline at end of file diff --git a/java/Basics/How to find which week of the year, month.java b/java/Basics/How to find which week of the year, month.java new file mode 100644 index 0000000..1d484a1 --- /dev/null +++ b/java/Basics/How to find which week of the year, month.java @@ -0,0 +1,11 @@ + import java.util.*; + public class Main { + public static void main(String[] args) throws Exception { + Date d1 = new Date(); + Calendar cl = Calendar. getInstance(); + cl.setTime(d1); + System.out.println("today is "+ cl.WEEK_OF_YEAR+ " week of the year"); + System.out.println("today is a "+cl.DAY_OF_MONTH + "month of the year"); + System.out.println("today is a "+cl.WEEK_OF_MONTH +"week of the month"); + } + } \ No newline at end of file diff --git a/java/Basics/How to format seconds.java b/java/Basics/How to format seconds.java new file mode 100644 index 0000000..24975fb --- /dev/null +++ b/java/Basics/How to format seconds.java @@ -0,0 +1,9 @@ + import java.text.SimpleDateFormat; + import java.util.Date; + public class Main { + public static void main(String[] args) { + Date date = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat("ss"); + System.out.println("seconds in ss format : "+ sdf.format(date)); + } + } \ No newline at end of file diff --git a/java/Basics/How to format time in 24 hour format.java b/java/Basics/How to format time in 24 hour format.java new file mode 100644 index 0000000..aa5743e --- /dev/null +++ b/java/Basics/How to format time in 24 hour format.java @@ -0,0 +1,9 @@ + import java.text.SimpleDateFormat; + import java.util.Date; + public class Main { + public static void main(String[] args) { + Date date = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat("h"); + System.out.println("hour in h format : "+ sdf.format(date)); + } + } \ No newline at end of file diff --git a/java/Basics/How to format time in AM-PM format.java b/java/Basics/How to format time in AM-PM format.java new file mode 100644 index 0000000..d5442a8 --- /dev/null +++ b/java/Basics/How to format time in AM-PM format.java @@ -0,0 +1,10 @@ + import java.text.SimpleDateFormat; + import java.util.Date; + public class Main { + public static void main(String[] args) { + Date date = new Date(); + String strDateFormat = "HH:mm:ss a"; + SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat); + System.out.println(sdf.format(date)); + } + } \ No newline at end of file diff --git a/java/Basics/How to get a files size in bytes.java b/java/Basics/How to get a files size in bytes.java new file mode 100644 index 0000000..cf73c54 --- /dev/null +++ b/java/Basics/How to get a files size in bytes.java @@ -0,0 +1,16 @@ + import java.io.File; + + public class Main { + public static long getFileSize(String filename) { + File file = new File(filename); + if (!file.exists() || !file.isFile()) { + System.out.println("File doesn\'t exist"); + return -1; + } + return file.length(); + } + public static void main(String[] args) { + long size = getFileSize("c:/java.txt"); + System.out.println("Filesize in bytes: " + size); + } + } \ No newline at end of file diff --git a/java/Basics/How to get the maximum element from a vector.java b/java/Basics/How to get the maximum element from a vector.java new file mode 100644 index 0000000..dc7dec5 --- /dev/null +++ b/java/Basics/How to get the maximum element from a vector.java @@ -0,0 +1,14 @@ + import java.util.Collections; + import java.util.Vector; + public class Main { + public static void main(String[] args) { + Vector v = new Vector(); + v.add(new Double("3.4324")); + v.add(new Double("3.3532")); + v.add(new Double("3.342")); + v.add(new Double("3.349")); + v.add(new Double("2.3")); + Object obj = Collections.max(v); + System.out.println("The max element is:"+obj); + } + } \ No newline at end of file diff --git a/java/Basics/How to make a file read-only.java b/java/Basics/How to make a file read-only.java new file mode 100644 index 0000000..62a308a --- /dev/null +++ b/java/Basics/How to make a file read-only.java @@ -0,0 +1,9 @@ + import java.io.File; + + public class Main { + public static void main(String[] args) { + File file = new File("C:/java.txt"); + System.out.println(file.setReadOnly()); + System.out.println(file.canWrite()); + } + } \ No newline at end of file diff --git a/java/Basics/How to match regions in strings.java b/java/Basics/How to match regions in strings.java new file mode 100644 index 0000000..cb115dd --- /dev/null +++ b/java/Basics/How to match regions in strings.java @@ -0,0 +1,9 @@ + public class StringRegionMatch { + public static void main(String[] args) { + String first_str = "Welcome to Microsoft"; + String second_str = "I work with Microsoft"; + boolean match = first_str. + regionMatches(11, second_str, 12, 9); + System.out.println("first_str[11 -19] == "+ "second_str[12 - 21]:-"+ match); + } + } \ No newline at end of file diff --git a/java/Basics/How to remove a particular character from a string.java b/java/Basics/How to remove a particular character from a string.java new file mode 100644 index 0000000..462c35b --- /dev/null +++ b/java/Basics/How to remove a particular character from a string.java @@ -0,0 +1,9 @@ + public class Main { + public static void main(String args[]) { + String str = "this is Scanftree;; + System.out.println(removeCharAt(str, 3)); + } + public static String removeCharAt(String s, int pos) { + return s.substring(0, pos) + s.substring(pos + 1); + } + } \ No newline at end of file diff --git a/java/Basics/How to replace a substring inside a string by another one.java b/java/Basics/How to replace a substring inside a string by another one.java new file mode 100644 index 0000000..0e31fc4 --- /dev/null +++ b/java/Basics/How to replace a substring inside a string by another one.java @@ -0,0 +1,8 @@ + public class StringReplaceEmp { + public static void main(String args[]) { + String str="Hello World"; + System.out.println( str.replace( 'H','W' ) ); + System.out.println( str.replaceFirst("He", "Wa") ); + System.out.println( str.replaceAll("He", "Ha") ); + } + } \ No newline at end of file diff --git a/java/Basics/How to reverse a String.java b/java/Basics/How to reverse a String.java new file mode 100644 index 0000000..79f3141 --- /dev/null +++ b/java/Basics/How to reverse a String.java @@ -0,0 +1,8 @@ + public class StringReverseExample { + public static void main(String[] args) { + String string="abcdef"; + String reverse = new StringBuffer(string).reverse().toString(); + System.out.println("\nString before reverse:"+string); + System.out.println("String after reverse:"+reverse); + } + } \ No newline at end of file diff --git a/java/Basics/How to reverse a string using stack.java b/java/Basics/How to reverse a string using stack.java new file mode 100644 index 0000000..a13db54 --- /dev/null +++ b/java/Basics/How to reverse a string using stack.java @@ -0,0 +1,53 @@ + import java.io.IOException; + public class StringReverserThroughStack { + private String input; + private String output; + public StringReverserThroughStack(String in) { + input = in; + } + public String doRev() { + int stackSize = input.length(); + Stack theStack = new Stack(stackSize); + for (int i = 0; i < input.length(); i++) { + char ch = input.charAt(i); + theStack.push(ch); + } + output = ""; + while (!theStack.isEmpty()) { + char ch = theStack.pop(); + output = output + ch; + } + return output; + } + public static void main(String[] args) + throws IOException { + String input = "Java Source and Support"; + String output; + StringReverserThroughStack theReverser = + new StringReverserThroughStack(input); + output = theReverser.doRev(); + System.out.println("Reversed: " + output); + } + class Stack { + private int maxSize; + private char[] stackArray; + private int top; + public Stack(int max) { + maxSize = max; + stackArray = new char[maxSize]; + top = -1; + } + public void push(char j) { + stackArray[++top] = j; + } + public char pop() { + return stackArray[top--]; + } + public char peek() { + return stackArray[top]; + } + public boolean isEmpty() { + return (top == -1); + } + } + } \ No newline at end of file diff --git a/java/Basics/How to roll through hours & months.java b/java/Basics/How to roll through hours & months.java new file mode 100644 index 0000000..d384ff9 --- /dev/null +++ b/java/Basics/How to roll through hours & months.java @@ -0,0 +1,13 @@ + import java.util.*; + public class Main { + public static void main(String[] args) throws Exception { + Date d1 = new Date(); + Calendar cl = Calendar. getInstance(); + cl.setTime(d1); + System.out.println("today is "+ d1.toString()); + cl. roll(Calendar.MONTH, 100); + System.out.println("date after a month will be " + cl.getTime().toString() ); + cl. roll(Calendar.HOUR, 70); + System.out.println("date after 7 hrs will be "+ cl.getTime().toString() ); + } + } \ No newline at end of file diff --git a/java/Basics/How to search a word inside a string.java b/java/Basics/How to search a word inside a string.java new file mode 100644 index 0000000..1d058ff --- /dev/null +++ b/java/Basics/How to search a word inside a string.java @@ -0,0 +1,11 @@ + public class SearchStringEmp { + public static void main(String[] args) { + String strOrig = "Hello readers"; + int intIndex = strOrig.indexOf("Hello"); + if(intIndex == - 1) { + System.out.println("Hello not found"); + } else { + System.out.println("Found Hello at index "+ intIndex); + } + } + } \ No newline at end of file diff --git a/java/Basics/How to search last occurance of a substring inside a substring.java b/java/Basics/How to search last occurance of a substring inside a substring.java new file mode 100644 index 0000000..30a3f9b --- /dev/null +++ b/java/Basics/How to search last occurance of a substring inside a substring.java @@ -0,0 +1,12 @@ + public class SearchlastString { + public static void main(String[] args) { + String strOrig = "Hello world ,Hello Reader"; + int lastIndex = strOrig.lastIndexOf("Hello"); + if(lastIndex == - 1) { + System.out.println("Hello not found"); + } else { + System.out.println("Last occurrence of Hello + is at index "+ lastIndex); + } + } + } \ No newline at end of file diff --git a/java/Basics/How to split a string into a number of substrings.java b/java/Basics/How to split a string into a number of substrings.java new file mode 100644 index 0000000..e2da9c4 --- /dev/null +++ b/java/Basics/How to split a string into a number of substrings.java @@ -0,0 +1,23 @@ + public class JavaStringSplitEmp { + public static void main(String args[]) { + String str = "jan-feb-march"; + String[] temp; + String delimeter = "-"; + temp = str.split(delimeter); + for (int i =0; i < temp.length ; i++) { + System.out.println(temp[i]); + System.out.println(""); + str = "jan.feb.march"; + delimeter = "\\."; + temp = str.split(delimeter); + } + for (int i =0; i < temp.length ; i++) { + System.out.println(temp[i]); + System.out.println(""); + temp = str.split(delimeter,2); + for (int j =0; j < temp.length ; j++) { + System.out.println(temp[i]); + } + } + } + } \ No newline at end of file diff --git a/java/Basics/How to swap two elements in a vector.java b/java/Basics/How to swap two elements in a vector.java new file mode 100644 index 0000000..f4be559 --- /dev/null +++ b/java/Basics/How to swap two elements in a vector.java @@ -0,0 +1,16 @@ + import java.util.Collections; + import java.util.Vector; + public class Main { + public static void main(String[] args) { + Vector v = new Vector(); + v.add("1"); + v.add("2"); + v.add("3"); + v.add("4"); + v.add("5"); + System.out.println(v); + Collections.swap(v, 0, 4); + System.out.println("After swapping"); + System.out.println(v); + } + } \ No newline at end of file diff --git a/java/Basics/How to swap two numbers without using temporary variable.java b/java/Basics/How to swap two numbers without using temporary variable.java new file mode 100644 index 0000000..6e4f4f2 --- /dev/null +++ b/java/Basics/How to swap two numbers without using temporary variable.java @@ -0,0 +1,16 @@ + package com.scanftree.algos; + public class MySwapingTwoNumbers { + public static void main(String a[]) { + int x = 10; + int y = 20; + System.out.println("Before swap:"); + System.out.println("x value: "+x); + System.out.println("y value: "+y); + x = x+y; + y=x-y; + x=x-y; + System.out.println("After swap:"); + System.out.println("x value: "+x); + System.out.println("y value: "+y); + } + } \ No newline at end of file diff --git a/java/Basics/If Else Statement.java b/java/Basics/If Else Statement.java new file mode 100644 index 0000000..37d851d --- /dev/null +++ b/java/Basics/If Else Statement.java @@ -0,0 +1,46 @@ +If Else Statement + + + +public class IfElseStatement { + public static void main( String[] args ) { + boolean single = false; + boolean tall = true; + + // one way + if( single ) + System.out.println( "i am single" ); + + // recommended + if( single ) { + System.out.println( "i am single" ); + } + + // one way + if( single ) + System.out.println( "i am single" ); + else + System.out.println( "i am not single" ); + + // recommended + if( single ) { + System.out.println( "i am single" ); + } + else { + System.out.println( "i am not single" ); + System.out.println( "...but sometimes..." ); + } + + // note that there can be any number of + // if...else if statements + if( single == true ) { + System.out.println( "i am single" ); + } + else if( single == false && tall ) { + System.out.println( "tall, non-single man" ); + } + else { + System.out.println( "and all the rest..." ); + } + } +} diff --git a/java/Basics/InsertionSort (Java).java b/java/Basics/InsertionSort (Java).java new file mode 100644 index 0000000..6dde7b8 --- /dev/null +++ b/java/Basics/InsertionSort (Java).java @@ -0,0 +1,35 @@ +public class InsertionSortExample +{ + public static void insertionSort(int array[]) + { + int n = array.length; + for (int j = 1; j < n; j++) + { + int key = array[j]; + int i = j-1; + while ( (i > -1) && ( array [i] > key ) ) + { + array [i+1] = array [i]; + i--; + } + array[i+1] = key; + } + } + + public static void main(String a[]) + { + int[] arr1 = {9,14,3,2,43,11,58,22}; + System.out.println("Before Insertion Sort"); + for(int i:arr1) + { + System.out.print(i+" "); + } + System.out.println(); + insertionSort(arr1);//sorting array using insertion sort + System.out.println("After Insertion Sort"); + for(int i:arr1) + { + System.out.print(i+" "); + } + } +} \ No newline at end of file diff --git a/java/Basics/Integers.java b/java/Basics/Integers.java new file mode 100644 index 0000000..c36dcc8 --- /dev/null +++ b/java/Basics/Integers.java @@ -0,0 +1,215 @@ +package com.jwetherell.algorithms.numbers; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; + +public class Integers { + + private static final BigDecimal ZERO = new BigDecimal(0); + private static final BigDecimal TWO = new BigDecimal(2); + + public static final String toBinaryUsingDivideAndModulus(int numberToConvert) { + int integer = numberToConvert; + if (integer<0) throw new IllegalArgumentException("Method argument cannot be negative. number="+integer); + StringBuilder builder = new StringBuilder(); + int temp = 0; + while (integer > 0) { + temp = integer; + integer = temp / 2; + builder.append(temp % 2); + } + return builder.reverse().toString(); + } + + public static final String toBinaryUsingShiftsAndModulus(int numberToConvert) { + int integer = numberToConvert; + if (integer<0) throw new IllegalArgumentException("Method argument cannot be negative. number="+integer); + StringBuilder builder = new StringBuilder(); + int temp = 0; + while (integer > 0) { + temp = integer; + integer = (temp >> 1); + builder.append(temp % 2); + } + return builder.reverse().toString(); + } + + public static final String toBinaryUsingBigDecimal(int numberToConvert) { + int integer = numberToConvert; + if (integer<0) throw new IllegalArgumentException("Method argument cannot be negative. number="+integer); + StringBuilder builder = new StringBuilder(); + BigDecimal number = new BigDecimal(integer); + BigDecimal[] decimals = null; + while (number.compareTo(ZERO) > 0) { + decimals = number.divideAndRemainder(TWO); + number = decimals[0]; + builder.append(decimals[1]); + } + return builder.reverse().toString(); + } + + public static final String toBinaryUsingDivideAndDouble(int numberToConvert) { + int integer = numberToConvert; + if (integer<0) throw new IllegalArgumentException("Method argument cannot be negative. number="+integer); + StringBuilder builder = new StringBuilder(); + double temp = 0d; + while (integer > 0) { + temp = integer/2d; + integer = (int) temp; + builder.append((temp > integer) ? 1 : 0); + } + return builder.reverse().toString(); + } + + public static final boolean powerOfTwoUsingLoop(int numberToCheck) { + int number = numberToCheck; + if (number == 0) + return false; + while (number % 2 == 0) { + number /= 2; + } + if (number > 1) + return false; + return true; + } + + public static final boolean powerOfTwoUsingRecursion(int numberToCheck) { + int number = numberToCheck; + if (number == 1) + return true; + if (number == 0 || number % 2 != 0) + return false; + return powerOfTwoUsingRecursion(number / 2); + } + + public static final boolean powerOfTwoUsingLog(int numberToCheck) { + int number = numberToCheck; + double doubleLog = Math.log10(number) / Math.log10(2); + int intLog = (int) doubleLog; + if (doubleLog == intLog) + return true; + return false; + } + + public static final boolean powerOfTwoUsingBits(int numberToCheck) { + int number = numberToCheck; + if (number != 0 && ((number & (number - 1)) == 0)) + return true; + return false; + } + + // Integer to English + private static final Map singleDigits = new HashMap(); + static { + singleDigits.put(0,"zero"); + singleDigits.put(1,"one"); + singleDigits.put(2,"two"); + singleDigits.put(3,"three"); + singleDigits.put(4,"four"); + singleDigits.put(5,"five"); + singleDigits.put(6,"six"); + singleDigits.put(7,"seven"); + singleDigits.put(8,"eight"); + singleDigits.put(9,"nine"); + singleDigits.put(10,"ten"); + singleDigits.put(11,"eleven"); + singleDigits.put(12,"twelve"); + singleDigits.put(13,"thirteen"); + singleDigits.put(14,"fourteen"); + singleDigits.put(15,"fifteen"); + singleDigits.put(16,"sixteen"); + singleDigits.put(17,"seventee"); + singleDigits.put(18,"eighteen"); + singleDigits.put(19,"nineteen"); + } + + private static final Map multiDigits = new HashMap(); + static { + multiDigits.put(10,"ten"); + multiDigits.put(20,"twenty"); + multiDigits.put(30,"thirty"); + multiDigits.put(40,"fourty"); + multiDigits.put(50,"fifty"); + multiDigits.put(60,"sixty"); + multiDigits.put(70,"seventy"); + multiDigits.put(80,"eighty"); + multiDigits.put(90,"ninty"); + } + + private static final int BILLION = 1000000000; + private static final int MILLION = 1000000; + private static final int THOUSAND = 1000; + private static final int HUNDRED = 100; + private static final int TEN = 10; + + private static final String handleUnderOneThousand(int number) { + StringBuilder builder = new StringBuilder(); + int x = number; + int m = x / HUNDRED; + int r = x % HUNDRED; + if (m > 0) { + builder.append(singleDigits.get(m)).append("-hundred"); + x = x % HUNDRED; + } + if (r > 0) { + if (m > 0) builder.append(" "); + if (x <= 19) { + builder.append(singleDigits.get(x)); + } else { + m = x / TEN; + r = x % TEN; + if (r == 0) { + builder.append(multiDigits.get(x)); + } else { + x = x - r; + builder.append(multiDigits.get(x)).append("-"); + builder.append(singleDigits.get(r)); + } + } + } + return builder.toString(); + } + + public static final String toEnglish(int number) { + int x = number; + if (x>Integer.MAX_VALUE || x<=Integer.MIN_VALUE) throw new IllegalArgumentException("Number has to be <= Integer.MAX_VALUE and > Integer.MIN_VALUE. number="+x); + StringBuilder builder = new StringBuilder(); + if (x==0) { + //Zero is a special case + builder.append(singleDigits.get(x)); + return builder.toString(); + } + boolean billion = false; + boolean million = false; + boolean thousand = false; + if (x<0) { + builder.append("negative "); + // Make the number positive + x = x * -1; + } + int m = x / BILLION; + if (m > 0) { + billion = true; + builder.append(handleUnderOneThousand(m)).append("-billion"); + x = x % BILLION; + } + m = x / MILLION; + if (m > 0) { + if (billion) builder.append(" "); + million = true; + builder.append(handleUnderOneThousand(m)).append("-million"); + x = x % MILLION; + } + m = x / THOUSAND; + if (m > 0) { + if (billion || million) builder.append(" "); + thousand = true; + builder.append(handleUnderOneThousand(m)).append("-thousand"); + x = x % THOUSAND; + } + if (billion || million || thousand && x!=0) builder.append(" "); + builder.append(handleUnderOneThousand(x)); + return builder.toString(); + } +} diff --git a/java/Basics/Java Doc Comments.java b/java/Basics/Java Doc Comments.java new file mode 100644 index 0000000..4e3ddd0 --- /dev/null +++ b/java/Basics/Java Doc Comments.java @@ -0,0 +1,40 @@ +Java Doc Comments + + + + + +public class JavaDocComments { + + /** + * The execute method does blah blah + * + * @param min the min variable is this + * @param max the max variable is that + * @return String the process name + * @throws java.lang.NullPointerException reports any problems trying to execute process + */ + public String execute( int min, String max ) throws NullPointerException { + return null; + } + + /** + * outputs something like this for the execute method + + execute + + public String execute(int min, String max) + + The execute method does blah blah + + Parameters: + min - the min variable is this + max - the max variable is that + + Returns: + String the process name + + Throws: + NullPointerException - reports any problems trying to execute process + */ +} diff --git a/java/Basics/Java program to convert Fahrenheit to Celsius.java b/java/Basics/Java program to convert Fahrenheit to Celsius.java new file mode 100644 index 0000000..8bb8b6d --- /dev/null +++ b/java/Basics/Java program to convert Fahrenheit to Celsius.java @@ -0,0 +1,14 @@ +import java.util.*; + +class FahrenheitToCelsius +{ + public static void main(String[] args) + { + float temperatue; + Scanner in = new Scanner(System.in); + System.out.println("Enter temperatue in Fahrenheit"); + temperatue = in.nextInt(); + temperatue = ((temperatue - 32)*5)/9; + System.out.println("Temperatue in Celsius = " + temperatue); + } +} \ No newline at end of file diff --git a/java/Basics/Java program to display Current date and time.java b/java/Basics/Java program to display Current date and time.java new file mode 100644 index 0000000..d827ba8 --- /dev/null +++ b/java/Basics/Java program to display Current date and time.java @@ -0,0 +1,22 @@ + import java.util.*; + + class GetCurrentDateAndTime + { + public static void main(String args[]) + { + int day, month, year; + int second, minute, hour; + GregorianCalendar date = new GregorianCalendar(); + + day = date.get(Calendar.DAY_OF_MONTH); + month = date.get(Calendar.MONTH); + year = date.get(Calendar.YEAR); + + second = date.get(Calendar.SECOND); + minute = date.get(Calendar.MINUTE); + hour = date.get(Calendar.HOUR); + + System.out.println("Current date is "+day+"/"+(month+1)+"/"+year); + System.out.println("Current time is "+hour+" : "+minute+" : "+second); + } + } \ No newline at end of file diff --git a/java/Basics/Java program to find all substrings of a string.java b/java/Basics/Java program to find all substrings of a string.java new file mode 100644 index 0000000..66bd25e --- /dev/null +++ b/java/Basics/Java program to find all substrings of a string.java @@ -0,0 +1,23 @@ +import java.util.Scanner; + +class SubstringsOfAString +{ + public static void main(String args[]) + { + String string, sub; + int i, c, length; + Scanner in = new Scanner(System.in); + System.out.println("Enter a string to print it's all substrings"); + string = in.nextLine(); + length = string.length(); + System.out.println("Substrings of \""+string+"\" are :-"); + for( c = 0 ; c < length ; c++ ) + { + for( i = 1 ; i <= length - c ; i++ ) + { + sub = string.substring(c, c+i); + System.out.println(sub); + } + } + } +} \ No newline at end of file diff --git a/java/Basics/Java program to perform garbage collection.java b/java/Basics/Java program to perform garbage collection.java new file mode 100644 index 0000000..02c1a34 --- /dev/null +++ b/java/Basics/Java program to perform garbage collection.java @@ -0,0 +1,12 @@ +import java.util.*; + +class GarbageCollection +{ + public static void main(String s[]) throws Exception + { + Runtime rs = Runtime.getRuntime(); + System.out.println("Free memory in JVM before Garbage Collection = "+rs.freeMemory()); + rs.gc(); + System.out.println("Free memory in JVM after Garbage Collection = "+rs.freeMemory()); + } +} \ No newline at end of file diff --git a/java/Basics/Java program to transpose matrix.java b/java/Basics/Java program to transpose matrix.java new file mode 100644 index 0000000..6942967 --- /dev/null +++ b/java/Basics/Java program to transpose matrix.java @@ -0,0 +1,31 @@ +import java.util.Scanner; + +class TransposeAMatrix +{ + public static void main(String args[]) + { + int m, n, c, d; + Scanner in = new Scanner(System.in); + System.out.println("Enter the number of rows and columns of matrix"); + m = in.nextInt(); + n = in.nextInt(); + int matrix[][] = new int[m][n]; + System.out.println("Enter the elements of matrix"); + for ( c = 0 ; c < m ; c++ ) + for ( d = 0 ; d < n ; d++ ) + matrix[c][d] = in.nextInt(); + int transpose[][] = new int[n][m]; + for ( c = 0 ; c < m ; c++ ) + { + for ( d = 0 ; d < n ; d++ ) + transpose[d][c] = matrix[c][d]; + } + System.out.println("Transpose of entered matrix:-"); + for ( c = 0 ; c < n ; c++ ) + { + for ( d = 0 ; d < m ; d++ ) + System.out.print(transpose[c][d]+"\t"); + System.out.print("\n"); + } + } +} \ No newline at end of file diff --git a/java/Basics/KnuthMorrisPratt.java b/java/Basics/KnuthMorrisPratt.java new file mode 100644 index 0000000..361ccd3 --- /dev/null +++ b/java/Basics/KnuthMorrisPratt.java @@ -0,0 +1,56 @@ +package com.jwetherell.algorithms.strings; + +import java.util.ArrayList; +import java.util.List; + +/** + * This class implements KMP algorithm for finding length of maximal prefix-suffix for each prefix of the string. + * Prefix-suffix of string S is a substring which occurs at the beginning and at the end of S. + *

+ * Time complexity: O(n)
+ *
+ * https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm + *
+ * @author Szymon Stankiewicz + * @author Justin Wetherell + */ +public class KnuthMorrisPratt { + + private KnuthMorrisPratt() {} + + /** + * This function implements KMP algorithm for finding length of maximal prefix-suffix for each prefix of the string. + * Prefix-suffix of string S is a substring which occurs at the beginning and at the end of S. + *

+ * Time complexity: O(n)

+ *

+ * https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm + *
+ * @param text Text + * @return maximal length of prefix-suffix for each prefix of the string text + */ + public static List getPrefSufTable(String text) { + final List prefSufTable = new ArrayList(); + final char[] chars = text.toCharArray(); + + if (text.length() == 0) + return prefSufTable; + + prefSufTable.add(0); + + for (int i = 1; i 0 && (chars[i] != chars[sizeOfPrefSuf])) + sizeOfPrefSuf = prefSufTable.get(sizeOfPrefSuf-1); // because string is 0-indexed + + // if characters at this positions are different then sizeOfPrefSuf is equal to zero, + // so there is no proper prefix-suffix + if (chars[i] == chars[sizeOfPrefSuf]) { + prefSufTable.add(sizeOfPrefSuf+1); + } else { + prefSufTable.add(0); + } + } + return prefSufTable; + } +} diff --git a/java/Basics/Letter combinations recursion.java b/java/Basics/Letter combinations recursion.java new file mode 100644 index 0000000..3036d9c --- /dev/null +++ b/java/Basics/Letter combinations recursion.java @@ -0,0 +1,31 @@ +Letter combinations recursion + + + + + +public class LetterCombinationsRecursion { + + private static String sum = ""; + + public static void main( String[] argv ) { + long l = System.currentTimeMillis(); + printAlphabetCombinations( 4, "" ); + System.out.println( "Time:" + ( System.currentTimeMillis() - l ) / 1000 + " sec" ); + } + + public static void printAlphabetCombinations( int recurseCounter, String current ) { + String temp = current; + if( recurseCounter == 0 ) { + System.out.println( temp ); + return; + } + else { + recurseCounter--; + for( int i = 0; i < 26; i++ ) { + temp = current + (char) ( 65 + i ); + printAlphabetCombinations( recurseCounter, temp ); + } + } + } +} diff --git a/java/Basics/Listing all running threads.java b/java/Basics/Listing all running threads.java new file mode 100644 index 0000000..5eadcaf --- /dev/null +++ b/java/Basics/Listing all running threads.java @@ -0,0 +1,42 @@ +Listing all running threads + +// Find the root thread group +ThreadGroup root = Thread.currentThread().getThreadGroup().getParent(); + while (root.getParent() != null) { + root = root.getParent(); +} + +// Visit each thread group +visit(root, 0); + +// This method recursively visits all thread groups under `group'. + public static void visit(ThreadGroup group, int level) { + // Get threads in `group' + int numThreads = group.activeCount(); + Thread[] threads = new Thread[numThreads*2]; + numThreads = group.enumerate(threads, false); + + // Enumerate each thread in `group' + for (int i=0; i // Get thread + Thread thread = threads[i]; + } + + // Get thread subgroups of `group' + int numGroups = group.activeGroupCount(); + ThreadGroup[] groups = new ThreadGroup[numGroups*2]; + numGroups = group.enumerate(groups, false); + + // Recursively visit each subgroup + for (int i=0; i visit(groups[i], level+1); + } +} + +//Here's an example of some thread groups that contain some threads: +java.lang.ThreadGroup[name=system,maxpri=10] +Thread[Reference Handler,10,system] +Thread[Finalizer,8,system] +Thread[Signal Dispatcher,10,system] +Thread[CompileThread0,10,system] +java.lang.ThreadGroup[name=main,maxpri=10] +Thread[main,5,main] +Thread[Thread-1,5,main] diff --git a/java/Basics/LongestCommonSubsequence.java b/java/Basics/LongestCommonSubsequence.java new file mode 100644 index 0000000..fa807cd --- /dev/null +++ b/java/Basics/LongestCommonSubsequence.java @@ -0,0 +1,175 @@ +package com.jwetherell.algorithms.sequence; + +import java.util.HashSet; +import java.util.Set; + +/** + * The longest common subsequence (LCS) problem is the problem of finding the longest subsequence common to all sequences in a set of sequences (often just two sequences). It differs from problems + * of finding common substrings: unlike substrings, subsequences are not required to occupy consecutive positions within the original sequences. + *

+ * https://en.wikipedia.org/wiki/Longest_common_subsequence_problem + *
+ * @author Justin Wetherell + */ +@SuppressWarnings("unchecked") +public class LongestCommonSubsequence { + + private static int[][] lengthMatrix = null; + private static Set[][] sequenceMatrix = null; + + private LongestCommonSubsequence() { } + + public static MatrixPair getLCS(char[] seq1, char[] seq2) { + try { + populateMatrix(seq1, seq2); + + for (int i = 0; i < seq1.length; i++) { + for (int j = 0; j < seq2.length; j++) { + lengthMatrix[i + 1][j + 1] = longestCommonSubsequence(i, j, seq1, seq2); + } + } + + return (new MatrixPair(lengthMatrix, sequenceMatrix)); + } finally { + lengthMatrix = null; + sequenceMatrix = null; + } + } + + private static void populateMatrix(char[] seq1, char[] seq2) { + lengthMatrix = new int[seq1.length + 1][seq2.length + 1]; + sequenceMatrix = new HashSet[seq1.length][seq2.length]; + } + + private static int longestCommonSubsequence(int i, int j, char[] seq1, char[] seq2) { + char x = seq1[i]; + char y = seq2[j]; + int result = 0; + Set set = sequenceMatrix[i][j]; + if (set == null) + set = new HashSet(); + if (x == y) { + if (i > 0 && j > 0) + set = new HashSet(sequenceMatrix[i - 1][j - 1]); + distribute(x, set); + + result = (lengthMatrix[i][j]) + 1; + } else { + int a = lengthMatrix[i][j + 1]; + int b = lengthMatrix[i + 1][j]; + + if (a > b) { + set = new HashSet(sequenceMatrix[i - 1][j]); + + result = a; + } else if (b > a) { + set = new HashSet(sequenceMatrix[i][j - 1]); + + result = b; + } else if (a == b) { + if (i > 0 && j > 0) { + Set list1 = sequenceMatrix[i - 1][j]; + Set list2 = sequenceMatrix[i][j - 1]; + + set.addAll(list1); + set.addAll(list2); + } + + result = a; // a==b + } + } + sequenceMatrix[i][j] = set; + return result; + } + + private static void distribute(char c, Set set) { + if (set.size() == 0) { + set.add(String.valueOf(c)); + } else { + Object[] strings = set.toArray(); + set.clear(); + for (Object object : strings) { + String string = (String) object; + String seq = String.valueOf(c); + if (!string.contains(seq)) + string = string.concat(seq); + set.add(string); + } + } + } + + public static class MatrixPair { + + private int[][] lenMatrix = null; + private Set[][] seqMatrix = null; + + public MatrixPair(int[][] lengthMatrix, Set[][] sequenceMatrix) { + this.lenMatrix = lengthMatrix; + this.seqMatrix = sequenceMatrix; + } + + public int getLongestSequenceLength() { + if (lenMatrix == null) + return 0; + + int length1 = lenMatrix.length; + int length2 = lenMatrix[length1 - 1].length; + return lenMatrix[length1 - 1][length2 - 1]; + } + + public Set getLongestSequences() { + if (seqMatrix == null) + return (new HashSet()); + + int length1 = seqMatrix.length; + int length2 = seqMatrix[length1 - 1].length; + return seqMatrix[length1 - 1][length2 - 1]; + } + + public int[][] getLengthMatrix() { + return lenMatrix; + } + + public Set[][] getSequenceMatrix() { + return seqMatrix; + } + + public String getLengthMatrixString() { + StringBuilder builder = new StringBuilder(); + if (lenMatrix == null) { + builder.append("Length matrix is NULL.\n"); + } else { + for (int i = 0; i < lenMatrix.length; i++) { + int length = lenMatrix[i].length; + for (int j = 0; j < length; j++) { + int size = lenMatrix[i][j]; + builder.append(size); + if (j < length - 1) + builder.append(",\t"); + } + builder.append("\n"); + } + } + return builder.toString(); + } + + public String getSequenceMatrixString() { + StringBuilder builder = new StringBuilder(); + if (seqMatrix == null) { + builder.append("Sequence matrix is NULL.\n"); + } else { + for (int i = 0; i < seqMatrix.length; i++) { + int length = seqMatrix[i].length; + for (int j = 0; j < length; j++) { + Set set = seqMatrix[i][j]; + builder.append(set.toString()); + if (j < length - 1) + builder.append(", "); + } + builder.append("\n"); + } + } + return builder.toString(); + } + } +} diff --git a/java/Basics/LongestIncreasingSubsequence.java b/java/Basics/LongestIncreasingSubsequence.java new file mode 100644 index 0000000..cdb39de --- /dev/null +++ b/java/Basics/LongestIncreasingSubsequence.java @@ -0,0 +1,38 @@ +package com.jwetherell.algorithms.sequence; + +import com.jwetherell.algorithms.search.LowerBound; + +import java.util.Arrays; + +/** + * In computer science, the longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in + * which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique. + *

+ * https://en.wikipedia.org/wiki/Longest_increasing_subsequence + *
+ * @author Bartlomiej Drozd + * @author Justin Wetherell + */ +public class LongestIncreasingSubsequence { + + private LongestIncreasingSubsequence() { } + + /** + * Longest increasing subsequence solved using dynamic programming. + */ + public static int[] getLongestIncreasingSubsequence(int[] sequence) { + final int[] resultSequence = new int[sequence.length]; + + int resultLength = 0; + for (int i = 0; i < sequence.length; ++i) { + // try to find the best place for new element in sorted result + final int pos = LowerBound.lowerBound(resultSequence, resultLength, sequence[i]); //O(log n) + // if the best place is at the end increase result length + if (pos >= resultLength) + resultLength++; + resultSequence[pos] = sequence[i]; + } + + return Arrays.copyOfRange(resultSequence, 0, resultLength); + } +} diff --git a/java/Basics/Longs.java b/java/Basics/Longs.java new file mode 100644 index 0000000..e3f1f3d --- /dev/null +++ b/java/Basics/Longs.java @@ -0,0 +1,48 @@ +package com.jwetherell.algorithms.numbers; + +import java.math.BigDecimal; + +public class Longs { + + public static final String toBinaryUsingDivideAndModulus(long numberToConvert) { + long longNumber = numberToConvert; + if (longNumber<0) throw new IllegalArgumentException("Method argument cannot be negative. number="+longNumber); + StringBuilder builder = new StringBuilder(); + long temp = 0l; + while (longNumber > 0) { + temp = longNumber; + longNumber = temp / 2; + builder.append(temp % 2); + } + return builder.reverse().toString(); + } + + public static final String toBinaryUsingShiftsAndModulus(long numberToConvert) { + long longNumber = numberToConvert; + if (longNumber<0) throw new IllegalArgumentException("Method argument cannot be negative. number="+longNumber); + StringBuilder builder = new StringBuilder(); + long temp = 0l; + while (longNumber > 0) { + temp = longNumber; + longNumber = (temp >> 1); + builder.append(temp % 2); + } + return builder.reverse().toString(); + } + + public static final String toBinaryUsingBigDecimal(long numberToConvert) { + long longNumber = numberToConvert; + if (longNumber<0) throw new IllegalArgumentException("Method argument cannot be negative. number="+longNumber); + StringBuilder builder = new StringBuilder(); + BigDecimal zero = new BigDecimal(0); + BigDecimal two = new BigDecimal(2); + BigDecimal number = new BigDecimal(longNumber); + BigDecimal[] decimals = null; + while (number.compareTo(zero) > 0) { + decimals = number.divideAndRemainder(two); + number = decimals[0]; + builder.append(decimals[1]); + } + return builder.reverse().toString(); + } +} diff --git a/java/Basics/Multiple Inheritance.java b/java/Basics/Multiple Inheritance.java new file mode 100644 index 0000000..2b51092 --- /dev/null +++ b/java/Basics/Multiple Inheritance.java @@ -0,0 +1,28 @@ +Multiple Inheritance + + + + + +import java.io.Serializable; +import java.rmi.Remote; +import java.util.Vector; + +public class MultipleInheritance + extends Vector + implements Remote, Serializable { + /** + * Java is a single inheritance tree and only allows a + * class to inherit implementation from one class. That + * class is specified using extends (eg. Vector ) otherwise + * if nothing is specified it is Object, the root class in + * the Java inheritance hierarchy + *

+ * However, Java does support the multiple interface inheritance. + * In this example we inheritance from both the Remote and Serializable + * interfaces. + */ + public static void main( String[] args ) { + + } +} diff --git a/java/Basics/Null Reference.java b/java/Basics/Null Reference.java new file mode 100644 index 0000000..baabd87 --- /dev/null +++ b/java/Basics/Null Reference.java @@ -0,0 +1,33 @@ +Null Reference + + + + + +import com.ack.learning.examples.account.Account; + +public class NullReference { + public static void main( String[] args ) { + // unitialised variables + String x; + Account y; + + /** + * this is an error because x is unitialised + if( x == null ) + { + + } + */ + + // initialised variables + String hsbc = null; + Account account = null; + + // object arrays are initialised to null + String[] names = new String[5]; + for( int i = 0; i < names.length; i++ ) { + System.out.println( names[i] ); + } + } +} diff --git a/java/Basics/Palindrome (Java).java b/java/Basics/Palindrome (Java).java new file mode 100644 index 0000000..b773622 --- /dev/null +++ b/java/Basics/Palindrome (Java).java @@ -0,0 +1,19 @@ +class PalindromeExample +{ + public static void main(String args[]) + { + int r,sum=0,temp; + int n=454;//It is the number variable to be checked for palindrome + temp=n; + while(n>0) + { + r=n%10; //getting remainder + sum=(sum*10)+r; + n=n/10; + } + if(temp==sum) + System.out.println("palindrome number "); + else + System.out.println("not palindrome"); + } +} \ No newline at end of file diff --git a/java/Basics/Pie Eater.java b/java/Basics/Pie Eater.java new file mode 100644 index 0000000..1c32696 --- /dev/null +++ b/java/Basics/Pie Eater.java @@ -0,0 +1,21 @@ +Pie Eater + + + +package com.ack.learning.exceptions; + +public class PieEater { + private int piesEaten; + + // the throws clause tells use that this method + // can throw a PieException + public int howManyPies() throws PieException { + // do some processing + if( piesEaten > 100 ) { + // create a PieException object and throw it + throw new PieException( "he's eaten all the pies" ); + } + + return piesEaten; + } +} diff --git a/java/Basics/Pie Maker.java b/java/Basics/Pie Maker.java new file mode 100644 index 0000000..756343f --- /dev/null +++ b/java/Basics/Pie Maker.java @@ -0,0 +1,27 @@ +Pie Maker + + + +package com.ack.learning.exceptions; + +import com.ack.learning.exceptions.PieEater; +import com.ack.learning.exceptions.PieException; + +public class PieMaker { + public static void main( String[] args ) { + try { + PieEater pie = new PieEater(); + // some processing + System.out.println( pie.howManyPies() ); + } + catch( PieException pex ) { + // catch the PieException and printout its stack trace + pex.printStackTrace(); + } + finally { + // and always print out 'no more pies', regardless of what + // happens within the try block + System.out.println( "no more pies" ); + } + } +} diff --git a/java/Basics/Pie exception.java b/java/Basics/Pie exception.java new file mode 100644 index 0000000..200e2be --- /dev/null +++ b/java/Basics/Pie exception.java @@ -0,0 +1,16 @@ +Pie exception + + + +package com.ack.learning.exceptions; + +// define your own exception by extending java.lang.Exception + +public class PieException extends Exception { + // let this exception accept a user message that can be + // accessed through calling getMessage() that is defined + // within its parent class + public PieException( String msg ) { + super( msg ); + } +} diff --git a/java/Basics/Pre and post increment operators.java b/java/Basics/Pre and post increment operators.java new file mode 100644 index 0000000..c36a500 --- /dev/null +++ b/java/Basics/Pre and post increment operators.java @@ -0,0 +1,34 @@ +Pre and post increment operators + + + + + +public class PreAndPostIncrementOperators { + public static void main( String[] args ) { + int index = 0; + + // all these statements add one to index + index = index + 1; + index += 1; + index++; + ++index; + + // prints index value -> 4 + System.out.println( index ); + + // prints index current value of 4, and then increments + System.out.println( index++ ); + + // prints index value which is 5 + System.out.println( index ); + + // increments index, and then prints its value of 6 + System.out.println( ++index ); + + // prints out current value of index which is 6 + System.out.println( index ); + + // same logic holds for -- operator + } +} diff --git a/java/Basics/Program for converting numbers in a file to corres.java b/java/Basics/Program for converting numbers in a file to corres.java new file mode 100644 index 0000000..9244787 --- /dev/null +++ b/java/Basics/Program for converting numbers in a file to corres.java @@ -0,0 +1,114 @@ +Program for converting numbers in a file to corresponding words + +import java.io.*; +import java.lang.*; + +class NumToWords +{ + public static void main(String a[]) throws IOException + { + String s=""; + BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); + System.out.print("Enter filename : "); + try + { + s=br.readLine(); + }catch(Exception e){} + InputStream in=new FileInputStream(s); + MyInputStream mis=new MyInputStream(in); + mis.changeNumbers(); + in.close(); + mis.close(); + } +} +class MyInputStream extends FilterInputStream +{ + InputStream is; + MyInputStream(InputStream in) + { + super(in); + is=in; + } + public void changeNumbers() throws IOException + { + PushbackInputStream pis; + String num=""; + char ch; + int c; + pis=new PushbackInputStream(is); + while((c=pis.read())!=-1) + { + ch=(char)c; + if('0'<=ch&&ch<='9') + { + num=""; + while('0'<=ch&&ch<='9'&&c!=-1) + { + num=num+ch; + c=pis.read(); + ch=(char)c; + } + System.out.print(MyInputStream.process(num)); + pis.unread(ch); + } + else + System.out.print(ch); + } + } + static String process(String str) + { + String a1[]={"One","Two","Three","Four","Five","Six","Seven","Eight","Nine"}; + String a2[]={"Twenty","Thirty","Fourty","Fifty","Sixty","Seventy","Eighty","Ninety"}; + String a3[]={"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; + String a4[]={"Hundered","Thousand","Lakhs","Crores"}; + int num=0; + try + { + num=Integer.parseInt(str); + }catch(Exception e){} + if(num==0) + return "Zero"; + int n,n1; + String ans=""; + String ans1=""; + n1=num%10; + num=num/10; + if(n1!=0) + ans=a1[n1-1]; + if(num>0) + { + n=num%10; + num=num/10; + if(n==1) + ans=a3[n1]; + else if(n!=0) + ans=a2[n-2]+" "+ans; + } + if(num>0) + { + n=num%10; + num=num/10; + if(n!=0) + ans=a1[n-1]+" "+a4[0]+" "+ans; + } + for(int i=1;num>0;i++) + { + n1=num%10; + num=num/10; + if(n1!=0) + ans1=a1[n1-1]; + if(num>0) + { + n=num%10; + num=num/10; + if(n==1) + ans1=a3[n1]; + else if(n!=0) + ans1=a2[n-2]+" "+ans1; + } + ans=ans1+" "+a4[i]+" "+ans; + ans1=""; + } + return(ans); + } +} diff --git a/java/Basics/Program for counting no.java b/java/Basics/Program for counting no.java new file mode 100644 index 0000000..ae8ffcd --- /dev/null +++ b/java/Basics/Program for counting no.java @@ -0,0 +1,35 @@ +Program for counting no. of Chars, Words and Lines in a file + +import java.lang.*; +import java.io.*; +import java.util.*; +class WordCount +{ + public static void main(String arg[]) throws Exception + { + int char_count=0; + int word_count=0; + int line_count=0; + String s; + StringTokenizer st; + BufferedReader buf=new BufferedReader(new InputStreamReader(System.in)); + System.out.print("Enter filename : "); + s=buf.readLine(); + buf=new BufferedReader(new FileReader(s)); + while((s=buf.readLine())!=null) + { + line_count++; + st=new StringTokenizer(s," ,;:."); + while(st.hasMoreTokens()) + { + word_count++; + s=st.nextToken(); + char_count+=s.length(); + } + } + System.out.println("Character Count : "+char_count); + System.out.println("Word Count : "+word_count); + System.out.println("Line Count : "+line_count); + buf.close(); + } +} diff --git a/java/Basics/Program to Add of two matrices (Java).java b/java/Basics/Program to Add of two matrices (Java).java new file mode 100644 index 0000000..b2c37b4 --- /dev/null +++ b/java/Basics/Program to Add of two matrices (Java).java @@ -0,0 +1,36 @@ +import java.util.Scanner; + +class Add2Matrix +{ + + public static void main(String args[]) + { + int rows, cols, c, d; + Scanner in = new Scanner(System.in); + System.out.println("Please Enter number of rows and columns"); + rows = in.nextInt(); + cols = in.nextInt(); + int first[][] = new int[rows][cols]; + int second[][] = new int[rows][cols]; + int sum[][] = new int[rows][cols]; + System.out.println("Please Enter elements of first matrix"); + for ( c = 0 ; c < rows ; c++ ) + for ( d = 0 ; d < cols ; d++ ) + first[c][d] = in.nextInt(); + System.out.println("Please Enter elements of second matrix"); + for ( c = 0 ; c < rows ; c++ ) + for ( d = 0 ; d < cols ; d++ ) + second[c][d] = in.nextInt(); + for ( c = 0 ; c < rows ; c++ ) + for ( d = 0 ; d < cols ; d++ ) + sum[c][d] = first[c][d] + second[c][d]; //replace '+' with '-' to subtract matrices + System.out.println("Sum of entered matrices:-"); + for ( c = 0 ; c < rows ; c++ ) + { + for ( d = 0 ; d < cols ; d++ ) + System.out.print(sum[c][d]+"\t"); + System.out.println(); + } + } + +} diff --git a/java/Basics/Program to Calculate Circle Area (Java).java b/java/Basics/Program to Calculate Circle Area (Java).java new file mode 100644 index 0000000..0563645 --- /dev/null +++ b/java/Basics/Program to Calculate Circle Area (Java).java @@ -0,0 +1,51 @@ +/* + Calculate Circle Area using Java Example + This Calculate Circle Area using Java Example shows how to calculate + area of circle using it's radius. +*/ + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class CalculateCircleAreaExample +{ + + public static void main(String[] args) + { + int radius = 0; + System.out.println("Please enter radius of a circle"); + try + { + //get the radius from console + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + radius = Integer.parseInt(br.readLine()); + } + //if invalid value was entered + catch(NumberFormatException ne) + { + System.out.println("Invalid radius value" + ne); + System.exit(0); + } + catch(IOException ioe) + { + System.out.println("IO Error :" + ioe); + System.exit(0); + } + /* + * Area of a circle is + * pi * r * r + * where r is a radius of a circle. + */ + //NOTE : use Math.PI constant to get value of pi + double area = Math.PI * radius * radius; + System.out.println("Area of a circle is " + area); + } +} + +/* +Output of Calculate Circle Area using Java Example would be +Please enter radius of a circle +19 +Area of a circle is 1134.1149479459152 +*/ \ No newline at end of file diff --git a/java/Basics/Program to Calculate Circle Perimeter (Java).java b/java/Basics/Program to Calculate Circle Perimeter (Java).java new file mode 100644 index 0000000..01a7a00 --- /dev/null +++ b/java/Basics/Program to Calculate Circle Perimeter (Java).java @@ -0,0 +1,51 @@ +/* + Calculate Circle Perimeter using Java Example + This Calculate Circle Perimeter using Java Example shows how to calculate + Perimeter of circle using it's radius. +*/ + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class CalculateCirclePerimeterExample +{ + + public static void main(String[] args) + { + int radius = 0; + System.out.println("Please enter radius of a circle"); + try + { + //get the radius from console + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + radius = Integer.parseInt(br.readLine()); + } + //if invalid value was entered + catch(NumberFormatException ne) + { + System.out.println("Invalid radius value" + ne); + System.exit(0); + } + catch(IOException ioe) + { + System.out.println("IO Error :" + ioe); + System.exit(0); + } + /* + * Perimeter of a circle is + * 2 * pi * r + * where r is a radius of a circle. + */ + //NOTE : use Math.PI constant to get value of pi + double perimeter = 2 * Math.PI * radius; + System.out.println("Perimeter of a circle is " + perimeter); + } +} + +/* +Output of Calculate Circle Perimeter using Java Example would be +Please enter radius of a circle +19 +Perimeter of a circle is 119.38052083641213 +*/ \ No newline at end of file diff --git a/java/Basics/Program to Calculate Rect Area (Java).java b/java/Basics/Program to Calculate Rect Area (Java).java new file mode 100644 index 0000000..70a862e --- /dev/null +++ b/java/Basics/Program to Calculate Rect Area (Java).java @@ -0,0 +1,56 @@ +/* + Calculate Rectangle Area using Java Example + This Calculate Rectangle Area using Java Example shows how to calculate + area of Rectangle using it's length and width. +*/ + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class CalculateRectArea +{ + + public static void main(String[] args) + { + int width = 0; + int length = 0; + try + { + //read the length from console + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Please enter length of a rectangle"); + length = Integer.parseInt(br.readLine()); + //read the width from console + System.out.println("Please enter width of a rectangle"); + width = Integer.parseInt(br.readLine()); + } + //if invalid value was entered + catch(NumberFormatException ne) + { + System.out.println("Invalid value" + ne); + System.exit(0); + } + catch(IOException ioe) + { + System.out.println("IO Error :" + ioe); + System.exit(0); + } + /* + * Area of a rectangle is + * length * width + */ + int area = length * width; + System.out.println("Area of a rectangle is " + area); + } + +} + +/* +Output of Calculate Rectangle Area using Java Example would be +Please enter length of a rectangle +10 +Please enter width of a rectangle +15 +Area of a rectangle is 150 +*/ \ No newline at end of file diff --git a/java/Basics/Program to Calculate Rect Perimeter (Java).java b/java/Basics/Program to Calculate Rect Perimeter (Java).java new file mode 100644 index 0000000..faad5a6 --- /dev/null +++ b/java/Basics/Program to Calculate Rect Perimeter (Java).java @@ -0,0 +1,56 @@ +/* + Calculate Rectangle Perimeter using Java Example + This Calculate Rectangle Perimeter using Java Example shows how to calculate + perimeter of Rectangle using it's length and width. +*/ + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class CalculateRectPerimeter +{ + + public static void main(String[] args) + { + int width = 0; + int length = 0; + try + { + //read the length from console + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Please enter length of a rectangle"); + length = Integer.parseInt(br.readLine()); + //read the width from console + System.out.println("Please enter width of a rectangle"); + width = Integer.parseInt(br.readLine()); + } + //if invalid value was entered + catch(NumberFormatException ne) + { + System.out.println("Invalid value" + ne); + System.exit(0); + } + catch(IOException ioe) + { + System.out.println("IO Error :" + ioe); + System.exit(0); + } + /* + * Perimeter of a rectangle is + * 2 * (length + width) + */ + int perimeter = 2 * (length + width); + System.out.println("Perimeter of a rectangle is " + perimeter); + } + +} + +/* +Output of Calculate Rectangle Perimeter using Java Example would be +Please enter length of a rectangle +10 +Please enter width of a rectangle +15 +Perimeter of a rectangle is 50 +*/ \ No newline at end of file diff --git a/java/Basics/Program to Find Even Or Odd Number (Java).java b/java/Basics/Program to Find Even Or Odd Number (Java).java new file mode 100644 index 0000000..157bba2 --- /dev/null +++ b/java/Basics/Program to Find Even Or Odd Number (Java).java @@ -0,0 +1,41 @@ +/* + Even Odd Number Example + This Java Even Odd Number Example shows how to check if the given + number is even or odd. +*/ + +public class FindEvenOrOddNumber +{ + + public static void main(String[] args) + { + //create an array of 10 numbers + int[] numbers = new int[] {1,2,3,4,5,6,7,8,9,10}; + for(int i=0; i < numbers.length; i++) + { + /* + * use modulus operator to check if the number is even or odd. + * If we divide any number by 2 and reminder is 0 then the number is + * even, otherwise it is odd. + */ + if(numbers[i]%2 == 0) + System.out.println(numbers[i] + " is even number."); + else + System.out.println(numbers[i] + " is odd number."); + } + } +} + +/* +Output of the program would be +1 is odd number. +2 is even number. +3 is odd number. +4 is even number. +5 is odd number. +6 is even number. +7 is odd number. +8 is even number. +9 is odd number. +10 is even number. +*/ \ No newline at end of file diff --git a/java/Basics/Program to Find Largest Smallest Number (Java).java b/java/Basics/Program to Find Largest Smallest Number (Java).java new file mode 100644 index 0000000..0fdc3b3 --- /dev/null +++ b/java/Basics/Program to Find Largest Smallest Number (Java).java @@ -0,0 +1,32 @@ +/* + Find Largest and Smallest Number in an Array Example + This Java Example shows how to find largest and smallest number in an + array. +*/ +public class FindLargestSmallestNumber +{ + + public static void main(String[] args) + { + //array of 10 numbers + int numbers[] = new int[] {32,43,53,54,32,65,63,98,43,23}; + //assign first element of an array to largest and smallest + int smallest = numbers[0]; + int largetst = numbers[0]; + for(int i=1; i< numbers.length; i++) + { + if(numbers[i] > largetst) + largetst = numbers[i]; + else if (numbers[i] < smallest) + smallest = numbers[i]; + } + System.out.println("Largest Number is : " + largetst); + System.out.println("Smallest Number is : " + smallest); + } +} + +/* +Output of this program would be +Largest Number is : 98 +Smallest Number is : 23 +*/ \ No newline at end of file diff --git a/java/Basics/Program to Find Second smallest number in java without sorting (Java).java b/java/Basics/Program to Find Second smallest number in java without sorting (Java).java new file mode 100644 index 0000000..2b356a0 --- /dev/null +++ b/java/Basics/Program to Find Second smallest number in java without sorting (Java).java @@ -0,0 +1,26 @@ + +class SecondSmallestNumber +{ + + public static void main(String args[]) + { + int numbers[] = {6,3,37,12,46,5,64,21}; + int smallest= numbers[0];; + int second_smallest = numbers[0];; + for(int n:numbers) + { + if(n< smallest) + { + second_smallest = smallest; + smallest=n; + } + else if( n< second_smallest) + { + second_smallest= n; + } + } + System.out.println("Smallest Number: "+smallest); + System.out.println("Second Smallest Number: "+second_smallest); + } + +} \ No newline at end of file diff --git a/java/Basics/Program to Find longest substring without repeating characters (Java).java b/java/Basics/Program to Find longest substring without repeating characters (Java).java new file mode 100644 index 0000000..8c8f195 --- /dev/null +++ b/java/Basics/Program to Find longest substring without repeating characters (Java).java @@ -0,0 +1,78 @@ +/* +Given a string, find the longest substrings without repeating characters. Iterate through the given string, find the longest maximum substrings. + +*/ + +import java.util.HashSet; +import java.util.Set; + +public class MyLongestSubstr +{ + + private Set subStrList = new HashSet(); + private int finalSubStrSize = 0; + + public Set getLongestSubstr(String input) + { + //reset instance variables + subStrList.clear(); + finalSubStrSize = 0; + // have a boolean flag on each character ascii value + boolean[] flag = new boolean[256]; + int j = 0; + char[] inputCharArr = input.toCharArray(); + for (int i = 0; i < inputCharArr.length; i++) + { + char c = inputCharArr[i]; + if (flag[c]) + { + extractSubString(inputCharArr,j,i); + for (int k = j; k < i; k++) + { + if (inputCharArr[k] == c) + { + j = k + 1; + break; + } + flag[inputCharArr[k]] = false; + } + } + else + { + flag[c] = true; + } + } + extractSubString(inputCharArr,j,inputCharArr.length); + return subStrList; + } + + private String extractSubString(char[] inputArr, int start, int end) + { + StringBuilder sb = new StringBuilder(); + for(int i=start; i finalSubStrSize) + { + finalSubStrSize = subStr.length(); + subStrList.clear(); + subStrList.add(subStr); + } + else if(subStr.length() == finalSubStrSize) + { + subStrList.add(subStr); + } + return sb.toString(); + } + + public static void main(String a[]) + { + MyLongestSubstr mls = new MyLongestSubstr(); + System.out.println(mls.getLongestSubstr("java2novice")); + System.out.println(mls.getLongestSubstr("java_language_is_sweet")); + System.out.println(mls.getLongestSubstr("java_java_java_java")); + System.out.println(mls.getLongestSubstr("abcabcbb")); + } +} \ No newline at end of file diff --git a/java/Basics/Program to Find out duplicate number between 1 to N numbers (Java).java b/java/Basics/Program to Find out duplicate number between 1 to N numbers (Java).java new file mode 100644 index 0000000..df347e0 --- /dev/null +++ b/java/Basics/Program to Find out duplicate number between 1 to N numbers (Java).java @@ -0,0 +1,37 @@ +import java.util.ArrayList; +import java.util.List; + +public class DuplicateNumber +{ + + public int findDuplicateNumber(List numbers) + { + int highestNumber = numbers.size() - 1; + int total = getSum(numbers); + int duplicate = total - (highestNumber*(highestNumber+1)/2); + return duplicate; + } + + public int getSum(List numbers) + { + int sum = 0; + for(int num:numbers) + { + sum += num; + } + return sum; + } + + public static void main(String a[]) + { + List numbers = new ArrayList(); + for(int i=1; i<30; i++) + { + numbers.add(i); + } + //add duplicate number into the list + numbers.add(22); + DuplicateNumber dn = new DuplicateNumber(); + System.out.println("Duplicate Number: "+dn.findDuplicateNumber(numbers)); + } +} \ No newline at end of file diff --git a/java/Basics/Program to Find out middle index where sum of both ends are equal. (Java).java b/java/Basics/Program to Find out middle index where sum of both ends are equal. (Java).java new file mode 100644 index 0000000..38ebd08 --- /dev/null +++ b/java/Basics/Program to Find out middle index where sum of both ends are equal. (Java).java @@ -0,0 +1,50 @@ +public class FindMiddleIndex +{ + + public static int findMiddleIndex(int[] numbers) throws Exception + { + int endIndex = numbers.length - 1; + int startIndex = 0; + int sumLeft = 0; + int sumRight = 0; + while (true) + { + if (sumLeft > sumRight) + { + sumRight += numbers[endIndex--]; + } + else + { + sumLeft += numbers[startIndex++]; + } + if (startIndex > endIndex) + { + if (sumLeft == sumRight) + { + break; + } + else + { + throw new Exception( + "Please pass proper array to match the requirement"); + } + } + } + return endIndex; + } + + public static void main(String a[]) + { + int[] num = { 2, 4, 4, 5, 4, 1 }; + try + { + System.out.println("Starting from index 0, adding numbers till index " + + findMiddleIndex(num) + " and"); + System.out.println("adding rest of the numbers can be equal"); + } + catch (Exception ex) + { + System.out.println(ex.getMessage()); + } + } +} \ No newline at end of file diff --git a/java/Basics/Program to Get distinct elements from an array by avoiding duplicate elements (Java).java b/java/Basics/Program to Get distinct elements from an array by avoiding duplicate elements (Java).java new file mode 100644 index 0000000..a369291 --- /dev/null +++ b/java/Basics/Program to Get distinct elements from an array by avoiding duplicate elements (Java).java @@ -0,0 +1,33 @@ +/* +The below example shows how to avoid duplicate elements from an array and disply only distinct elements. Please use only arrays to process it. +*/ + +public class MyDisticntElements +{ + + public static void printDistinctElements(int[] arr) + { + for(int i=0; i +{ + + private Node head; + + public void add(T element) + { + Node nd = new Node(); + nd.setValue(element); + System.out.println("Adding: "+element); + Node tmp = head; + while(true) + { + if(tmp == null) + { + //since there is only one element, both head and + //tail points to the same object. + head = nd; + break; + } + else if(tmp.getNextRef() == null) + { + tmp.setNextRef(nd); + break; + } + else + { + tmp = tmp.getNextRef(); + } + } + } + + public void traverse() + { + Node tmp = head; + while(true) + { + if(tmp == null) + { + break; + } + System.out.print(tmp.getValue()+"\t"); + tmp = tmp.getNextRef(); + } + } + + public void reverse() + { + System.out.println("\nreversing the linked list\n"); + Node prev = null; + Node current = head; + Node next = null; + while(current != null) + { + next = current.getNextRef(); + current.setNextRef(prev); + prev = current; + current = next; + } + head = prev; + } + + public static void main(String a[]) + { + SinglyLinkedListImpl sl = new SinglyLinkedListImpl(); + sl.add(3); + sl.add(32); + sl.add(54); + sl.add(89); + System.out.println(); + sl.traverse(); + System.out.println(); + sl.reverse(); + sl.traverse(); + } +} + +class Node implements Comparable +{ + + private T value; + private Node nextRef; + + public T getValue() + { + return value; + } + public void setValue(T value) + { + this.value = value; + } + public Node getNextRef() + { + return nextRef; + } + public void setNextRef(Node ref) + { + this.nextRef = ref; + } + @Override + public int compareTo(T arg) + { + if(arg == this.value) + { + return 0; + } + else + { + return 1; + } + } +} \ No newline at end of file diff --git a/java/Basics/Program to ReverseNumber (Java) v2.java b/java/Basics/Program to ReverseNumber (Java) v2.java new file mode 100644 index 0000000..2262229 --- /dev/null +++ b/java/Basics/Program to ReverseNumber (Java) v2.java @@ -0,0 +1,20 @@ +public class NumberReverse +{ + + public int reverseNumber(int number) + { + int reverse = 0; + while(number != 0) + { + reverse = (reverse*10)+(number%10); + number = number/10; + } + return reverse; + } + + public static void main(String a[]) + { + NumberReverse nr = new NumberReverse(); + System.out.println("Result: "+nr.reverseNumber(17868)); + } +} \ No newline at end of file diff --git a/java/Basics/Program to ReverseNumber (Java).java b/java/Basics/Program to ReverseNumber (Java).java new file mode 100644 index 0000000..1871e8a --- /dev/null +++ b/java/Basics/Program to ReverseNumber (Java).java @@ -0,0 +1,31 @@ +/* + Reverse Number using Java + This Java Reverse Number Example shows how to reverse a given number. +*/ + +public class ReverseNumber +{ + + public static void main(String[] args) + { + //original number + int number = 1234; + int reversedNumber = 0; + int temp = 0; + while(number > 0) + { + //use modulus operator to strip off the last digit + temp = number%10; + //create the reversed number + reversedNumber = reversedNumber * 10 + temp; + number = number/10; + } + //output the reversed number + System.out.println("Reversed Number is: " + reversedNumber); + } +} + +/* +Output of this Number Reverse program would be +Reversed Number is: 4321 +*/ \ No newline at end of file diff --git a/java/Basics/Program to Sort a Stack using a temporary Stack (Java).java b/java/Basics/Program to Sort a Stack using a temporary Stack (Java).java new file mode 100644 index 0000000..809b0e1 --- /dev/null +++ b/java/Basics/Program to Sort a Stack using a temporary Stack (Java).java @@ -0,0 +1,42 @@ +/* +You have a stack with full of integers. Sort it in the ascending order using another temporary array by using all stack functionality. +*/ + +import java.util.Stack; + +public class StackSort +{ + + public static Stack sortStack(Stack input) + { + Stack tmpStack = new Stack(); + System.out.println("=============== debug logs ================"); + while(!input.isEmpty()) + { + int tmp = input.pop(); + System.out.println("Element taken out: "+tmp); + while(!tmpStack.isEmpty() && tmpStack.peek() > tmp) + { + input.push(tmpStack.pop()); + } + tmpStack.push(tmp); + System.out.println("input: "+input); + System.out.println("tmpStack: "+tmpStack); + } + System.out.println("=============== debug logs ended ================"); + return tmpStack; + } + + public static void main(String a[]) + { + Stack input = new Stack(); + input.add(34); + input.add(3); + input.add(31); + input.add(98); + input.add(92); + input.add(23); + System.out.println("input: "+input); + System.out.println("final sorted list: "+sortStack(input)); + } +} \ No newline at end of file diff --git a/java/Basics/Program to Swap Elements (Java).java b/java/Basics/Program to Swap Elements (Java).java new file mode 100644 index 0000000..d0ff543 --- /dev/null +++ b/java/Basics/Program to Swap Elements (Java).java @@ -0,0 +1,40 @@ +/* + Swap Numbers Java Example + This Swap Numbers Java Example shows how to + swap value of two numbers using java. +*/ + +public class SwapElementsExample +{ + + public static void main(String[] args) + { + int num1 = 10; + int num2 = 20; + System.out.println("Before Swapping"); + System.out.println("Value of num1 is :" + num1); + System.out.println("Value of num2 is :" +num2); + //swap the value + swap(num1, num2); + } + + private static void swap(int num1, int num2) + { + int temp = num1; + num1 = num2; + num2 = temp; + System.out.println("After Swapping"); + System.out.println("Value of num1 is :" + num1); + System.out.println("Value of num2 is :" +num2); + } +} + +/* +Output of Swap Numbers example would be +Before Swapping +Value of num1 is :10 +Value of num2 is :20 +After Swapping +Value of num1 is :20 +Value of num2 is :10 +*/ \ No newline at end of file diff --git a/java/Basics/Program to Swap Elements Without Third Variable (Java).java b/java/Basics/Program to Swap Elements Without Third Variable (Java).java new file mode 100644 index 0000000..65404df --- /dev/null +++ b/java/Basics/Program to Swap Elements Without Third Variable (Java).java @@ -0,0 +1,37 @@ +/* + Swap Numbers Without Using Third Variable Java Example + This Swap Numbers Java Example shows how to + swap value of two numbers without using third variable using java. +*/ + +public class SwapElementsWithoutThirdVariableExample +{ + + public static void main(String[] args) + { + int num1 = 10; + int num2 = 20; + System.out.println("Before Swapping"); + System.out.println("Value of num1 is :" + num1); + System.out.println("Value of num2 is :" +num2); + //add both the numbers and assign it to first + num1 = num1 + num2; + num2 = num1 - num2; + num1 = num1 - num2; + System.out.println("Before Swapping"); + System.out.println("Value of num1 is :" + num1); + System.out.println("Value of num2 is :" +num2); + } + + +} + +/* +Output of Swap Numbers Without Using Third Variable example would be +Before Swapping +Value of num1 is :10 +Value of num2 is :20 +Before Swapping +Value of num1 is :20 +Value of num2 is :10 +*/ \ No newline at end of file diff --git a/java/Basics/Program to Write a singleton class (Java).java b/java/Basics/Program to Write a singleton class (Java).java new file mode 100644 index 0000000..9a1600c --- /dev/null +++ b/java/Basics/Program to Write a singleton class (Java).java @@ -0,0 +1,39 @@ +/* +Singleton class means you can create only one object for the given class. +You can create a singleton class by making its constructor as private, +so that you can restrict the creation of the object. +Provide a static method to get instance of the object, wherein you can handle +the object creation inside the class only. In this example we are creating +object by using static block. +*/ + +public class MySingleton +{ + + private static MySingleton myObj; + + static + { + myObj = new MySingleton(); + } + + private MySingleton() + { + } + + public static MySingleton getInstance() + { + return myObj; + } + + public void testMe() + { + System.out.println("Hey.... it is working!!!"); + } + + public static void main(String a[]) + { + MySingleton ms = getInstance(); + ms.testMe(); + } +} \ No newline at end of file diff --git a/java/Basics/Program to check the given number is binary number or not (Java).java b/java/Basics/Program to check the given number is binary number or not (Java).java new file mode 100644 index 0000000..669a2dc --- /dev/null +++ b/java/Basics/Program to check the given number is binary number or not (Java).java @@ -0,0 +1,38 @@ +/* +The binary numeral system, or base-2 number system, represents numeric values using two symbols: 0 and 1. More specifically, the usual base-2 system is a positional notation with a radix of 2. Because of its straightforward implementation in digital electronic circuitry using logic gates, the binary system is used internally by almost all modern computers. + +*/ + +public class MyBinaryCheck +{ + + public boolean isBinaryNumber(int binary) + { + boolean status = true; + while(true) + { + if(binary == 0) + { + break; + } + else + { + int tmp = binary%10; + if(tmp > 1) + { + status = false; + break; + } + binary = binary/10; + } + } + return status; + } + + public static void main(String a[]) + { + MyBinaryCheck mbc = new MyBinaryCheck(); + System.out.println("Is 1000111 binary? :"+mbc.isBinaryNumber(1000111)); + System.out.println("Is 10300111 binary? :"+mbc.isBinaryNumber(10300111)); + } +} \ No newline at end of file diff --git a/java/Basics/Program to check the input characcter for uppercas.java b/java/Basics/Program to check the input characcter for uppercas.java new file mode 100644 index 0000000..ae8eb57 --- /dev/null +++ b/java/Basics/Program to check the input characcter for uppercas.java @@ -0,0 +1,46 @@ +Program to check the input characcter for uppercase, lowercase, no. of digits +and other characters + +import java.io.*; + +class InputDiagnosis{ + + public static void main(String args[]) throws IOException + { + char ch; + int digit=0; + int upper=0; + int lower=0; + int other=0; + + BufferedReader inputstream =new BufferedReader(new InputStreamReader(System.in)); + + System.out.println(" + + Type some text. When done, press Enter to Quit:"); + + + do{ + + ch=(char) inputstream.read(); + + if(Character.isDigit(ch)) + digit++; + else if(Character.isUpperCase(ch)) + upper++; + else if(Character.isLowerCase(ch)) + lower++; + else + other++; + + }while(ch !=' +'); + + + System.out.println("No Of Digits:" +digit); + System.out.println("No Of Uppercase Characters:" +upper); + System.out.println("No Of Lowercase Characters:" +lower); + System.out.println("No Of Other Characters:" +other); + + } + } diff --git a/java/Basics/Program to convert binary to decimal number. (Java).java b/java/Basics/Program to convert binary to decimal number. (Java).java new file mode 100644 index 0000000..66a6858 --- /dev/null +++ b/java/Basics/Program to convert binary to decimal number. (Java).java @@ -0,0 +1,36 @@ +/* +Write a program to convert binary format to decimal number using numeric operations. Below example shows how to convert binary to decimal format using numeric operations. +*/ + +public class BinaryToDecimal +{ + + public int getDecimalFromBinary(int binary) + { + int decimal = 0; + int power = 0; + while(true) + { + if(binary == 0) + { + break; + } + else + { + int tmp = binary%10; + decimal += tmp*Math.pow(2, power); + binary = binary/10; + power++; + } + } + return decimal; + } + + public static void main(String a[]) + { + BinaryToDecimal bd = new BinaryToDecimal(); + System.out.println("11 ===> "+bd.getDecimalFromBinary(11)); + System.out.println("110 ===> "+bd.getDecimalFromBinary(110)); + System.out.println("100110 ===> "+bd.getDecimalFromBinary(100110)); + } +} \ No newline at end of file diff --git a/java/Basics/Program to convert decimal number to binary format. (Java).java b/java/Basics/Program to convert decimal number to binary format. (Java).java new file mode 100644 index 0000000..8ea92a1 --- /dev/null +++ b/java/Basics/Program to convert decimal number to binary format. (Java).java @@ -0,0 +1,28 @@ +/* +Write a program to convert decimal number to binary format using numeric operations. Below example shows how to convert decimal number to binary format using numeric operations. +*/ + +public class DecimalToBinary +{ + + public void printBinaryFormat(int number) + { + int binary[] = new int[25]; + int index = 0; + while(number > 0) + { + binary[index++] = number%2; + number = number/2; + } + for(int i = index-1; i >= 0; i--) + { + System.out.print(binary[i]); + } + } + + public static void main(String a[]) + { + DecimalToBinary dtb = new DecimalToBinary(); + dtb.printBinaryFormat(25); + } +} \ No newline at end of file diff --git a/java/Basics/Program to convert string to number without using Integer.parseInt() method (Java).java b/java/Basics/Program to convert string to number without using Integer.parseInt() method (Java).java new file mode 100644 index 0000000..dca2a6a --- /dev/null +++ b/java/Basics/Program to convert string to number without using Integer.parseInt() method (Java).java @@ -0,0 +1,28 @@ +/* +Below example shows how to convert string format of a number to number without calling Integer.parseInt() method. We can do this by converting each character into ascii format and form the number. +*/ + +public class MyStringToNumber +{ + + public static int convert_String_To_Number(String numStr) + { + char ch[] = numStr.toCharArray(); + int sum = 0; + //get ascii value for zero + int zeroAscii = (int)'0'; + for(char c:ch) + { + int tmpAscii = (int)c; + sum = (sum*10)+(tmpAscii-zeroAscii); + } + return sum; + } + + public static void main(String a[]) + { + System.out.println("\"3256\" == "+convert_String_To_Number("3256")); + System.out.println("\"76289\" == "+convert_String_To_Number("76289")); + System.out.println("\"90087\" == "+convert_String_To_Number("90087")); + } +} \ No newline at end of file diff --git a/java/Basics/Program to create GUI for Bank Account Simulation.java b/java/Basics/Program to create GUI for Bank Account Simulation.java new file mode 100644 index 0000000..c78e6fc --- /dev/null +++ b/java/Basics/Program to create GUI for Bank Account Simulation.java @@ -0,0 +1,135 @@ +// Program to create GUI for Bank Account Simulation + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +class GuiAccTest extends Frame implements ActionListener +{ + Label lab=new Label(" "); + Label lab1=new Label(" "); + TextField t[]=new TextField [4]; + Label l[]=new Label [4]; + Button but=new Button("Create Account"); + Button but1=new Button("Test Account"); + BankAccount b; + GuiAccTest() + { + addWindowListener(new NewWindowAdapter()); + setLayout(new GridLayout(2,0)); + Panel p=new Panel(); + Panel p1=new Panel(); + but.addActionListener(this); + but1.addActionListener(this); + p.setLayout(new GridLayout(5,2)); + p1.add(lab1); + p1.add(lab); + l[0]=new Label("Account Number"); + l[1]=new Label("Initial Balance"); + l[2]=new Label("Deposit Amount"); + l[3]=new Label("Withdraw Amount"); + for(int i=0;i<4;i++) + { + t[i]=new TextField(10); + p.add(l[i]); + p.add(t[i]); + } + p.add(but); + p.add(but1); + but1.setVisible(false); + l[2].setVisible(false); + l[3].setVisible(false); + t[2].setVisible(false); + t[3].setVisible(false); + add(p); + add(p1); + } + String testAccount(int d_amt,int w_amt) + { + String msg; + b.deposit(d_amt); + msg="Transaction Succesful"; + try + { + b.withdraw(w_amt); + }catch(FundsInsufficientException fe) + { + fe=new FundsInsufficientException(b.amount,w_amt); + msg=String.valueOf(fe); + } + return msg; + } + public void actionPerformed(ActionEvent ae) + { + String str=ae.getActionCommand(); + if(str.equals("Create Account")) + { + b=new BankAccount(Integer.parseInt(t[0].getText()),Integer.parseInt(t[1].getText())); + but1.setVisible(true); + l[2].setVisible(true); + l[3].setVisible(true); + t[2].setVisible(true); + t[3].setVisible(true); + but.setVisible(false); + l[0].setVisible(false); + l[1].setVisible(false); + t[0].setVisible(false); + t[1].setVisible(false); + lab1.setText("Account : "+b.accnum+", Current Balance : "+b.amount); + return; + } + else + { + lab.setText(testAccount(Integer.parseInt(t[2].getText()),Integer.parseInt(t[3].getText()))); + lab1.setText("Account : "+b.accnum+", Current Balance : "+b.amount); + } + } + public static void main(String arg[]) + { + GuiAccTest at=new GuiAccTest(); + at.setTitle("Bank Account Tester"); + at.setSize(600,200); + at.setVisible(true); + } +} +class NewWindowAdapter extends WindowAdapter +{ + public void windowClosing(WindowEvent we) + { + System.exit(0); + } +} +class BankAccount +{ + int accnum; + int amount; + BankAccount(int num,int amt) + { + accnum=num; + amount=amt; + } + public void deposit(int amt) + { + amount=amount+amt; + } + public void withdraw(int amt) throws FundsInsufficientException + { + if(amt>amount) + throw new FundsInsufficientException(amount,amt); + else + amount=amount-amt; + } +} +class FundsInsufficientException extends Exception +{ + int balance; + int withdraw_amount; + FundsInsufficientException(int bal,int w_amt) + { + balance=bal; + withdraw_amount=w_amt; + } + public String toString() + { + return "Your withdraw amount ("+withdraw_amount+") is less than the balance ("+balance+"). No withdrawal was recorded."; + } +} diff --git a/java/Basics/Program to create deadlock between two threads. (Java).java b/java/Basics/Program to create deadlock between two threads. (Java).java new file mode 100644 index 0000000..2b67466 --- /dev/null +++ b/java/Basics/Program to create deadlock between two threads. (Java).java @@ -0,0 +1,57 @@ +/* +Deadlock describes a situation where two or more threads are blocked forever, + waiting for each other. Deadlocks can occur in Java when the synchronized + keyword causes the executing thread to block while waiting to get the lock, + associated with the specified object. Since the thread might already hold + locks associated with other objects, two threads could each be waiting for + the other to release a lock. +In such case, they will end up waiting forever. +*/ + +public class MyDeadlock +{ + + String str1 = "Java"; + String str2 = "UNIX"; + + Thread trd1 = new Thread("My Thread 1") + { + public void run() + { + while(true) + { + synchronized(str1) + { + synchronized(str2) + { + System.out.println(str1 + str2); + } + } + } + } + }; + + Thread trd2 = new Thread("My Thread 2") + { + public void run() + { + while(true) + { + synchronized(str2) + { + synchronized(str1) + { + System.out.println(str2 + str1); + } + } + } + } + }; + + public static void main(String a[]) + { + MyDeadlock mdl = new MyDeadlock(); + mdl.trd1.start(); + mdl.trd2.start(); + } +} \ No newline at end of file diff --git a/java/Basics/Program to determine if a number is Prime (Java).java b/java/Basics/Program to determine if a number is Prime (Java).java new file mode 100644 index 0000000..0c68f42 --- /dev/null +++ b/java/Basics/Program to determine if a number is Prime (Java).java @@ -0,0 +1,20 @@ +class PrimeExample +{ + public static void main(String args[]) + { + int i,m=0,flag=0; + int n=17;//it is the number to be checked + m=n/2; + for(i=2; i<=m; i++) + { + if(n%i==0) + { + System.out.println("Number is not prime"); + flag=1; + break; + } + } + if(flag==0) + System.out.println("Number is prime"); + } +} \ No newline at end of file diff --git a/java/Basics/Program to find all distinct words from the given file. Remove special chars. (Java).java b/java/Basics/Program to find all distinct words from the given file. Remove special chars. (Java).java new file mode 100644 index 0000000..b49528a --- /dev/null +++ b/java/Basics/Program to find all distinct words from the given file. Remove special chars. (Java).java @@ -0,0 +1,71 @@ +/* +Write a program to find all distinct words from the given file. Remove special chars like ".,;:" etc. Ignore case sensitivity. +*/ + +import java.io.BufferedReader; +import java.io.DataInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +public class MyDistinctFileWords +{ + + public List getDistinctWordList(String fileName) + { + FileInputStream fis = null; + DataInputStream dis = null; + BufferedReader br = null; + List wordList = new ArrayList(); + try + { + fis = new FileInputStream(fileName); + dis = new DataInputStream(fis); + br = new BufferedReader(new InputStreamReader(dis)); + String line = null; + while((line = br.readLine()) != null) + { + StringTokenizer st = new StringTokenizer(line, " ,.;:\""); + while(st.hasMoreTokens()) + { + String tmp = st.nextToken().toLowerCase(); + if(!wordList.contains(tmp)) + { + wordList.add(tmp); + } + } + } + } + catch (FileNotFoundException e) + { + e.printStackTrace(); + } + catch (IOException e) + { + e.printStackTrace(); + } + finally + { + try + { + if(br != null) br.close(); + } + catch(Exception ex) {} + } + return wordList; + } + + public static void main(String a[]) + { + MyDistinctFileWords distFw = new MyDistinctFileWords(); + List wordList = distFw.getDistinctWordList("C:/sample.txt"); + for(String str:wordList) + { + System.out.println(str); + } + } +} \ No newline at end of file diff --git a/java/Basics/Program to find common elements between two arrays. (Java).java b/java/Basics/Program to find common elements between two arrays. (Java).java new file mode 100644 index 0000000..6345716 --- /dev/null +++ b/java/Basics/Program to find common elements between two arrays. (Java).java @@ -0,0 +1,26 @@ +/* +Write a program to identify common elements or numbers between +two given arrays. You should not use any inbuilt methods are list to +find common values. +*/ + + +public class CommonElementsInArray +{ + + public static void main(String a[]) + { + int[] arr1 = {4,7,3,9,2}; + int[] arr2 = {3,2,12,9,40,32,4}; + for(int i=0; i getWordCount(String fileName) + { + FileInputStream fis = null; + DataInputStream dis = null; + BufferedReader br = null; + Map wordMap = new HashMap(); + try + { + fis = new FileInputStream(fileName); + dis = new DataInputStream(fis); + br = new BufferedReader(new InputStreamReader(dis)); + String line = null; + while((line = br.readLine()) != null) + { + StringTokenizer st = new StringTokenizer(line, " "); + while(st.hasMoreTokens()) + { + String tmp = st.nextToken().toLowerCase(); + if(wordMap.containsKey(tmp)) + { + wordMap.put(tmp, wordMap.get(tmp)+1); + } + else + { + wordMap.put(tmp, 1); + } + } + } + } + catch (FileNotFoundException e) + { + e.printStackTrace(); + } + catch (IOException e) + { + e.printStackTrace(); + } + finally + { + try + { + if(br != null) br.close(); + } + catch(Exception ex) {} + } + return wordMap; + } + + public List> sortByValue(Map wordMap) + { + Set> set = wordMap.entrySet(); + List> list = new ArrayList>(set); + Collections.sort( list, new Comparator>() + { + public int compare( Map.Entry o1, Map.Entry o2 ) + { + return (o2.getValue()).compareTo( o1.getValue() ); + } + } ); + return list; + } + + public static void main(String a[]) + { + MaxDuplicateWordCount mdc = new MaxDuplicateWordCount(); + Map wordMap = mdc.getWordCount("C:/MyTestFile.txt"); + List> list = mdc.sortByValue(wordMap); + for(Map.Entry entry:list) + { + System.out.println(entry.getKey()+" ==== "+entry.getValue()); + } + } +} diff --git a/java/Basics/Program to find missing numbers in an array (Java).java b/java/Basics/Program to find missing numbers in an array (Java).java new file mode 100644 index 0000000..081aa2c --- /dev/null +++ b/java/Basics/Program to find missing numbers in an array (Java).java @@ -0,0 +1,53 @@ +/* +To find missing numbers in an array first we need to make sure that array is sorted. +After sorting we need to check that array each element with next element then we can find the difference. +if Array is not sorted :To sort array use Arrays.sort(array); +If difference is 1 then no need to do any thing because numbers are in order. +If difference is not equal to 1 then we need to print all those numbers or pick those numbers and place it in one array. +this would be the logic to find missing numbers in an array +Here there may be a chance of array not starts with 1 then we need to check first itself whether array starts with 1 or not if not we need to print 1 to starting element of array. +for example int a[]={4,5,6,8}; then we need to print 1 2 3 7. +*/ + +public class PrintMissingNumbers +{ + + private static void findMissingNumber(int[] number) + { + // take max length as last number in array + int k[] = new int[number[number.length-1]]; + int m=0; + if(number[0]!=1) + { + for (int x = 1; x < number[0]; x++) + { + k[m] = x; + m++; + } + } + for (int i = 0; i < number.length -1; i++) + { + int j = i+1; + int difference = number[j] - number[i] ; + if(difference != 1 ) + { + for (int x = 1; x < difference; x++) + { + k[m] = number[i] + x; + m++; + } + } + } + System.out.println("missing numbers in array ::"); + for (int l = 0; l < m ; l++) + { + System.out.println( k[l]+" "); + } + } + public static void main(String[] args) + { + int a[]= {2,4,6,9,10,20}; + //if Array is not sorted :To sort array use ArraysC.sort(a); + findMissingNumber(a); + } +} \ No newline at end of file diff --git a/java/Basics/Program to find out duplicate characters in a string. (Java).java b/java/Basics/Program to find out duplicate characters in a string. (Java).java new file mode 100644 index 0000000..25295f2 --- /dev/null +++ b/java/Basics/Program to find out duplicate characters in a string. (Java).java @@ -0,0 +1,43 @@ +/* +Write a program to find out duplicate or repeated characters in a +string, and calculate the count of repeatation. +*/ + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class DuplicateCharsInString +{ + + public void findDuplicateChars(String str) + { + Map dupMap = new HashMap(); + char[] chrs = str.toCharArray(); + for(Character ch:chrs) + { + if(dupMap.containsKey(ch)) + { + dupMap.put(ch, dupMap.get(ch)+1); + } + else + { + dupMap.put(ch, 1); + } + } + Set keys = dupMap.keySet(); + for(Character ch:keys) + { + if(dupMap.get(ch) > 1) + { + System.out.println(ch+"--->"+dupMap.get(ch)); + } + } + } + + public static void main(String a[]) + { + DuplicateCharsInString dcs = new DuplicateCharsInString(); + dcs.findDuplicateChars("Java2Novice"); + } +} \ No newline at end of file diff --git a/java/Basics/Program to find perfect number or not. (Java).java b/java/Basics/Program to find perfect number or not. (Java).java new file mode 100644 index 0000000..a6ef3d9 --- /dev/null +++ b/java/Basics/Program to find perfect number or not. (Java).java @@ -0,0 +1,42 @@ +/* +A perfect number is a positive integer that is equal to the sum +of its proper positive divisors, that is, the sum of its positive +divisors excluding the number itself. Equivalently, a perfect number +is a number that is half the sum of all of its positive divisors. +The first perfect number is 6, because 1, 2 and 3 are its proper +positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6 +is equal to half the sum of all its positive divisors: + ( 1 + 2 + 3 + 6 ) / 2 = 6. +*/ + +public class IsPerfectNumber +{ + + public boolean isPerfectNumber(int number) + { + int temp = 0; + for(int i=1; i<=number/2; i++) + { + if(number%i == 0) + { + temp += i; + } + } + if(temp == number) + { + System.out.println("It is a perfect number"); + return true; + } + else + { + System.out.println("It is not a perfect number"); + return false; + } + } + + public static void main(String a[]) + { + IsPerfectNumber ipn = new IsPerfectNumber(); + System.out.println("Is perfect number: "+ipn.isPerfectNumber(28)); + } +} \ No newline at end of file diff --git a/java/Basics/Program to find sum of each digit in the given number using recursion. (Java).java b/java/Basics/Program to find sum of each digit in the given number using recursion. (Java).java new file mode 100644 index 0000000..e28d023 --- /dev/null +++ b/java/Basics/Program to find sum of each digit in the given number using recursion. (Java).java @@ -0,0 +1,30 @@ +/* +Below example shows how to find out sum of each digit in the given number using recursion logic. For example, if the number is 259, then the sum should be 2+5+9 = 16. +*/ + + +public class MyNumberSumRec +{ + + int sum = 0; + + public int getNumberSum(int number) + { + if(number == 0) + { + return sum; + } + else + { + sum += (number%10); + getNumberSum(number/10); + } + return sum; + } + + public static void main(String a[]) + { + MyNumberSumRec mns = new MyNumberSumRec(); + System.out.println("Sum is: "+mns.getNumberSum(223)); + } +} \ No newline at end of file diff --git a/java/Basics/Program to find the sum of the first 1000 prime numbers (Java).java b/java/Basics/Program to find the sum of the first 1000 prime numbers (Java).java new file mode 100644 index 0000000..cb41af7 --- /dev/null +++ b/java/Basics/Program to find the sum of the first 1000 prime numbers (Java).java @@ -0,0 +1,35 @@ +/* +Program to find the sum of the first 1000 prime numbers. +*/ +public class Main +{ + + public static void main(String args[]) + { + int number = 2; + int count = 0; + long sum = 0; + while(count < 1000) + { + if(isPrimeNumber(number)) + { + sum += number; + count++; + } + number++; + } + System.out.println(sum); + } + + private static boolean isPrimeNumber(int number) + { + for(int i=2; i<=number/2; i++) + { + if(number % i == 0) + { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/java/Basics/Program to find top two maximum numbers in a array. (Java).java b/java/Basics/Program to find top two maximum numbers in a array. (Java).java new file mode 100644 index 0000000..7b47100 --- /dev/null +++ b/java/Basics/Program to find top two maximum numbers in a array. (Java).java @@ -0,0 +1,42 @@ +/* +Write a program to find top two maximum numbers in the +given array. You should not use any sorting functions. You +should iterate the array only once. You should not use any +kind of collections in java. +*/ + +public class TwoMaxNumbers +{ + + public void printTwoMaxNumbers(int[] nums) + { + int maxOne = 0; + int maxTwo = 0; + for(int n:nums) + { + if(maxOne < n) + { + maxTwo = maxOne; + maxOne =n; + } + else if(maxTwo < n) + { + maxTwo = n; + } + } + System.out.println("First Max Number: "+maxOne); + System.out.println("Second Max Number: "+maxTwo); + } + + public static void main(String a[]) + { + int num[] = {5,34,78,2,45,1,99,23}; + TwoMaxNumbers tmn = new TwoMaxNumbers(); + tmn.printTwoMaxNumbers(num); + } +} + +/* +Output: +First Max Number: 99 +Second Max Number: 78 \ No newline at end of file diff --git a/java/Basics/Program to find two lines with max characters in descending order (Java).java b/java/Basics/Program to find two lines with max characters in descending order (Java).java new file mode 100644 index 0000000..b45bc50 --- /dev/null +++ b/java/Basics/Program to find two lines with max characters in descending order (Java).java @@ -0,0 +1,85 @@ +/* +Write a program to read a multiple line text file and write the 'N' longest lines to the output console, where the file to be read is specified as command line aruguments. The program should read an input file. The first line should contain the value of the number 'N' followed by multiple lines. 'N' should be a valid positive integer. +*/ +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.Comparator; +import java.util.Set; +import java.util.TreeSet; + +public class Main +{ + + public static void main(String[] args) + { + BufferedReader br = null; + String filePath = args[0]; + int topList = 0; + Set liSet = new TreeSet(new MyComp()); + try + { + br = new BufferedReader(new FileReader(new File(filePath))); + String line = br.readLine(); + topList = Integer.parseInt(line.trim()); + while((line = br.readLine()) != null) + { + line = line.trim(); + if(!"".equals(line)) + { + liSet.add(new Entries(line.length(), line)); + } + } + int count = 0; + for(Entries ent:liSet) + { + System.out.println(ent.line); + if(++count == topList) + { + break; + } + } + } + catch (FileNotFoundException e) + { + // TODO Auto-generated catch block + e.printStackTrace(); + } + catch (IOException e) + { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public static class Entries + { + Integer length; + String line; + public Entries(Integer l,String line) + { + length = l; + this.line = line; + } + } + + public static class MyComp implements Comparator + { + + @Override + public int compare(Entries e1, Entries e2) + { + if(e2.length > e1.length) + { + return 1; + } + else + { + return -1; + } + } + + } +} \ No newline at end of file diff --git a/java/Basics/Program to get a line with max word count from the given file. (Java).java b/java/Basics/Program to get a line with max word count from the given file. (Java).java new file mode 100644 index 0000000..fdb4035 --- /dev/null +++ b/java/Basics/Program to get a line with max word count from the given file. (Java).java @@ -0,0 +1,97 @@ +/* +Below example shows how to find out the line with maximum number of word count in the given file. In case if it has multiple lines with max number of words, then it has to list all those lines. +*/ + + +import java.io.BufferedReader; +import java.io.DataInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; + +public class MaxWordCountInLine +{ + + private int currentMaxCount = 0; + private List lines = new ArrayList(); + + public void readMaxLineCount(String fileName) + { + FileInputStream fis = null; + DataInputStream dis = null; + BufferedReader br = null; + try + { + fis = new FileInputStream(fileName); + dis = new DataInputStream(fis); + br = new BufferedReader(new InputStreamReader(dis)); + String line = null; + while((line = br.readLine()) != null) + { + int count = (line.split("\\s+")).length; + if(count > currentMaxCount) + { + lines.clear(); + lines.add(line); + currentMaxCount = count; + } + else if(count == currentMaxCount) + { + lines.add(line); + } + } + } + catch (FileNotFoundException e) + { + e.printStackTrace(); + } + catch (IOException e) + { + e.printStackTrace(); + } + finally + { + try + { + if(br != null) br.close(); + } + catch(Exception ex) {} + } + } + + public int getCurrentMaxCount() + { + return currentMaxCount; + } + + public void setCurrentMaxCount(int currentMaxCount) + { + this.currentMaxCount = currentMaxCount; + } + + public List getLines() + { + return lines; + } + + public void setLines(List lines) + { + this.lines = lines; + } + + public static void main(String a[]) + { + MaxWordCountInLine mdc = new MaxWordCountInLine(); + mdc.readMaxLineCount("/Users/ngootooru/MyTestFile.txt"); + System.out.println("Max number of words in a line is: "+mdc.getCurrentMaxCount()); + System.out.println("Line with max word count:"); + List lines = mdc.getLines(); + for(String l:lines) + { + System.out.println(l); + } + } +} \ No newline at end of file diff --git a/java/Basics/Program to get distinct word list from the given file. (Java).java b/java/Basics/Program to get distinct word list from the given file. (Java).java new file mode 100644 index 0000000..b49528a --- /dev/null +++ b/java/Basics/Program to get distinct word list from the given file. (Java).java @@ -0,0 +1,71 @@ +/* +Write a program to find all distinct words from the given file. Remove special chars like ".,;:" etc. Ignore case sensitivity. +*/ + +import java.io.BufferedReader; +import java.io.DataInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +public class MyDistinctFileWords +{ + + public List getDistinctWordList(String fileName) + { + FileInputStream fis = null; + DataInputStream dis = null; + BufferedReader br = null; + List wordList = new ArrayList(); + try + { + fis = new FileInputStream(fileName); + dis = new DataInputStream(fis); + br = new BufferedReader(new InputStreamReader(dis)); + String line = null; + while((line = br.readLine()) != null) + { + StringTokenizer st = new StringTokenizer(line, " ,.;:\""); + while(st.hasMoreTokens()) + { + String tmp = st.nextToken().toLowerCase(); + if(!wordList.contains(tmp)) + { + wordList.add(tmp); + } + } + } + } + catch (FileNotFoundException e) + { + e.printStackTrace(); + } + catch (IOException e) + { + e.printStackTrace(); + } + finally + { + try + { + if(br != null) br.close(); + } + catch(Exception ex) {} + } + return wordList; + } + + public static void main(String a[]) + { + MyDistinctFileWords distFw = new MyDistinctFileWords(); + List wordList = distFw.getDistinctWordList("C:/sample.txt"); + for(String str:wordList) + { + System.out.println(str); + } + } +} \ No newline at end of file diff --git a/java/Basics/Program to implement ArrayList (Java).java b/java/Basics/Program to implement ArrayList (Java).java new file mode 100644 index 0000000..2abc6fb --- /dev/null +++ b/java/Basics/Program to implement ArrayList (Java).java @@ -0,0 +1,105 @@ +/* +Write a program to implement your own ArrayList class. It should +contain add(), get(), remove(), size() methods. Use dynamic array logic. +It should increase its size when it reaches threshold. +*/ + + +import java.util.Arrays; + +public class MyArrayList +{ + + private Object[] myStore; + private int actSize = 0; + + public MyArrayList() + { + myStore = new Object[10]; + } + + public Object get(int index) + { + if(index < actSize) + { + return myStore[index]; + } + else + { + throw new ArrayIndexOutOfBoundsException(); + } + } + + public void add(Object obj) + { + if(myStore.length-actSize <= 5) + { + increaseListSize(); + } + myStore[actSize++] = obj; + } + + public Object remove(int index) + { + if(index < actSize) + { + Object obj = myStore[index]; + myStore[index] = null; + int tmp = index; + while(tmp < actSize) + { + myStore[tmp] = myStore[tmp+1]; + myStore[tmp+1] = null; + tmp++; + } + actSize--; + return obj; + } + else + { + throw new ArrayIndexOutOfBoundsException(); + } + } + + public int size() + { + return actSize; + } + + private void increaseListSize() + { + myStore = Arrays.copyOf(myStore, myStore.length*2); + System.out.println("\nNew length: "+myStore.length); + } + + public static void main(String a[]) + { + MyArrayList mal = new MyArrayList(); + mal.add(new Integer(2)); + mal.add(new Integer(5)); + mal.add(new Integer(1)); + mal.add(new Integer(23)); + mal.add(new Integer(14)); + for(int i=0; i hm = new HashMap(); + hm.put(new Price("Banana", 20), "Banana"); + hm.put(new Price("Apple", 40), "Apple"); + hm.put(new Price("Orange", 30), "Orange"); + //creating new object to use as key to get value + Price key = new Price("Banana", 20); + System.out.println("Hashcode of the key: "+key.hashCode()); + System.out.println("Value from map: "+hm.get(key)); + } +} + +class Price +{ + + private String item; + private int price; + + public Price(String itm, int pr) + { + this.item = itm; + this.price = pr; + } + + public int hashCode() + { + System.out.println("In hashcode"); + int hashcode = 0; + hashcode = price*20; + hashcode += item.hashCode(); + return hashcode; + } + + public boolean equals(Object obj) + { + System.out.println("In equals"); + if (obj instanceof Price) + { + Price pp = (Price) obj; + return (pp.item.equals(this.item) && pp.price == this.price); + } + else + { + return false; + } + } + + public String getItem() + { + return item; + } + public void setItem(String item) + { + this.item = item; + } + public int getPrice() + { + return price; + } + public void setPrice(int price) + { + this.price = price; + } + + public String toString() + { + return "item: "+item+" price: "+price; + } +} \ No newline at end of file diff --git a/java/Basics/Program to remove duplicates from sorted array. (Java).java b/java/Basics/Program to remove duplicates from sorted array. (Java).java new file mode 100644 index 0000000..13e0f94 --- /dev/null +++ b/java/Basics/Program to remove duplicates from sorted array. (Java).java @@ -0,0 +1,45 @@ +/* +Given array is already sorted, and it has duplicate elements. Write a program to remove duplicate elements and return new array without any duplicate elements. The array should contain only unique elements. +*/ + +public class MyDuplicateElements +{ + + public static int[] removeDuplicates(int[] input) + { + int j = 0; + int i = 1; + //return if the array length is less than 2 + if(input.length < 2) + { + return input; + } + while(i < input.length) + { + if(input[i] == input[j]) + { + i++; + } + else + { + input[++j] = input[i++]; + } + } + int[] output = new int[j+1]; + for(int k=0; k map = new HashMap(); + map.put("java", 20); + map.put("C++", 45); + map.put("Java2Novice", 2); + map.put("Unix", 67); + map.put("MAC", 26); + map.put("Why this kolavari", 93); + Set> set = map.entrySet(); + List> list = new ArrayList>(set); + Collections.sort( list, new Comparator>() + { + public int compare( Map.Entry o1, Map.Entry o2 ) + { + return (o2.getValue()).compareTo( o1.getValue() ); + } + } ); + for(Map.Entry entry:list) + { + System.out.println(entry.getKey()+" ==== "+entry.getValue()); + } + } +} diff --git a/java/Basics/Raise Exceptions.java b/java/Basics/Raise Exceptions.java new file mode 100644 index 0000000..d5469d7 --- /dev/null +++ b/java/Basics/Raise Exceptions.java @@ -0,0 +1,42 @@ +Raise Exceptions + + + + + +/** + * This example demonstrates how to catch + * multiple exceptions that are raised in + * a try block + */ +public class RaiseExceptions { + public static void main( String[] args ) { + try { + Integer.parseInt( "a" ); + double[] amounts = new double[-10]; + "hello".charAt( -1 ); + String str = args[6]; + ( (String) null ).length(); + int a = 3 / 0; + } + catch( NumberFormatException nfex ) { + System.out.println( nfex ); + } + catch( NegativeArraySizeException nasex ) { + System.out.println( nasex ); + } + catch( StringIndexOutOfBoundsException siex ) { + System.out.println( siex ); + } + catch( ArrayIndexOutOfBoundsException arex ) { + System.out.println( arex ); + } + catch( NullPointerException npex ) { + System.out.println( npex ); + } + catch( ArithmeticException aex ) { + System.out.println( aex ); + } + + } +} diff --git a/java/Basics/Rotation.java b/java/Basics/Rotation.java new file mode 100644 index 0000000..c92ebb0 --- /dev/null +++ b/java/Basics/Rotation.java @@ -0,0 +1,93 @@ +package com.jwetherell.algorithms.strings; + +/** + * Rotation of the string is some cyclic transformation of that string. + * More formally a string s = uv is said to be a rotation of t if t = vu. + *

+ * http://en.wikipedia.org/wiki/String_(computer_science)#Rotations + *
+ * @Author Szymon Stankiewicz + * @author Justin Wetherell + */ +public class Rotation { + + private static char charAt(String text, int pos) { + pos = pos % text.length(); + return text.charAt(pos); + } + + private static int compare(char a, char b, boolean greater) { + if (a == b) + return 0; + return (a < b) ^ greater ? -1 : 1; + } + + private static String bestRotation(String text, boolean greatest) { + if (text.length() < 2) + return text; + + final int n = text.length() * 2; + int k = 0; + int i = 0, j = 1; + while (i + k < n && j + k < n) { + final char a = charAt(text, i+k); + final char b = charAt(text, j+k); + final int comp = compare(a, b, greatest); + if (comp == 0) { + k++; + } else if (comp > 0) { + i += k+1; + if (i <= j ) + i = j + 1; + k = 0; + } else { + j += k+1; + if (j <= i) + j = i + 1; + k = 0; + } + } + final int pos = i < j ? i : j; + return text.substring(pos) + text.substring(0, pos); + } + + /** + * Finds lexicographically minimal string rotation. + * Lexicographically minimal string rotation is a rotation of a string possessing the + * lowest lexicographical order of all such rotations. + * Finding the lexicographically minimal rotation is useful as a way of normalizing strings. + *

+ * http://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation + *
+ * This function implements Duval's algorithm. + *
+ * http://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation#Duval.27s_Lyndon_Factorization_Algorithm + * Complexity: O(n) + *
+ * @param text + * @return lexicographicall minimal rotation of text + */ + public static String getLexicographicallyMinimalRotation(String text) { + return bestRotation(text, false); + } + + /** + * Finds lexicographically maximal string rotation. + * Lexicographically maximal string rotation is a rotation of a string possessing the + * highest lexicographical order of all such rotations. + * Finding the lexicographically maximal rotation is useful as a way of normalizing strings. + *

+ * http://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation + *
+ * This function implements Duval's algorithm. + * http://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation#Duval.27s_Lyndon_Factorization_Algorithm + *
+ * Complexity: O(n) + *
+ * @param text + * @return lexicographicall minimal rotation of text + */ + public static String getLexicographicallyMaximalRotation(String text) { + return bestRotation(text, true); + } +} diff --git a/java/Basics/School Management System.java b/java/Basics/School Management System.java new file mode 100644 index 0000000..590a8eb --- /dev/null +++ b/java/Basics/School Management System.java @@ -0,0 +1,405 @@ +School Management System + +import java.awt.*; +import java.io.*; +import java.util.*; +import javax.swing.*; +import javax.swing.event.*; +import java.awt.event.*; + +public class ProjectX extends JFrame implements ChangeListener, +ActionListener +{ + static int choice = 0; + static String line = "-------------------------------- +"; + DataInputStream inputData = new DataInputStream(System.in); + private Registration studentDetails = new Registration(); + int topScore = studentDetails.getTopScore(); + int passMarks = studentDetails.getPassMarks(); + int firstClass = studentDetails.getFirstClass(); + int secondClass = studentDetails.getSecondClass(); + + JTabbedPane tabbedPane = new JTabbedPane(); + JLabel statusLabel = new JLabel(); + JLabel titleLabel = new JLabel("Student Software Beta Edition"); + JPanel addStudentPanel = new JPanel(); + JTextField studentName = new JTextField(); + JTextField physicsMarks = new JTextField(); + JTextField biologyMarks = new JTextField(); + JTextField mathsMarks = new JTextField(); + JButton submitDetails = new JButton("Submit Details"); + JPanel studentDetailsPanel = new JPanel(); + JTextField studentID1 = new JTextField(); + JTextArea studentInfo = new JTextArea(); + JButton submitID1 = new JButton("Submit ID"); + JPanel studentGradePanel = new JPanel(); + JTextField studentID2 = new JTextField(); + JTextArea studentGrade = new JTextArea(); + JButton submitID2 = new JButton("Submit ID"); + JPanel numberPassedPanel = new JPanel(); + JTextArea studentPassed = new JTextArea(); + JPanel classTopperPanel = new JPanel(); + JTextArea studentTopper = new JTextArea(); + + public ProjectX(String frameTitle) + { + super(frameTitle); + setResizable(true); + setSize(400,400); + submitDetails.addActionListener(this); + submitID1.addActionListener(this); + submitID2.addActionListener(this); + + getContentPane().setLayout(new BorderLayout()); + + getContentPane().add(titleLabel,"North"); + + tabbedPane.addTab("Add Student",addStudentPanel); + addStudentPanel.setLayout(new GridLayout(8,2,5,5)); + addStudentPanel.add(new JLabel("Student Name: ")); + addStudentPanel.add(studentName); + addStudentPanel.add(new JLabel("Physics Marks: ")); + addStudentPanel.add(physicsMarks); + addStudentPanel.add(new JLabel("Biology Marks: ")); + addStudentPanel.add(biologyMarks); + addStudentPanel.add(new JLabel("Maths Marks: ")); + addStudentPanel.add(mathsMarks); + addStudentPanel.add(submitDetails); + + tabbedPane.addTab("Student Details",studentDetailsPanel); + studentDetailsPanel.add(new JLabel("Enter Student ID: ")); + studentDetailsPanel.add(studentID1); + studentDetailsPanel.add(submitID1); + studentDetailsPanel.add(new JLabel("Student Details:")); + studentDetailsPanel.add(studentInfo); + + tabbedPane.addTab("Student Grade",studentGradePanel); + studentGradePanel.setLayout(new GridLayout(5,2,5,5)); + studentGradePanel.add(new JLabel("Enter Student ID: ")); + studentGradePanel.add(studentID2); + studentGradePanel.add(submitID2); + studentGradePanel.add(new JLabel("Student Grade:")); + studentGradePanel.add(studentGrade); + + tabbedPane.addTab("Passed Student",numberPassedPanel); + numberPassedPanel.setLayout(new GridLayout(2,2,5,5)); + numberPassedPanel.add(new JLabel("Number of Student Passed: ")); + numberPassedPanel.add(studentPassed); + + tabbedPane.addTab("Class Topper",classTopperPanel); + classTopperPanel.setLayout(new GridLayout(2,2,5,5)); + classTopperPanel.add(new JLabel("Here are the class Toppers: ")); + classTopperPanel.add(studentTopper); + + tabbedPane.addChangeListener(this); + getContentPane().add(tabbedPane,"Center"); + + statusLabel.setText("Status: Normal"); + getContentPane().add(statusLabel,"South"); + + setVisible(true); + + } + + public static void main(String args[]) + { + ProjectX outputScreen = new ProjectX("Case Study"); + } + + public String setStudentInfo() + { + int id = studentDetails.addStudent(studentName.getText(), +Integer.parseInt(physicsMarks.getText()), +Integer.parseInt(biologyMarks.getText()), +Integer.parseInt(mathsMarks.getText())); + return (" +" + + line + + "Record Created For " + studentName + + " +" + + "Student ID: " + id + + " +" + + line ); + } + + public String getStudentInfo() + { + int id = Integer.parseInt(studentID1.getText()); + if(studentDetails.getStudentDetails(id)) + return (" +" + + line + + "Student Details +" + + line + + "Student ID:" + " " + id + " +" + + "Student Name:" + " " + studentDetails.studentName + " +" + + "Physics Marks:" + " " + studentDetails.physicsMarks + " +" + + "Biology Marks:" + " " + studentDetails.biologyMarks + " +" + + "Maths Marks:" + " " + studentDetails.mathsMarks + " +" + + line ); + else + return(" + Records Not Found for ID " + id); + } + + public String getStudentGrade() + { + int id = Integer.parseInt(studentID2.getText()); + studentDetails.getStudentDetails(id); + String grade; + if(studentDetails.studentName == null) + { + System.out.println(" + Records Not Found for ID " + id); + return null; + } + if(studentDetails.physicsMarks < passMarks || +studentDetails.biologyMarks < passMarks || studentDetails.mathsMarks < +passMarks) + { + grade = "Failed"; + } + else + { + int avgMarks = (studentDetails.physicsMarks + +studentDetails.biologyMarks + studentDetails.mathsMarks)/3; + if(avgMarks >= passMarks && avgMarks < secondClass) grade = "Pass +Class"; + else if(avgMarks >= secondClass && avgMarks < firstClass) grade = +"Second Class"; + else if(avgMarks >= firstClass && avgMarks < topScore) grade = "First +Class"; + else grade = "Distinction"; + } + return(line + "Grade For " + studentDetails.studentName + " is " + grade ++ " +" + line); + } + + public String getNumberPasses() + { + int lastID = Registration.getNextID() -1; + boolean passed = true; + int numberPassed = 0; + for(int id = 1; id <= lastID; id++) + { + studentDetails.getStudentDetails(id); + if(studentDetails.physicsMarks >= passMarks && +studentDetails.biologyMarks >= passMarks && studentDetails.mathsMarks >= +passMarks) numberPassed++; + } + return(line + "Number of Student Passed: " + numberPassed + " +" + +line); + } + + public String getClassTopper() + { + int lastID = Registration.getNextID() -1; + String classTopper; + StringBuffer buffer = new StringBuffer(500); + int topMarks = 0; + for(int id = 1; id <= lastID; id++) + { + studentDetails.getStudentDetails(id); + int studentMarks = studentDetails.physicsMarks + +studentDetails.biologyMarks + studentDetails.mathsMarks; + if(studentMarks > topMarks) topMarks = studentMarks; + } + buffer.append(line + "Student Having Top Marks: +"); + for(int id = 1; id <= lastID; id++) + { + studentDetails.getStudentDetails(id); + int studentMarks = studentDetails.physicsMarks + +studentDetails.biologyMarks + studentDetails.mathsMarks; + if(studentMarks == topMarks) + { + buffer.append(studentDetails.studentName + " Having Total Marks: " + +topMarks + " +"); + } + } + buffer.append(line); + return(buffer.toString()); + } + + public void stateChanged(ChangeEvent e) + { + switch(tabbedPane.getSelectedIndex()) + { + case 3: studentPassed.setText(getNumberPasses()); + break; + case 4: studentTopper.setText(getClassTopper()); + break; + } + } + + public void actionPerformed(ActionEvent e) + { + if(e.getSource() == submitID1) + { + studentInfo.setText(getStudentInfo()); + } + else if(e.getSource() == submitID2) + { + studentGrade.setText(getStudentGrade()); + } + if(e.getSource() == submitDetails) + { + setStudentInfo(); + } + } + +} + + +//Registration Class +class Registration +{ + private int topScore = 90; + private int passMarks = 35; + private int firstClass = 65; + private int secondClass = 45; + private static String idFile = "id.dat"; + private static String studentFile = "studentfile.dat"; + + public int id; + public String studentName; + public int physicsMarks; + public int biologyMarks; + public int mathsMarks; + + public int addStudent(String studentName, int physicsMarks, int +biologyMarks, int mathsMarks) + { + int id = 0; + try + { + FileWriter fileOutput = new FileWriter(Registration.studentFile,true); + id = Registration.getNextID(); + String buffer = id + "|" + studentName + "|" + physicsMarks + "|" + +biologyMarks + "|" + mathsMarks + " +"; + fileOutput.write(buffer); + fileOutput.close(); + Registration.setID(id); + } + catch(IOException e) + { + System.err.println(e.toString()); + System.exit(1); + } + return id; + + } + +//Function to get the details of a student given the ID + public boolean getStudentDetails(int id) + { + try + { + FileReader fileInput = new FileReader(Registration.studentFile); + BufferedReader br = new BufferedReader(fileInput); + { + + String str; + while((str = br.readLine()) != null) + { + StringTokenizer fields = new StringTokenizer(str,"|"); + if(Integer.parseInt(fields.nextToken()) == id) + { + this.id = id; + this.studentName = fields.nextToken(); + this.physicsMarks = Integer.parseInt(fields.nextToken()); + this.biologyMarks = Integer.parseInt(fields.nextToken()); + this.mathsMarks = Integer.parseInt(fields.nextToken()); + return true; + } + } + } + + } + + catch(IOException e) + { + System.err.println(e.toString()); + System.exit(1); + } + + return false; + } + + public int getTopScore() + { + return topScore; + } + + public int getPassMarks() + { + return passMarks; + } + + public int getFirstClass() + { + return firstClass; + } + + public int getSecondClass() + { + return secondClass; + } + +//Function to get the next ID available + public static int getNextID() + { + int id = 0; + try + { + RandomAccessFile studentIDFile = new +RandomAccessFile(Registration.idFile,"rw"); + if(studentIDFile.length() == 0) + { + id = 0; + } + else id = studentIDFile.readInt(); + id++; + studentIDFile.close(); + } + + catch(IOException e) + { + System.err.println(e.toString()); + System.exit(1); + } + return id; + } + +//Function to Store current ID in a file + public static void setID(int id) + { + try + { + RandomAccessFile studentIDFile = new +RandomAccessFile(Registration.idFile,"rw"); + studentIDFile.seek(0); + studentIDFile.writeInt(id); + studentIDFile.close(); + } + + catch(IOException e) + { + System.err.println(e.toString()); + System.exit(1); + } + } +} diff --git a/java/Basics/SelectionSort (Java).java b/java/Basics/SelectionSort (Java).java new file mode 100644 index 0000000..c1dc773 --- /dev/null +++ b/java/Basics/SelectionSort (Java).java @@ -0,0 +1,37 @@ +public class SelectionSortExample +{ + public static void selectionSort(int[] arr) + { + for (int i = 0; i < arr.length - 1; i++) + { + int index = i; + for (int j = i + 1; j < arr.length; j++) + { + if (arr[j] < arr[index]) + { + index = j;//searching for lowest index + } + } + int smallerNumber = arr[index]; + arr[index] = arr[i]; + arr[i] = smallerNumber; + } + } + + public static void main(String a[]) + { + int[] arr1 = {9,14,3,2,43,11,58,22}; + System.out.println("Before Selection Sort"); + for(int i:arr1) + { + System.out.print(i+" "); + } + System.out.println(); + selectionSort(arr1);//sorting array using selection sort + System.out.println("After Selection Sort"); + for(int i:arr1) + { + System.out.print(i+" "); + } + } +} \ No newline at end of file diff --git a/java/Basics/Set the foreground and background color to the tex.java b/java/Basics/Set the foreground and background color to the tex.java new file mode 100644 index 0000000..619a8fc --- /dev/null +++ b/java/Basics/Set the foreground and background color to the tex.java @@ -0,0 +1,186 @@ +Set the foreground and background color to the text area + +import java.awt.*; +import java.awt.event.*; +import java.applet.*; + +class colopat extends Frame +{ + Checkbox r,g,b; + Checkbox m,y,gr,p,w,bl,c; + TextArea ta; + Checkbox r1,g1,b1; + Checkbox m1,y1,gr1,p1,w1,bl1,c1; + Label ba,fo; + Panel pa1,p2,p3; + + colopat() + { + setSize(800,600); + + setLayout(new BorderLayout()); + pa1=new Panel(new GridLayout(5,2,10,10)); + p2=new Panel(new GridLayout(5,2,10,10)); + + CheckboxGroup cbg=new CheckboxGroup(); + + r=new Checkbox("red",cbg,false); + g=new Checkbox("green",cbg,false); + b=new Checkbox("blue",cbg,false); + m=new Checkbox("megenta",cbg,false); + y=new Checkbox("yellow",cbg,false); + gr=new Checkbox("grey",cbg,false); + p=new Checkbox("pink",cbg,false); + w=new Checkbox("white",cbg,false); + bl=new Checkbox("black",cbg,true); + c=new Checkbox("cyan",cbg,false); + ba=new Label("BACKGROUND COLORS",Label.CENTER); + ba.setBackground(Color.pink); + + pa1.add(ba); + pa1.add(r); + pa1.add(b); + pa1.add(m); + pa1.add(y); + pa1.add(gr); + pa1.add(p); + pa1.add(w); + pa1.add(bl); + pa1.add(c); + add("West",pa1); + + ta=new TextArea(5,25); + p3=new Panel(new GridLayout(3,1)); + p3.add(new Label("Text Area",1)); + p3.add(ta); + add("Center",p3); + + r.addItemListener(new CheckBoxHandler(this)); + g.addItemListener(new CheckBoxHandler(this)); + b.addItemListener(new CheckBoxHandler(this)); + m.addItemListener(new CheckBoxHandler(this)); + y.addItemListener(new CheckBoxHandler(this)); + gr.addItemListener(new CheckBoxHandler(this)); + p.addItemListener(new CheckBoxHandler(this)); + w.addItemListener(new CheckBoxHandler(this)); + c.addItemListener(new CheckBoxHandler(this)); + bl.addItemListener(new CheckBoxHandler(this)); + + CheckboxGroup cbg1=new CheckboxGroup(); + r1=new Checkbox("red",cbg1,false); + g1=new Checkbox("green",cbg1,false); + b1=new Checkbox("blue",cbg1,false); + m1=new Checkbox("megenta",cbg1,false); + y1=new Checkbox("yellow",cbg1,false); + gr1=new Checkbox("grey",cbg1,false); + p1=new Checkbox("pink",cbg1,false); + w1=new Checkbox("white",cbg1,false); + bl1=new Checkbox("black",cbg1,true); + c1=new Checkbox("cyan",cbg1,false); + fo=new Label("FOREGROUND COLORS"); + fo.setBackground(Color.pink); + + p2.add(fo); + p2.add(c1); + p2.add(g1); + p2.add(b1); + p2.add(m1); + p2.add(y1); + p2.add(gr1); + p2.add(p1); + p2.add(w1); + p2.add(bl1); + p2.add(c1); + add("East",p2); + + r1.addItemListener(new CheckBoxHandler(this)); + g1.addItemListener(new CheckBoxHandler(this)); + b1.addItemListener(new CheckBoxHandler(this)); + m1.addItemListener(new CheckBoxHandler(this)); + y1.addItemListener(new CheckBoxHandler(this)); + gr1.addItemListener(new CheckBoxHandler(this)); + p1.addItemListener(new CheckBoxHandler(this)); + w1.addItemListener(new CheckBoxHandler(this)); + c1.addItemListener(new CheckBoxHandler(this)); + bl1.addItemListener(new CheckBoxHandler(this)); + c1.addItemListener(new CheckBoxHandler(this)); + + addWindowListener(new mywindowAdapter(this)); + + setVisible(true); + } + + public static void main(String args[]) + { + new colopat(); + } +} + +class CheckBoxHandler implements ItemListener +{ + colopat cp; + +CheckBoxHandler(colopat cp) +{ + this.cp=cp; +} +public void itemStateChanged(ItemEvent ie) +{ +if(cp.r.getState()) +cp.ta.setBackground(Color.red); +else if(cp.g.getState()) +cp.ta.setBackground(Color.green); +else if(cp.b.getState()) +cp.ta.setBackground(Color.blue); +else if(cp.m.getState()) +cp.ta.setBackground(Color.magenta); +else if(cp.y.getState()) +cp.ta.setBackground(Color.yellow); +else if(cp.gr.getState()) +cp.ta.setBackground(Color.lightGray); +else if(cp.bl.getState()) +cp.ta.setBackground(Color.black); +else if(cp.w.getState()) +cp.ta.setBackground(Color.white); +else if(cp.p.getState()) +cp.ta.setBackground(Color.pink); +else +cp.ta.setBackground(Color.cyan); + + +if(cp.r1.getState()) +cp.ta.setForeground(Color.red); +else if(cp.g1.getState()) +cp.ta.setForeground(Color.green); +else if(cp.b1.getState()) +cp.ta.setForeground(Color.blue); +else if(cp.m1.getState()) +cp.ta.setForeground(Color.magenta); +else if(cp.y1.getState()) +cp.ta.setForeground(Color.yellow); +else if(cp.gr1.getState()) +cp.ta.setForeground(Color.lightGray); +else if(cp.bl1.getState()) +cp.ta.setForeground(Color.black); +else if(cp.w1.getState()) +cp.ta.setForeground(Color.white); +else if(cp.p1.getState()) +cp.ta.setForeground(Color.pink); +else +cp.ta.setForeground(Color.cyan); +} +} + +class mywindowAdapter extends WindowAdapter +{ + colopat cp; + +mywindowAdapter(colopat cp) +{ + this.cp=cp; +} +public void windowClosing(WindowEvent e) +{ + System.exit(0); +} +} diff --git a/java/Basics/Simple Arithmetic.java b/java/Basics/Simple Arithmetic.java new file mode 100644 index 0000000..07cf95f --- /dev/null +++ b/java/Basics/Simple Arithmetic.java @@ -0,0 +1,35 @@ +Simple Arithmetic + + + + + +public class SimpleArithmetic { + public static void main( String[] args ) { + int withdraw = 300; + int deposit = 400; + + // declare and define using initialised variables + int balance = deposit - withdraw; + + // different way of adding 100 to balance + balance = balance + 100; + balance += 100; + + // use boolean + boolean isGood = false; + isGood = !isGood; // isGood is now true + + // remainder is one + int remainder = 100 % 3; + + // all operators have the = semantics + // so we have examles of /= and *= below + int value = 100 * 10; + value /= 5; + value *= 2; + + // and of course we can have compound arithmetic + int yourValue = ( ( value + balance ) / ( withdraw * deposit ) ); + } +} diff --git a/java/Basics/Simple Inheritance.java b/java/Basics/Simple Inheritance.java new file mode 100644 index 0000000..7dce554 --- /dev/null +++ b/java/Basics/Simple Inheritance.java @@ -0,0 +1,51 @@ +Simple Inheritance + + + + + + +public class SimpleInheritance /* implicitly inherits from Object class */ { + // available to subclass and package level clients + protected int balance; + + public SimpleInheritance( String str ) { + System.out.println( "SimpleInheritance says: " + str ); + } + + public void message() { + + } +} + +class MySubclass extends SimpleInheritance { + // must define constructor because parent class + // does not define a default constructor + public MySubclass( String str ) { + // call the parent class's constructor + super( str ); + } + + // i've overriden the message method declared within SimpleInheritance + public void message() { + // but can call it by using the super keyword + super.message(); + + // i can also access non-private implementation, best not to have any + // in the first place, and expose through controlled accessor methods + System.out.println( super.balance ); + } +} + +class PackageLevelClient { + public PackageLevelClient() { + SimpleInheritance is = new MySubclass( "yo" ); + + // nasty, as a class in the package i can access + // all protected variables defined within this package, + // even though i'm not a part of the inheritance tree + // yuk, yuk, yuk, yuk!!!!!!!!!! + is.balance = 45; + } + +} diff --git a/java/Basics/Simple Mathematical Calculations 2.java b/java/Basics/Simple Mathematical Calculations 2.java new file mode 100644 index 0000000..0152059 --- /dev/null +++ b/java/Basics/Simple Mathematical Calculations 2.java @@ -0,0 +1,61 @@ +Simple Mathematical Calculations 2 + +import java.awt.*; +import java.awt.event.*; + +// Java extension packages +import javax.swing.*; + +public class Points extends JApplet implements ActionListener { + JTextField x1Input, x2Input, y1Input, y2Input; + JLabel labelX1, labelY1, labelX2, labelY2; + + // set up GUI components + public void init() + { + labelX1 = new JLabel( "Enter X1: " ); + labelY1 = new JLabel( "Enter Y1: " ); + labelX2 = new JLabel( "Enter X2: " ); + labelY2 = new JLabel( "Enter Y2: " ); + x1Input = new JTextField( 4 ); + x2Input = new JTextField( 4 ); + y1Input = new JTextField( 4 ); + y2Input = new JTextField( 4 ); + y2Input.addActionListener( this ); + + Container container = getContentPane(); + container.setLayout( new FlowLayout() ); + container.add( labelX1 ); + container.add( x1Input ); + container.add( labelY1 ); + container.add( y1Input ); + container.add( labelX2 ); + container.add( x2Input ); + container.add( labelY2 ); + container.add( y2Input ); + } + + // display distance between user input points + public void actionPerformed( ActionEvent e ) + { + double x1, y1, x2, y2; + + // read in two points + x1 = Double.parseDouble( x1Input.getText() ); + y1 = Double.parseDouble( y1Input.getText() ); + x2 = Double.parseDouble( x2Input.getText() ); + y2 = Double.parseDouble( y2Input.getText() ); + + double theDistance = distance( x1, y1, x2, y2 ); + showStatus( "Distance is " + theDistance ); + } + + // calculate distance between two points + public double distance( double x1, double y1, + double x2, double y2 ) + { + return Math.sqrt( Math.pow( ( x1 - x2 ), 2 ) + + Math.pow( ( y1 - y2 ), 2 ) ); + } + +} // end class Points diff --git a/java/Basics/Simple Mathematical Calculations.java b/java/Basics/Simple Mathematical Calculations.java new file mode 100644 index 0000000..52ed13b --- /dev/null +++ b/java/Basics/Simple Mathematical Calculations.java @@ -0,0 +1,51 @@ +Simple Mathematical Calculations + +// Exercise 3.12 Solution: Multiples.java +// Given two doubles as input, the program determines if the first// is a multiple of the second. + +// Java core packages +import java.awt.Graphics; // import class Graphics + +// Java extension packages +import javax.swing.*; // import package javax.swing + +public class Multiples extends JApplet { + String result; // output display String + + // initialize applet by obtaining values from user + public void init() + { + String firstNumber; // first String entered by user + String secondNumber; // second String entered by user + double number1; // first number to compare + double number2; // second number to compare + + // read first number from user as a String + firstNumber = + JOptionPane.showInputDialog( "Enter first floating-point number:" ); + + // read second number from user as a String + secondNumber = + JOptionPane.showInputDialog( "Enter second floating-point number:" ); + + // convert numbers from type String to type double + number1 = Double.parseDouble( firstNumber ); + number2 = Double.parseDouble( secondNumber ); + + if ( number1 % number2 == 0 ) + result = number1 + " is a multiple of " + number2; + + if ( number1 % number2 != 0 ) + result = number1 + " is not a multiple of " + number2; + + } // end method init + + // draw results on applet's background + public void paint( Graphics g ) + { + // draw result as a String at (25, 25) + g.drawString( result, 25, 25 ); + + } // end method paint + +} // end class OddEven diff --git a/java/Basics/Simple Strings.java b/java/Basics/Simple Strings.java new file mode 100644 index 0000000..20e7686 --- /dev/null +++ b/java/Basics/Simple Strings.java @@ -0,0 +1,79 @@ +Simple Strings + + + + + +/** + * messing about with Java Strings + */ +public class SimpleStrings { + public static void main( String[] args ) { + // a string is a array of characters + char[] helloChars = {'h', 'e', 'l', 'l', 'o'}; + String helloString = new String( helloChars ); + System.out.println( helloString ); + + // best way to assign a string literal + helloString = "hello"; + + // no need to do this + helloString = new String( "hello" ); + + // an example + String barryWhite = "i love you all!"; + System.out.println( barryWhite.length() ); // 15 + System.out.println( barryWhite.charAt( 0 ) ); // i + System.out.println( barryWhite.startsWith( "i love" ) ); // true + System.out.println( barryWhite.endsWith( "all" ) ); // false + System.out.println( barryWhite.indexOf( 'l' ) ); // 2 + System.out.println( barryWhite.indexOf( "you" ) ); // 7 + System.out.println( barryWhite.substring( 7 ) ); // you all! + System.out.println( barryWhite.substring( 3, 8 ) ); // ove y + + // String equality + String a = "hello"; + String b = "world"; + String c = new String( "hello" ); + String d = a; + + // == between Java objects is on reference equality + // equals() method is used to value equality + System.out.println( a == b ); // false + System.out.println( a == c ); // false + System.out.println( a.equals( c ) ); // true + System.out.println( a == d ); // true + + // String are immutable + String noChange = "have i changed, not likely"; + + noChange.substring( 3 ); + noChange.toLowerCase(); + noChange.toUpperCase(); + noChange.trim(); + System.out.println( noChange ); // have i changed, not likely + + // StringBuffer usage + StringBuffer buffer = new StringBuffer(); + for( int i = 0; i < 10; i++ ) { + buffer.append( "say hello: " ); + buffer.append( i ); + buffer.append( "\n" ); + } + + System.out.println( buffer ); + /** + * this outputs + * say hello: 0 + * say hello: 1 + * say hello: 2 + * say hello: 3 + * say hello: 4 + * say hello: 5 + * say hello: 6 + * say hello: 7 + * say hello: 8 + * say hello: 9 + */ + } +} diff --git a/java/Basics/SimpleWordCounter (Java).java b/java/Basics/SimpleWordCounter (Java).java new file mode 100644 index 0000000..d833f46 --- /dev/null +++ b/java/Basics/SimpleWordCounter (Java).java @@ -0,0 +1,39 @@ +// Program demonstrating use of a map to count the frequency of words in a file. + +import java.io.File; +import java.io.IOException; +import java.util.Map; +import java.util.Scanner; +import java.util.TreeMap; + +public class SimpleWordCounter +{ + + public static void main(String[] args) + { + try + { + File f = new File("ciaFactBook2008.txt"); + Scanner sc; + sc = new Scanner(f); + // sc.useDelimiter("[^a-zA-Z']+"); + Map wordCount = new TreeMap(); + while(sc.hasNext()) + { + String word = sc.next(); + if(!wordCount.containsKey(word)) + wordCount.put(word, 1); + else + wordCount.put(word, wordCount.get(word) + 1); + } + // show results + for(String word : wordCount.keySet()) + System.out.println(word + " " + wordCount.get(word)); + System.out.println(wordCount.size()); + } + catch(IOException e) + { + System.out.println("Unable to read from file."); + } + } +} diff --git a/java/Basics/Stop watch programme.java b/java/Basics/Stop watch programme.java new file mode 100644 index 0000000..44c08a2 --- /dev/null +++ b/java/Basics/Stop watch programme.java @@ -0,0 +1,83 @@ +Stop watch programme + +import java.awt.event.*; +import java.awt.*; +import javax.swing.*; + +public class Stopwatch extends JFrame implements ActionListener, Runnable + { + private long startTime; + private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("mm : ss.SSS"); + private final JButton startStopButton= new JButton("Start/stop"); + private Thread updater; + private boolean isRunning= false; + private final Runnable displayUpdater= new Runnable() + { + public void run() + { + displayElapsedTime(System.currentTimeMillis() - Stopwatch.this.startTime); + } + }; + public void actionPerformed(ActionEvent ae) + { + if(isRunning) + { + long elapsed= System.currentTimeMillis() - startTime; + isRunning= false; + try + { + updater.join(); + // Wait for updater to finish + } + catch(InterruptedException ie) {} + displayElapsedTime(elapsed); + // Display the end-result + } + else + { + startTime= System.currentTimeMillis(); + isRunning= true; + updater= new Thread(this); + updater.start(); + } + } + private void displayElapsedTime(long elapsedTime) + { + startStopButton.setText(timerFormat.format(new java.util.Date(elapsedTime))); + } + public void run() + { + try + { + while(isRunning) + { + SwingUtilities.invokeAndWait(displayUpdater); + Thread.sleep(50); + } + } + catch(java.lang.reflect.InvocationTargetException ite) + { + ite.printStackTrace(System.err); + // Should never happen! + } + catch(InterruptedException ie) {} + // Ignore and return! + } + public Stopwatch() + { + startStopButton.addActionListener(this); + getContentPane().add(startStopButton); + setSize(100,50); + setVisible(true); + } + public static void main(String[] arg) + { + new Stopwatch().addWindowListener(new WindowAdapter() + { + public void windowClosing(WindowEvent e) + { + System.exit(0); + } + }); + } +} diff --git a/java/Basics/StringFunctions.java b/java/Basics/StringFunctions.java new file mode 100644 index 0000000..ceca506 --- /dev/null +++ b/java/Basics/StringFunctions.java @@ -0,0 +1,308 @@ +package com.jwetherell.algorithms.strings; + +import java.util.BitSet; +import java.util.StringTokenizer; + +/** + * This class contains methods for modifying text. + * + * @author Justin Wetherell + */ +public class StringFunctions { + + private static final char SPACE = ' '; + + public static final String reverseWithStringConcat(String string) { + String output = new String(); + for (int i = (string.length() - 1); i >= 0; i--) { + output += (string.charAt(i)); + } + return output; + } + + public static final String reverseWithStringBuilder(String string) { + final StringBuilder builder = new StringBuilder(); + for (int i = (string.length() - 1); i >= 0; i--) { + builder.append(string.charAt(i)); + } + return builder.toString(); + } + + public static final String reverseWithStringBuilderBuiltinMethod(String string) { + final StringBuilder builder = new StringBuilder(string); + return builder.reverse().toString(); + } + + public static final String reverseWithSwaps(String string) { + final char[] array = string.toCharArray(); + final int length = array.length - 1; + final int half = (int) Math.floor(array.length / 2); + + char c; + for (int i = length; i >= half; i--) { + c = array[length - i]; + array[length - i] = array[i]; + array[i] = c; + } + return String.valueOf(array); + } + + public static final String reverseWithXOR(String string) { + final char[] array = string.toCharArray(); + final int length = array.length; + final int half = (int) Math.floor(array.length / 2); + + for (int i = 0; i < half; i++) { + array[i] ^= array[length - i - 1]; + array[length - i - 1] ^= array[i]; + array[i] ^= array[length - i - 1]; + } + return String.valueOf(array); + } + + public static final String reverseWordsByCharWithAdditionalStorage(String string) { + final StringBuilder builder = new StringBuilder(); + final int length = string.length() - 1; + final StringBuilder temp = new StringBuilder(); + + char c = 0; + int index = 0; + int last = string.length(); + for (int i = length; i >= 0; i--) { + c = string.charAt(i); + if (c == SPACE || i == 0) { + index = (i == 0) ? 0 : i + 1; + temp.append(string.substring(index, last)); + if (index != 0) + temp.append(c); + builder.append(temp); + temp.delete(0, temp.length()); + last = i; + } + } + + return builder.toString(); + } + + public static final String reverseWordsUsingStringTokenizerWithAdditionalStorage(String string) { + final StringTokenizer st = new StringTokenizer(string); + String output = new String(); + while (st.hasMoreTokens()) { + output = (st.nextToken()) + ' ' + output; + } + + return output.trim(); + } + + public static final String reverseWordsUsingSplitWithAdditionalStorage(String string) { + final StringBuilder builder = new StringBuilder(); + final String[] temp = string.split(" "); + + for (int i = (temp.length - 1); i >= 0; i--) { + builder.append(temp[i]).append(' '); + } + return builder.toString().trim(); + } + + public static final String reverseWordsInPlace(String string) { + char[] chars = string.toCharArray(); + + int lengthI = 0; + int lastI = 0; + int lengthJ = 0; + int lastJ = chars.length - 1; + + int i = 0; + char iChar = 0; + char jChar = 0; + while (i < chars.length && i <= lastJ) { + iChar = chars[i]; + if (iChar == SPACE) { + lengthI = i - lastI; + for (int j = lastJ; j >= i; j--) { + jChar = chars[j]; + if (jChar == SPACE) { + lengthJ = lastJ - j; + swapWords(lastI, i - 1, j + 1, lastJ, chars); + lastJ = lastJ - lengthI - 1; + break; + } + } + lastI = lastI + lengthJ + 1; + i = lastI; + } else { + i++; + } + } + + return String.valueOf(chars); + } + + private static final void swapWords(int startA, int endA, int startB, int endB, char[] array) { + int lengthA = endA - startA + 1; + int lengthB = endB - startB + 1; + + int length = lengthA; + if (lengthA > lengthB) + length = lengthB; + + int indexA = 0; + int indexB = 0; + char c = 0; + for (int i = 0; i < length; i++) { + indexA = startA + i; + indexB = startB + i; + + c = array[indexB]; + array[indexB] = array[indexA]; + array[indexA] = c; + } + + if (lengthB > lengthA) { + length = lengthB - lengthA; + int end = 0; + for (int i = 0; i < length; i++) { + end = endB - ((length - 1) - i); + c = array[end]; + shiftRight(endA + i, end, array); + array[endA + 1 + i] = c; + } + } else if (lengthA > lengthB) { + length = lengthA - lengthB; + for (int i = 0; i < length; i++) { + c = array[endA]; + shiftLeft(endA, endB, array); + array[endB + i] = c; + } + } + } + + private static final void shiftRight(int start, int end, char[] array) { + for (int i = end; i > start; i--) { + array[i] = array[i - 1]; + } + } + + private static final void shiftLeft(int start, int end, char[] array) { + for (int i = start; i < end; i++) { + array[i] = array[i + 1]; + } + } + + public static final boolean isPalindromeWithAdditionalStorage(String string) { + final String reversed = new StringBuilder(string).reverse().toString(); + return string.equals(reversed); + } + + public static final boolean isPalindromeInPlace(String string) { + final char[] array = string.toCharArray(); + final int length = array.length - 1; + final int half = Math.round(array.length / 2); + char a, b; + for (int i = length; i >= half; i--) { + a = array[length - i]; + b = array[i]; + if (a != b) + return false; + } + return true; + } + + public static final String[] generateSubsets(String inputString) { + final int length = inputString.length(); + final int size = (int) Math.pow(2, length); + final BitSet[] sets = new BitSet[size]; + final String[] output = new String[size]; + + for (int i = 0; i < size; i++) { + final BitSet set = new BitSet(size); + final StringBuilder builder = new StringBuilder(); + if (i > 0) { + for (int j = length - 1; j >= 0; j--) { + if (j == length - 1) { + if (i % 2 != 0) + set.set(j, true); + } else { + boolean prev = sets[i - 1].get(j); + boolean next = true; + for (int k = j + 1; k < length; k++) { + next = next && sets[i - 1].get(k); + } + if (next) + prev = !prev; + set.set(j, prev); + } + if (set.get(j)) + builder.append(inputString.charAt(j)); + } + } + sets[i] = set; + output[i] = builder.toString(); + } + return output; + } + + /** recursive **/ + public static final int levenshteinDistanceRecursive(String s, String t) { + final int sLength = s.length(); + final int tLength = t.length(); + final char[] sChars = s.toCharArray(); + final char[] tChars = t.toCharArray(); + + int cost = 0; + if ((sLength > 0 && tLength > 0) && sChars[0] != tChars[0]) + cost = 1; + + if (sLength == 0) + return tLength; + else if (tLength == 0) + return sLength; + else { + final int min1 = levenshteinDistanceRecursive(s.substring(1), t) + 1; + final int min2 = levenshteinDistanceRecursive(s, t.substring(1)) + 1; + final int min3 = levenshteinDistanceRecursive(s.substring(1), t.substring(1)) + cost; + + int minOfFirstSet = Math.min(min1, min2); + return (Math.min(minOfFirstSet, min3)); + } + } + + /** iterative - dynamic programming **/ + public static final int levenshteinDistanceIterative(String string1, String string2) { + final char[] s = string1.toCharArray(); + final char[] t = string2.toCharArray(); + final int m = s.length; + final int n = t.length; + + // for all i and j, d[i,j] will hold the Levenshtein distance between + // the first i characters of s and the first j characters of t + // note that d has (m+1)*(n+1) values + final int[][] d = new int[m+1][n+1]; + + // source prefixes can be transformed into empty string by + // dropping all characters + for (int i=1; i<=m; i++) + d[i][0] = i; + + // target prefixes can be reached from empty source prefix + // by inserting every character + for (int j=1; j<=n; j++) + d[0][j] = j; + + int substitutionCost; + for (int j=1; j<=n; j++) { + for (int i=1; i<=m; i++) { + if (s[i-1] == t[j-1]) + substitutionCost = 0; + else + substitutionCost = 1; + + int minOfInsAndDel = Math.min(d[i-1][j] + 1, // deletion + d[i][j-1] + 1); // insertion + d[i][j] = Math.min(minOfInsAndDel, // minimum of insert and delete + d[i-1][j-1] + substitutionCost); // substitution + } + } + return d[m][n]; + } +} diff --git a/java/Basics/SubsequenceCounter.java b/java/Basics/SubsequenceCounter.java new file mode 100644 index 0000000..3449cb9 --- /dev/null +++ b/java/Basics/SubsequenceCounter.java @@ -0,0 +1,60 @@ +package com.jwetherell.algorithms.sequence; + +/** + * Finds the number of times a string occurs as a subsequence in a text. + *

+ * http://www.geeksforgeeks.org/find-number-times-string-occurs-given-string/ + *
+ * @author Justin Wetherell + */ +public class SubsequenceCounter { + + private static char[] seq = null; + private static char[] subseq = null; + private static int[][] tbl = null; + + private SubsequenceCounter() { } + + /** + * Finds the number of times a string occurs as a subsequence in a text. + * + * @param sequence Text to find subsequence in. + * @param subSequence subsequence to find in the text. + * @return Number of times a string occurs as a subsequence in a text + */ + public static int getCount(char[] sequence, char[] subSequence) { + try { + seq = sequence; + subseq = subSequence; + tbl = new int[seq.length + 1][subseq.length + 1]; + + for (int row = 0; row < tbl.length; row++) + for (int col = 0; col < tbl[row].length; col++) + tbl[row][col] = countMatches(row, col); + + return tbl[seq.length][subseq.length]; + } finally { + seq = null; + subseq = null; + tbl = null; + } + } + + private static int countMatches(int seqDigitsLeft, int subseqDigitsLeft) { + if (subseqDigitsLeft == 0) + return 1; + + if (seqDigitsLeft == 0) + return 0; + + final char currSeqDigit = seq[seq.length - seqDigitsLeft]; + final char currSubseqDigit = subseq[subseq.length - subseqDigitsLeft]; + + int result = 0; + if (currSeqDigit == currSubseqDigit) + result += tbl[seqDigitsLeft - 1][subseqDigitsLeft - 1]; + result += tbl[seqDigitsLeft - 1][subseqDigitsLeft]; + + return result; + } +} diff --git a/java/Basics/Swap two numbers.java b/java/Basics/Swap two numbers.java new file mode 100644 index 0000000..3d2d87b --- /dev/null +++ b/java/Basics/Swap two numbers.java @@ -0,0 +1,22 @@ + import java.util.Scanner; + + class SwapNumbers + { + public static void main(String args[]) + { + int x, y, temp; + System.out.println("Enter x and y"); + Scanner in = new Scanner(System.in); + + x = in.nextInt(); + y = in.nextInt(); + + System.out.println("Before Swapping\nx = "+x+"\ny = "+y); + + temp = x; + x = y; + y = temp; + + System.out.println("After Swapping\nx = "+x+"\ny = "+y); + } + } \ No newline at end of file diff --git a/java/Basics/Switch Statements.java b/java/Basics/Switch Statements.java new file mode 100644 index 0000000..fe4f94d --- /dev/null +++ b/java/Basics/Switch Statements.java @@ -0,0 +1,57 @@ +Switch Statements + + + + + +public class SwitchStatements { + public static void main( String[] args ) { + int amount = 10; + + // simple switch statement + switch( amount ) { + case 1: + System.out.println( "amount is 1" ); + break; + case 2: + System.out.println( "amount is 2" ); + break; + default: + System.out.println( "don't care about amount" ); + } + + // more complicated switch statement + switch( amount ) { + case 1: + System.out.println( "amount was 1" ); + break; + + case 10: + case 4: + case 3: + if( amount == 10 ) { + System.out.println( "amount was ten" ); + } + else { + System.out.println( "amount was 4 or 3, actually -> " + amount ); + } + break; + + default: + System.out.println( "default action" ); + } + + // switch on a char + char c = 't'; + switch( c ) { + case 'b': + System.out.println( "hit the b character" ); + break; + case 't': + System.out.println( "hit the t character" ); + break; + default: + System.out.println( "unsupported character" ); + } + } +} diff --git a/java/Basics/This is a simple text clock.java b/java/Basics/This is a simple text clock.java new file mode 100644 index 0000000..cdb8878 --- /dev/null +++ b/java/Basics/This is a simple text clock.java @@ -0,0 +1,60 @@ +This is a simple text clock. See + +javax.swing.Timer for an explanation of how use this simple timer class. + + + + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.event.*; +import java.util.Calendar; // only need this one class + +/// TextClock +public class TextClock { + +main + public static void main(String[] args) { + JFrame clock = new TextClockWindow(); + clock.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + clock.setVisible(true); + }//end main +}//endclass TextClock + + +////// TextClockWindow +class TextClockWindow extends JFrame { + +instance variables + private JTextField timeField; // set by timer listener + + +constructor + public TextClockWindow() { + // Build the GUI - only one panel + timeField = new JTextField(6); + timeField.setFont(new Font("sansserif", Font.PLAIN, 48)); + + Container content = this.getContentPane(); + content.setLayout(new FlowLayout()); + content.add(timeField); + + this.setTitle("Text Clock"); + this.pack(); + + // Create a 1-second timer and action listener for it. + // Specify package because there are two Timer classes + javax.swing.Timer t = new javax.swing.Timer(1000, + new ActionListener() { + public void actionPerformed(ActionEvent e) { + Calendar now = Calendar.getInstance(); + int h = now.get(Calendar.HOUR_OF_DAY); + int m = now.get(Calendar.MINUTE); + int s = now.get(Calendar.SECOND); + timeField.setText("" + h + ":" + m + ":" + s); + } + }); + t.start(); // Start the timer + }//end constructor +}//endclass TextClock diff --git a/java/Basics/TimeQuery.java b/java/Basics/TimeQuery.java new file mode 100644 index 0000000..c9ade1d --- /dev/null +++ b/java/Basics/TimeQuery.java @@ -0,0 +1,83 @@ +TimeQuery + + + +import java.io.*; +import java.net.*; +import java.nio.*; +import java.nio.channels.*; +import java.nio.charset.*; +import java.util.regex.*; + + +public class TimeQuery { + + // The standard daytime port + private static int DAYTIME_PORT = 13; + + // The port we'll actually use + private static int port = DAYTIME_PORT; + + // Charset and decoder for US-ASCII + private static Charset charset = Charset.forName("US-ASCII"); + private static CharsetDecoder decoder = charset.newDecoder(); + + // Direct byte buffer for reading + private static ByteBuffer dbuf = ByteBuffer.allocateDirect(1024); + + // Ask the given host what time it is + // + private static void query(String host) throws IOException { + InetSocketAddress isa + = new InetSocketAddress(InetAddress.getByName(host), port); + SocketChannel sc = null; + + try { + + // Connect + sc = SocketChannel.open(); + sc.connect(isa); + + // Read the time from the remote host. For simplicity we assume + // that the time comes back to us in a single packet, so that we + // only need to read once. + dbuf.clear(); + sc.read(dbuf); + + // Print the remote address and the received time + dbuf.flip(); + CharBuffer cb = decoder.decode(dbuf); + System.out.print(isa + " : " + cb); + + } finally { + // Make sure we close the channel (and hence the socket) + if (sc != null) + sc.close(); + } + } + + public static void main(String[] args) { + if (args.length < 1) { + System.err.println("Usage: java TimeQuery [port] host..."); + return; + } + int firstArg = 0; + + // If the first argument is a string of digits then we take that + // to be the port number + if (Pattern.matches("[0-9]+", args[0])) { + port = Integer.parseInt(args[0]); + firstArg = 1; + } + + for (int i = firstArg; i < args.length; i++) { + String host = args[i]; + try { + query(host); + } catch (IOException x) { + System.err.println(host + ": " + x); + } + } + } + +} diff --git a/java/Basics/TimeServer.java b/java/Basics/TimeServer.java new file mode 100644 index 0000000..e20368b --- /dev/null +++ b/java/Basics/TimeServer.java @@ -0,0 +1,74 @@ +TimeServer + + + +import java.io.*; +import java.net.*; +import java.nio.*; +import java.nio.channels.*; +import java.nio.charset.*; +import java.util.*; +import java.util.regex.*; + + +public class TimeServer { + + // We can't use the normal daytime port (unless we're running as root, + // which is unlikely), so we use this one instead + private static int PORT = 8013; + + // The port we'll actually use + private static int port = PORT; + + // Charset and encoder for US-ASCII + private static Charset charset = Charset.forName("US-ASCII"); + private static CharsetEncoder encoder = charset.newEncoder(); + + // Direct byte buffer for writing + private static ByteBuffer dbuf = ByteBuffer.allocateDirect(1024); + + + // Open and bind the server-socket channel + // + private static ServerSocketChannel setup() throws IOException { + ServerSocketChannel ssc = ServerSocketChannel.open(); + InetSocketAddress isa + = new InetSocketAddress(InetAddress.getLocalHost(), port); + ssc.socket().bind(isa); + return ssc; + } + + // Service the next request to come in on the given channel + // + private static void serve(ServerSocketChannel ssc) throws IOException { + SocketChannel sc = ssc.accept(); + try { + String now = new Date().toString(); + sc.write(encoder.encode(CharBuffer.wrap(now + " +"))); + System.out.println(sc.socket().getInetAddress() + " : " + now); + sc.close(); + } finally { + // Make sure we close the channel (and hence the socket) + sc.close(); + } + } + + public static void main(String[] args) throws IOException { + if (args.length > 1) { + System.err.println("Usage: java TimeServer [port]"); + return; + } + + // If the first argument is a string of digits then we take that + // to be the port number + if ((args.length == 1) && Pattern.matches("[0-9]+", args[0])) + port = Integer.parseInt(args[0]); + + ServerSocketChannel ssc = setup(); + for (;;) + serve(ssc); + + } + +} diff --git a/java/Basics/Timer.java b/java/Basics/Timer.java new file mode 100644 index 0000000..9abb421 --- /dev/null +++ b/java/Basics/Timer.java @@ -0,0 +1,19 @@ +Timer + + + +package com.ack.webservices.soap.examples.handlers; + +import java.util.Calendar; +import java.util.Date; + +public class Timer { + public void sendTime( Date theTime ) { + System.out.println( "time on client: " + theTime ); + } + + public Date getTime() { + // return time on server + return Calendar.getInstance().getInstance().getTime(); + } +} diff --git a/java/Basics/TimerClient.java b/java/Basics/TimerClient.java new file mode 100644 index 0000000..1c8b94a --- /dev/null +++ b/java/Basics/TimerClient.java @@ -0,0 +1,55 @@ +TimerClient + + + +package com.ack.webservices.soap.examples.handlers; + +import java.util.Calendar; +import java.util.Date; + +import org.apache.axis.client.Call; +import org.apache.axis.client.Service; + +public class TimerClient { + public static void main( String[] args ) throws Exception { + String endpoint = "http://localhost:8080/axis/services/TimerService"; + + /** + * call the getTime to find out the time on the server + */ + + // calls are created our a service, that is typically associated, + // but not necessarily, with a WSDL file + Service service = new Service(); + Call call = (Call) service.createCall(); + + // set in the target endpoint, operation name, and request intent + call.setTargetEndpointAddress( new java.net.URL( endpoint ) ); + call.setOperationName( "getTime" ); + + // Axis provides a nicely overloaded invoke that delivered the return value + Date ret = (Date) call.invoke( new Object[]{} ); + + // then just print it out + System.out.println( "time on server: " + ret ); + + /** + * call the sendTime to pass the time on the client to the server + * note: check the soap server's console for the output. + * + * note: Be sure to check what is returned to the client from the server + * when an invokeOneWay() is called. Do this be uses the TraceMessageHandler + * in the of the TimeService. + */ + + call = (Call) service.createCall(); + + // set in the target endpoint, operation name, and request intent + call.setTargetEndpointAddress( new java.net.URL( endpoint ) ); + call.setOperationName( "sendTime" ); + + // send the time on the client to the server, in a one way method call + Date clientDate = Calendar.getInstance().getTime(); + call.invokeOneWay( new Object[]{clientDate} ); + } +} diff --git a/java/Basics/To compare two strings.java b/java/Basics/To compare two strings.java new file mode 100644 index 0000000..7be2210 --- /dev/null +++ b/java/Basics/To compare two strings.java @@ -0,0 +1,23 @@ + import java.util.Scanner; + + class CompareStrings + { + public static void main(String args[]) + { + String s1, s2; + Scanner in = new Scanner(System.in); + + System.out.println("Enter the first string"); + s1 = in.nextLine(); + + System.out.println("Enter the second string"); + s2 = in.nextLine(); + + if ( s1.compareTo(s2) > 0 ) + System.out.println("First string is greater than second."); + else if ( s1.compareTo(s2) < 0 ) + System.out.println("First string is smaller than second."); + else + System.out.println("Both strings are equal."); + } + } \ No newline at end of file diff --git a/java/Basics/To find all substrings of a string.java b/java/Basics/To find all substrings of a string.java new file mode 100644 index 0000000..c2765a0 --- /dev/null +++ b/java/Basics/To find all substrings of a string.java @@ -0,0 +1,28 @@ + Java programing code + import java.util.Scanner; + + class SubstringsOfAString + { + public static void main(String args[]) + { + String string, sub; + int i, c, length; + + Scanner in = new Scanner(System.in); + System.out.println("Enter a string to print it's all substrings"); + string = in.nextLine(); + + length = string.length(); + + System.out.println("Substrings of \""+string+"\" are :-"); + + for( c = 0 ; c < length ; c++ ) + { + for( i = 1 ; i <= length - c ; i++ ) + { + sub = string.substring(c, c+i); + System.out.println(sub); + } + } + } + } \ No newline at end of file diff --git a/java/Basics/To reverse a string.java b/java/Basics/To reverse a string.java new file mode 100644 index 0000000..f1c0eb6 --- /dev/null +++ b/java/Basics/To reverse a string.java @@ -0,0 +1,20 @@ + import java.util.*; + + class ReverseString + { + public static void main(String args[]) + { + String original, reverse = ""; + Scanner in = new Scanner(System.in); + + System.out.println("Enter a string to reverse"); + original = in.nextLine(); + + int length = original.length(); + + for ( int i = length - 1 ; i >= 0 ; i-- ) + reverse = reverse + original.charAt(i); + + System.out.println("Reverse of entered string is: "+reverse); + } + } \ No newline at end of file diff --git a/java/Basics/Transfer Account.java b/java/Basics/Transfer Account.java new file mode 100644 index 0000000..bd8b39d --- /dev/null +++ b/java/Basics/Transfer Account.java @@ -0,0 +1,24 @@ +Transfer Account + + + +package com.ack.learning.examples.account; + +public class TransferAccount { + private static int count; + + public TransferAccount() { + ++TransferAccount.count; + } + + public static int getObjectCount() { + return TransferAccount.count; + } + + public static void main( String[] args ) { + TransferAccount ta = new TransferAccount(); + TransferAccount da = new TransferAccount(); + + System.out.println( TransferAccount.getObjectCount() ); + } +} diff --git a/java/Basics/Try Finally.java b/java/Basics/Try Finally.java new file mode 100644 index 0000000..22ce625 --- /dev/null +++ b/java/Basics/Try Finally.java @@ -0,0 +1,21 @@ +Try Finally + + + + + +public class TryFinally { + public static void main( String[] args ) throws Exception { + // important to note that try, does not always need + // to be accompanied by a catch block + try { + // if an exception is raised the finally block is + // executed and the exception propogates out, hence + // note the Exception on the main method's throw clause + throw new Exception( "oopsy" ); + } + finally { + System.out.println( "no worries, i'm always called" ); + } + } +} diff --git a/java/Basics/Try Pie Finally.java b/java/Basics/Try Pie Finally.java new file mode 100644 index 0000000..d6e8234 --- /dev/null +++ b/java/Basics/Try Pie Finally.java @@ -0,0 +1,33 @@ +Try Pie Finally + + + +package com.ack.learning.exceptions; + +import com.ack.learning.exceptions.PieEater; +import com.ack.learning.exceptions.PieException; + +public class TryPieFinally { + public static void main( String[] args ) throws PieException { + + // in this example, you have decided not to handle + // PieExceptions raised in the try block. + + // When a PieException occurs, the finally block code + // is executed and the exception propagates up the + // method stack to main(), which we see can throw PieException + + // The JVM seeing that main() is the program entry point, catches + // the exception, dumps out its stack trace and ends the program + + // note: better to always handle application specific errors + try { + PieEater pe = new PieEater(); + // eat over a 100 pies + System.out.println( pe.howManyPies() ); + } + finally { + System.out.println( "no more pies" ); + } + } +} diff --git a/java/Basics/Type Casting.java b/java/Basics/Type Casting.java new file mode 100644 index 0000000..628cc37 --- /dev/null +++ b/java/Basics/Type Casting.java @@ -0,0 +1,35 @@ +Type Casting + + + + + +public class TypeCasting { + public static void main( String[] args ) { + // implicit cast + + // will allow if the right-hand side (rhs) value is small enough + short smallValue = 45; + + // this is not allowed because rhs value is too big for a short + //smallValue = 234251434324324; + + // assigning a short to an integer is an implicit cast and + // one the compiler can handle because ints are bigger than shorts + int littleValue = smallValue; + + // assigning a integer to short requires an explicit cast because + // shorts are smaller than ints and they would a loss of precision + smallValue = (short) littleValue; + + // specify typed literal values using L, F and D + // ( and their lowercase equivalents ) + float pay = 42234.45f; + long bigValue = 45243224L; + double amount = 345.45d; + + // default literal values + int defaultIsInt = 345; + double defaultIsDouble = 34.5; + } +} diff --git a/java/Basics/Use of Runtime Class.java b/java/Basics/Use of Runtime Class.java new file mode 100644 index 0000000..b0adc4a --- /dev/null +++ b/java/Basics/Use of Runtime Class.java @@ -0,0 +1,32 @@ +Use of Runtime Class + +import java.io.*; +class test extends Thread +{ + public void run() + { + Runtime r=Runtime.getRuntime(); + Process p=null; + try + { + for(int i=0;i<=100;i++) + { + p=r.exec("net send vishal how r u!"); + //p.waitFor(); + Thread.sleep(5000); + } + } + catch(Exception e) + { + System.out.println(e); + } + } + + public static void main(String args[]) + { + test t=new test(); + t.run(); + + } + +} diff --git a/java/Basics/Using Primitive Arrays.java b/java/Basics/Using Primitive Arrays.java new file mode 100644 index 0000000..61dc682 --- /dev/null +++ b/java/Basics/Using Primitive Arrays.java @@ -0,0 +1,43 @@ +Using Primitive Arrays + + + + + +public class UsingPrimitiveArrays { + public static void main( String[] args ) { + // declare an array + int[] bags; + + // create and assign array with 10 elements + bags = new int[5]; + + // declare, create and assign array in one step + float[] balances = new float[4]; + + /** + * Note that both the 'bags' and 'balances' arrays + * are initialised with the default values which for + * ints and float are zero + */ + + // assign bags new values + bags = new int[]{5, 10, 15, 20, 25}; + + // here is a shorthand for declaring an array, + // and assigning values. note that the omission + // of the new statement can only be done if declaration + // and assignment take place within one statement + int[] sacks = {1, 2, 3, 4, 5}; + + // and to get the length of the array + // java provides a special property on arrays + // NOTE: length is not a method, hence no parenthesis + System.out.println( "The number of sacks is: " + sacks.length ); + + // accessing arrays + for( int i = 0; i < bags.length; i++ ) { + System.out.println( bags[i] ); + } + } +} diff --git a/java/Basics/While Loops.java b/java/Basics/While Loops.java new file mode 100644 index 0000000..29bf0e7 --- /dev/null +++ b/java/Basics/While Loops.java @@ -0,0 +1,30 @@ +While Loops + + + + + +public class WhileLoops { + public static void main( String[] args ) { + // simple loop that goes round and around until + // expression evaluations to false + double index = 99999; + while( index > 10 ) { + System.out.println( "index has value " + index ); + index /= 2; + } + + // this would be an infinite loop... + while( true ) { + break; // ...if we didn't break out here + } + + // same as while loop, but with a subtle difference. code is alway + // executed before the loop iteration expression is evaluate + // do..whiles are the least used looping structures + do { + index *= 2; + System.out.println( "index has value " + index ); + } while( index < 9999 ); + } +} diff --git a/java/Basics/WordCount (Java).java b/java/Basics/WordCount (Java).java new file mode 100644 index 0000000..eb37900 --- /dev/null +++ b/java/Basics/WordCount (Java).java @@ -0,0 +1,194 @@ +//Program that compares counting words in files using an ArrayList and a Map. + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Scanner; + +import javax.swing.JFileChooser; +import javax.swing.UIManager; + + +public class WordCount +{ + + public static void main(String[] args) + { + countWordsViaGUI(); + } + + + // allow user to pick file to exam via GUI. + // allow multiple picks + public static void countWordsViaGUI() + { + setLookAndFeel(); + try + { + Scanner key = new Scanner(System.in); + do + { + System.out.println("Opening GUI to choose file."); + Scanner fileScanner = new Scanner(getFile()); + Stopwatch st = new Stopwatch(); + st.start(); + ArrayList words = countWordsWithArrayList(fileScanner); + st.stop(); + System.out.println("time to count: " + st); + System.out.print("Enter number of words to display: "); + int numWordsToShow = Integer.parseInt(key.nextLine()); + showWords(words, numWordsToShow); + fileScanner.close(); + System.out.print("Perform another count? "); + } + while(key.nextLine().toLowerCase().charAt(0) == 'y'); + key.close(); + } + catch(FileNotFoundException e) + { + System.out.println("Problem reading the data file. Exiting the program." + e); + } + } + + + // determine distinct words in a file using an array list + private static ArrayList countWordsWithArrayList(Scanner fileScanner) + { + System.out.println("Total number of words: " + numWords); + System.out.println("number of distincy words: " + result.size()); + return result; + } + + + // determine distinct words in a file and frequency of each word with a Map + private static Map countWordsWithMap(Scanner fileScanner) + { + System.out.println("Total number of words: " + numWords); + System.out.println("number of distincy words: " + result.size()); + return result; + } + + + private static void showWords(ArrayList words, int numWordsToShow) + { + for(int i = 0; i < words.size() && i < numWordsToShow; i++) + System.out.println(words.get(i)); + } + + + private static void showWords(Map words, int numWordsToShow) + { + } + + + // perform a series of experiments on files. Determine average time to + // count words in files of various sizes + private static void performExp() + { + String[] smallerWorks = {"smallWords.txt", "2BR02B.txt", "Alice.txt", "SherlockHolmes.txt"};; + String[] bigFile = {"ciaFactBook2008.txt"}; + timingExpWithArrayList(smallerWorks, 50); + timingExpWithArrayList(bigFile, 3); + timingExpWithMap(smallerWorks, 50); + timingExpWithMap(bigFile, 3); + } + + + // pre: titles != null, elements of titles refer to files in the + // same path as this program, numExp >= 0 + // read words from files and print average time to cound words. + private static void timingExpWithMap(String[] titles, int numExp) + { + try + { + double[] times = new double[titles.length]; + final int NUM_EXP = 50; + for(int i = 0; i < NUM_EXP; i++) + { + for(int j = 0; j < titles.length; j++) + { + Scanner fileScanner = new Scanner(new File(titles[j])); + Stopwatch st = new Stopwatch(); + st.start(); + Map words = countWordsWithMap(fileScanner); + st.stop(); + System.out.println(words.size()); + times[j] += st.time(); + fileScanner.close(); + } + } + for(double a : times) + System.out.println(a / NUM_EXP); + } + catch(FileNotFoundException e) + { + System.out.println("Problem reading the data file. Exiting the program." + e); + } + } + + + // pre: titles != null, elements of titles refer to files in the + // same path as this program, numExp >= 0 + // read words from files and print average time to cound words. + private static void timingExpWithArrayList(String[] titles, int numExp) + { + try + { + double[] times = new double[titles.length]; + for(int i = 0; i < numExp; i++) + { + for(int j = 0; j < titles.length; j++) + { + Scanner fileScanner = new Scanner(new File(titles[j])); + Stopwatch st = new Stopwatch(); + st.start(); + ArrayList words = countWordsWithArrayList(fileScanner); + st.stop(); + times[j] += st.time(); + fileScanner.close(); + } + } + for(int i = 0; i < titles.length; i++) + System.out.println("Average time for " + titles[i] + ": " + (times[i] / numExp)); + } + catch(FileNotFoundException e) + { + System.out.println("Problem reading the data file. Exiting the program." + e); + } + } + + + // try to set look and feel to same as system + private static void setLookAndFeel() + { + try + { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch(Exception e) + { + System.out.println("Unable to set look at feel to local settings. " + + "Continuing with default Java look and feel."); + } + } + + + /** Method to choose a file using a window. + * @return the file chosen by the user. Returns null if no file picked. + */ + private static File getFile() + { + // create a GUI window to pick the text to evaluate + JFileChooser chooser = new JFileChooser("."); + chooser.setDialogTitle("Select File To Count Words:"); + int retval = chooser.showOpenDialog(null); + File f =null; + chooser.grabFocus(); + if (retval == JFileChooser.APPROVE_OPTION) + f = chooser.getSelectedFile(); + return f; + } +} diff --git a/java/Basics/Working with static class members.java b/java/Basics/Working with static class members.java new file mode 100644 index 0000000..fd02612 --- /dev/null +++ b/java/Basics/Working with static class members.java @@ -0,0 +1,29 @@ +Working with static class members + + + + + +public class WorkingWithStaticClassMembers { + public static void main( String[] args ) { + Colour background = Colour.a; + } +} + +class Colour { + // take this slowly, you are defining constant class level + // objects for objects of this class - at compile time! boy i like Java! + public static final Colour a = new Colour( 255, 255, 255 ); + public static final Colour b = new Colour( 255, 255, 0 ); + public static final Colour c = new Colour( 255, 0, 0 ); + + private int red; + private int green; + private int blue; + + public Colour( int red, int green, int blue ) { + this.red = red; + this.green = green; + this.blue = blue; + } +} diff --git a/java/Basics/Write a program to remove duplicates from sorted array.java b/java/Basics/Write a program to remove duplicates from sorted array.java new file mode 100644 index 0000000..89862c0 --- /dev/null +++ b/java/Basics/Write a program to remove duplicates from sorted array.java @@ -0,0 +1,33 @@ + package com.scanftree.algos; + public class MyDuplicateElements { + public static int[] removeDuplicates(int[] input) { + int j = 0; + int i = 1; + //return if the array length is less than 2 + if(input.length < 2) { + return input; + } + while(i < input.length) { + if(input[i] == input[j]) { + i++; + } else { + input[++j] = input[i++]; + } + } + int[] output = new int[j+1]; + for (int k=0; k25) +{ +cmas.setFullYear(cmas.getFullYear()+1); +} +var one_day=1000*60*60*24; +console.log(Math.ceil((cmas.getTime()-today.getTime())/(one_day))+ +" days left until Christmas!"); \ No newline at end of file diff --git a/js/Basic/Write a JavaScript program to convert temperatures to and from celsius, fahrenheit..js b/js/Basic/Write a JavaScript program to convert temperatures to and from celsius, fahrenheit..js new file mode 100644 index 0000000..784a3a3 --- /dev/null +++ b/js/Basic/Write a JavaScript program to convert temperatures to and from celsius, fahrenheit..js @@ -0,0 +1,17 @@ +function cToF(celsius) +{ + var cTemp = celsius; + var cToFahr = cTemp * 9 / 5 + 32; + var message = cTemp+'\xB0C is ' + cToFahr + ' \xB0F.'; + console.log(message); +} + +function fToC(fahrenheit) +{ + var fTemp = fahrenheit; + var fToCel = (fTemp - 32) * 5 / 9; + var message = fTemp+'\xB0F is ' + fToCel + '\xB0C.'; + console.log(message); +} +cToF(60); +fToC(45); \ No newline at end of file diff --git a/js/Basic/Write a JavaScript program to determine whether a given year is a leap year in the Gregorian calendar..js b/js/Basic/Write a JavaScript program to determine whether a given year is a leap year in the Gregorian calendar..js new file mode 100644 index 0000000..8f9dd7a --- /dev/null +++ b/js/Basic/Write a JavaScript program to determine whether a given year is a leap year in the Gregorian calendar..js @@ -0,0 +1,3 @@ +year = window.prompt("Input a Year : "); +x = (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0); +alert(x); \ No newline at end of file diff --git a/js/Basic/Write a JavaScript program to display the current day and time in the following format..js b/js/Basic/Write a JavaScript program to display the current day and time in the following format..js new file mode 100644 index 0000000..4756ffa --- /dev/null +++ b/js/Basic/Write a JavaScript program to display the current day and time in the following format..js @@ -0,0 +1,38 @@ +var today = new Date(); +var day = today.getDay(); +var daylist = ["Sunday","Monday","Tuesday","Wednesday ","Thursday","Friday","Saturday"]; +console.log("Today is : " + daylist[day] + "."); +var hour = today.getHours(); +var minute = today.getMinutes(); +var second = today.getSeconds(); +var prepand = (hour >= 12)? " PM ":" AM "; +hour = (hour >= 12)? hour - 12: hour; + +if (hour===0 && prepand===' PM ') +{ + +if (minute===0 && second===0) +{ +hour=12; +prepand=' Noon'; +} +else +{ +hour=12; +prepand=' PM'; +} +} +if (hour===0 && prepand===' AM ') +{ +if (minute===0 && second===0) +{ +hour=12; +prepand=' Midnight'; +} +else +{ +hour=12; +prepand=' AM'; +} +} +console.log("Current Time : "+hour + prepand + " : " + minute + " : " + second); \ No newline at end of file diff --git a/js/Basic/Write a JavaScript program to find which 1st January is being a Sunday between 2014 and 2050..js b/js/Basic/Write a JavaScript program to find which 1st January is being a Sunday between 2014 and 2050..js new file mode 100644 index 0000000..2f56a30 --- /dev/null +++ b/js/Basic/Write a JavaScript program to find which 1st January is being a Sunday between 2014 and 2050..js @@ -0,0 +1,8 @@ +console.log('--------------------'); +for (var year = 2014; year <= 2050; year++) + { + var d = new Date(year, 0, 1); + if ( d.getDay() === 0 ) + console.log("1st January is being a Sunday "+year); + } +console.log('--------------------'); \ No newline at end of file diff --git a/js/Basic/Write a JavaScript program to get the current date..js b/js/Basic/Write a JavaScript program to get the current date..js new file mode 100644 index 0000000..4200b38 --- /dev/null +++ b/js/Basic/Write a JavaScript program to get the current date..js @@ -0,0 +1,22 @@ +var today = new Date(); +var dd = today.getDate(); + +var mm = today.getMonth()+1; +var yyyy = today.getFullYear(); +if(dd<10) +{ + dd='0'+dd; +} + +if(mm<10) +{ + mm='0'+mm; +} +today = mm+'-'+dd+'-'+yyyy; +console.log(today); +today = mm+'/'+dd+'/'+yyyy; +console.log(today); +today = dd+'-'+mm+'-'+yyyy; +console.log(today); +today = dd+'/'+mm+'/'+yyyy; +console.log(today); \ No newline at end of file diff --git a/js/Basic/Write a JavaScript program to get the website URL (loading page)..js b/js/Basic/Write a JavaScript program to get the website URL (loading page)..js new file mode 100644 index 0000000..8144450 --- /dev/null +++ b/js/Basic/Write a JavaScript program to get the website URL (loading page)..js @@ -0,0 +1,2 @@ +//Write a JavaScript program to get the website URL (loading page) +alert(document.URL); \ No newline at end of file diff --git a/js/Basic/Write a JavaScript program where the program takes a random integer between 1 to 10, the user is then prompted to input a guess number..js b/js/Basic/Write a JavaScript program where the program takes a random integer between 1 to 10, the user is then prompted to input a guess number..js new file mode 100644 index 0000000..f231585 --- /dev/null +++ b/js/Basic/Write a JavaScript program where the program takes a random integer between 1 to 10, the user is then prompted to input a guess number..js @@ -0,0 +1,7 @@ +// Get a random integer from 1 to 10 inclusive + var num = Math.ceil(Math.random() * 10); + var gnum = prompt('Guess the number between 1 and 10 inclusive'); + if (gnum == num) + alert('Matched'); + else + alert('Not matched, the number was ' + num); \ No newline at end of file diff --git a/js/README.md b/js/README.md new file mode 100644 index 0000000..8d4b9fb --- /dev/null +++ b/js/README.md @@ -0,0 +1,3 @@ +# JavaScript scripting language + +JavaScript often abbreviated as JS, is a high-level, interpreted scripting language that conforms to the ECMAScript specification. It's mostly used by web-development. \ No newline at end of file diff --git a/perl/Basics/! $v1 && $v2.pl b/perl/Basics/! $v1 && $v2.pl new file mode 100644 index 0000000..57ea67a --- /dev/null +++ b/perl/Basics/! $v1 && $v2.pl @@ -0,0 +1,13 @@ + + +$v1 = 1; +$v2 = 0; +$v3 = ! $v1 && $v2; +if($v3) { + print "\$v3 is true."; +} +else { + print "\$v3 is false."; +} + + \ No newline at end of file diff --git a/perl/Basics/A program that uses the pre-increment operation..pl b/perl/Basics/A program that uses the pre-increment operation..pl new file mode 100644 index 0000000..943c118 --- /dev/null +++ b/perl/Basics/A program that uses the pre-increment operation..pl @@ -0,0 +1,8 @@ +#!/usr/local/bin/perl +$value = 0; +while (++$value <= 5) { + print("value is now $value\n"); +} +print("all done\n"); + + \ No newline at end of file diff --git a/perl/Basics/Adding a number and a string.pl b/perl/Basics/Adding a number and a string.pl new file mode 100644 index 0000000..f2b5f58 --- /dev/null +++ b/perl/Basics/Adding a number and a string.pl @@ -0,0 +1,8 @@ +$string = "Top 10"; +$number = 10.0; +print "Number is 10.0 and string is 'Top 10'\n\n"; + +$add = $number + $string; +print "Adding a number and a string: $add\n"; + + \ No newline at end of file diff --git a/perl/Basics/After incrementing.pl b/perl/Basics/After incrementing.pl new file mode 100644 index 0000000..cc8050a --- /dev/null +++ b/perl/Basics/After incrementing.pl @@ -0,0 +1,8 @@ + +#!/usr/bin/perl -w + +$a = 4; +$b = 10; +print "Our variables are ", $a, " and ", $b, "\n"; +$b = $a++; +print "After incrementing, we have ", $a, " and ", $b, "\n"; diff --git a/perl/Basics/After pre-decrement.pl b/perl/Basics/After pre-decrement.pl new file mode 100644 index 0000000..a7b6a6a --- /dev/null +++ b/perl/Basics/After pre-decrement.pl @@ -0,0 +1,8 @@ +#!/usr/bin/perl -w + +$a = 4; +$b = 10; +print "Our variables are ", $a, " and ", $b, "\n"; + +$a = --$b + 4; +print "Finally, we have ", $a, " and ", $b, "\n"; \ No newline at end of file diff --git a/perl/Basics/Arithmetic Operators in action.pl b/perl/Basics/Arithmetic Operators in action.pl new file mode 100644 index 0000000..bb356ee --- /dev/null +++ b/perl/Basics/Arithmetic Operators in action.pl @@ -0,0 +1,7 @@ + + +printf "%d\n", 4 * 5 / 2; +printf "%d\n", 5 ** 3; +printf "%d\n", 5 + 4 - 2 * 10; +printf "%d\n", (5 + 4 - 2 ) * 10; +printf "%d\n", 11 % 2; diff --git a/perl/Basics/Assign value to four variables.pl b/perl/Basics/Assign value to four variables.pl new file mode 100644 index 0000000..2039426 --- /dev/null +++ b/perl/Basics/Assign value to four variables.pl @@ -0,0 +1,10 @@ +#!C:\perl\bin + +$age = $myage = $herage = $hisage = 25; + +print "\$age = $age\n\n"; +print "\$myage = $myage\n\n"; +print "\$herage = $herage\n\n"; +print "\$hisage = $hisage\n\n"; + + \ No newline at end of file diff --git a/perl/Basics/Assignment Operators.pl b/perl/Basics/Assignment Operators.pl new file mode 100644 index 0000000..1cb7319 --- /dev/null +++ b/perl/Basics/Assignment Operators.pl @@ -0,0 +1,15 @@ +Operator Example Meaning += $var = 5; Assign 5 to $var ++= $var += 3; Add +-= $var -= 2; Subtract +.= $str.="ing"; Concatenate ing to $str +*= $var *= 2; Multiply $var by 2 +/= $var /= 2; Divide $var by 2 +**= $var **= 2; Square $var +%= $var %= 2; Divide $var by 2 +x= $str x= 2; Repeat value of $str 2 times +<<= $var <<= 1; Left-shift bits in $var one position +>>= $var>>= 2; Right-shift bits in $var two positions +&= $var &= 1; One is bitwise-ANDed to $var +|= $var |= 2; Two is bitwise-ORed to $var +^= $var ^= 2; Two is bitwise-exclusive ORed to $var \ No newline at end of file diff --git a/perl/Basics/Assignment Statements.pl b/perl/Basics/Assignment Statements.pl new file mode 100644 index 0000000..0aa5501 --- /dev/null +++ b/perl/Basics/Assignment Statements.pl @@ -0,0 +1,14 @@ + +variable=expression; + + +$salary=50000; # Scalar assignment +@months=('Mar', 'Apr', 'May'); # Array assignment +%states= ( # Hash assignment + 'CA' => 'California', + 'NM' => 'New Mexico', + ); + + + + \ No newline at end of file diff --git a/perl/Basics/Autoincrement and Autodecrement Operators and Assignment.pl b/perl/Basics/Autoincrement and Autodecrement Operators and Assignment.pl new file mode 100644 index 0000000..c6662d9 --- /dev/null +++ b/perl/Basics/Autoincrement and Autodecrement Operators and Assignment.pl @@ -0,0 +1,15 @@ + +#!/usr/bin/perl +$x=5; $y=0; +$y=++$x; # Add 1 to $x first; then assign to $y +print "Pre-increment:\n"; +print "y is $y\n"; +print "x is $x\n"; + + +$x=5; +$y=0; +print "Post-increment:\n"; +$y=$x++; # Assign value in $x to $y; then add 1 to $x +print "y is $y\n"; +print "x is $x\n"; diff --git a/perl/Basics/Basic Math Compound Assignment Statements.pl b/perl/Basics/Basic Math Compound Assignment Statements.pl new file mode 100644 index 0000000..843f8f0 --- /dev/null +++ b/perl/Basics/Basic Math Compound Assignment Statements.pl @@ -0,0 +1,24 @@ + +#! /usr/local/bin/perl +$a = 5; +print "\$a equals $a before the operation.\n "; + +$a += 4.2; +print "The result of \$a += 4.2 is $a \n"; +print "\$a equals $a before the operation.\n "; + +$a -= 4.2; +print "The result of \$a -= 4.2 is $a \n"; +print "\$a equals $a before the operation.\n "; + +$a *= 4.2; +print "The result of \$a *= 4.2 is $a \n"; +print "\$a equals $a before the operation.\n "; + +$a /= 6; + +print "The result of \$a /= 6 is $a \n"; +print "\$a equals $a before the operation.\n "; + +$a %= 6; +print "The result of \$a %= 6 is $a \n"; diff --git a/perl/Basics/Basic Numeric Operations.pl b/perl/Basics/Basic Numeric Operations.pl new file mode 100644 index 0000000..554578c --- /dev/null +++ b/perl/Basics/Basic Numeric Operations.pl @@ -0,0 +1,17 @@ +#! /usr/local/bin/perl + +$a = 4.2 + 3; +print "The result of 4.2 + 3 is $a \n"; + +$a = 4.2 - 3; +print "The result of 4.2 - 3 is $a \n"; + +$a = 4.2 * 3; +print "The result of 4.2 * 3 is $a \n"; + +$a = 26 / 8; +print "The result of 26 / 8 is $a \n"; + +$a = 26 % 8; + +print "The result of 26 % 8 is $a \n"; diff --git a/perl/Basics/Bitwise And Operators in action.pl b/perl/Basics/Bitwise And Operators in action.pl new file mode 100644 index 0000000..d4e77fa --- /dev/null +++ b/perl/Basics/Bitwise And Operators in action.pl @@ -0,0 +1,7 @@ + + +print 5 & 4,"\n"; # 101 & 100 +print 5 & 0,"\n"; # 101 & 000 +print 4 & 0,"\n"; # 100 & 000 +print 0 & 4,"\n"; # 000 & 100 +print "=" x 10,"\n"; # print 10 equal signs \ No newline at end of file diff --git a/perl/Basics/Bitwise Logical Operators.pl b/perl/Basics/Bitwise Logical Operators.pl new file mode 100644 index 0000000..e3c409e --- /dev/null +++ b/perl/Basics/Bitwise Logical Operators.pl @@ -0,0 +1,7 @@ + +Operator Example Meaning +& $x & $y Bitwise and +| $x | $y Bitwise or +^ $x ^ $y Bitwise exclusive or +<< $x << 1 Bitwise left shift, integer multiply by two +>> $x >> 1 Bitwise right shift, integer divide by two \ No newline at end of file diff --git a/perl/Basics/Bitwise Or Operators in action.pl b/perl/Basics/Bitwise Or Operators in action.pl new file mode 100644 index 0000000..8adfce0 --- /dev/null +++ b/perl/Basics/Bitwise Or Operators in action.pl @@ -0,0 +1,7 @@ + +print 1 | 4,"\n"; # 001 & 100 +print 5 | 0,"\n"; # 101 | 000 +print 4 | 0,"\n"; # 100 | 000 +print 0 | 4,"\n"; # 000 | 100 + +print "=" x 10,"\n"; # print 10 equal signs diff --git a/perl/Basics/Bitwise operator.pl b/perl/Basics/Bitwise operator.pl new file mode 100644 index 0000000..7f315d3 --- /dev/null +++ b/perl/Basics/Bitwise operator.pl @@ -0,0 +1,17 @@ + +#!/usr/bin/perl + +use warnings; +use strict; + +my $a = 3; +my $b = 6; +my $r; + +printf "$a = %03b \n", $a; +printf "$b = %03b \n", $b; + +$r = $a & $b; printf "$a & $b = %03b = %d\n", $r, $r; +$r = $a | $b; printf "$a | $b = %03b = %d\n", $r, $r; +$r = $a ^ $b; printf "$a ^ $b = %03b = %d\n", $r, $r; +$r = ~$a; printf "~$a = %03b = %d\n", $r, $r; diff --git a/perl/Basics/Boolean and &&.pl b/perl/Basics/Boolean and &&.pl new file mode 100644 index 0000000..6d5fcea --- /dev/null +++ b/perl/Basics/Boolean and &&.pl @@ -0,0 +1,11 @@ + + +print "Please enter positive numbers up to 100\n"; +while (<>) { + chomp; + if ($_ > 0 && $_ < 100) { + print "Thank you - let's have another!\n"; + } else { + print "Please enter positive numbers up to 100\n"; + } +} diff --git a/perl/Basics/Boolean operator.pl b/perl/Basics/Boolean operator.pl new file mode 100644 index 0000000..b023e87 --- /dev/null +++ b/perl/Basics/Boolean operator.pl @@ -0,0 +1,15 @@ + +print "Please enter numbers from 5 to 10\n"; + +while (<>) { + chop; + if ($_ < 5 || $_ > 10) { + print "Please enter numbers from 5 to 10\n"; + } else { + print "Thank you - let's have another!\n"; + } +} + + + + \ No newline at end of file diff --git a/perl/Basics/Built-in Perl Arithmetic Functions.pl b/perl/Basics/Built-in Perl Arithmetic Functions.pl new file mode 100644 index 0000000..70b215b --- /dev/null +++ b/perl/Basics/Built-in Perl Arithmetic Functions.pl @@ -0,0 +1,27 @@ +atan2(Y,X) Returns the arctangent of Y/X. + +cos(EXPR) +cos EXPR Returns the cosine of EXPR in radians. If EXPR is omitted, takes cosine of $_. + +exp(EXPR) +exp EXPR Returns e to the power of EXPR. If EXPR is omitted, gives exp($_). + +int(EXPR) +int EXPR Returns the integer portion of EXPR. If EXPR is omitted, uses $_. + +log(EXPR) +log EXPR Returns logarithm (base e) of EXPR. If EXPR is omitted, returns log of $_. + +rand(EXPR) +rand EXPR +rand Returns a random fractional number between 0 and the value of EXPR. + If EXPR is omitted, returns a value between 0 and 1. + +sin(EXPR) +sin EXPR Returns the sine of EXPR in radians. If EXPR is omitted, returns sine of $_. + +sqrt(EXPR) +sqrt EXPR Return the square root of EXPR. If EXPR is omitted, returns square root of $_. + +srand(EXPR) +srand EXPR Sets the random number seed for the rand operator. If EXPR is omitted, does srand(time). \ No newline at end of file diff --git a/perl/Basics/Complex Assignment.pl b/perl/Basics/Complex Assignment.pl new file mode 100644 index 0000000..d9754e4 --- /dev/null +++ b/perl/Basics/Complex Assignment.pl @@ -0,0 +1,16 @@ + + +$degrees = 2; + +($degrees += 100) *= 700; + +print $degrees; + + +$degrees = 2; + +$degrees += 100; +$degrees *= 700; + + +print $degrees; diff --git a/perl/Basics/Compound Assignment Operators.pl b/perl/Basics/Compound Assignment Operators.pl new file mode 100644 index 0000000..fee63ba --- /dev/null +++ b/perl/Basics/Compound Assignment Operators.pl @@ -0,0 +1,31 @@ +Operator Example Meaning + ++= $a += 3; Add + +-= $a -= 3; Subtract + +*= $a *= 3; Multiply + +/= $a /= 3; Divide + +**= $a **= 3; Raise the power + +%= $a %= 3; Modulo + +.= $a .= "String Value"; Append + +x= $a x= 3; Multiply (replicate) the expression (string) + +&= $a &= 3; Binary AND + +|= $a |= 3; Binary OR + +^= $a ^= 3; Exclusive OR + +<<= $a <<= 3; Left shift + +>>= $a >>= 3; Right shift + +&&= $a &&= 1; Logical AND + +||= $a ||= 0; Logical OR \ No newline at end of file diff --git a/perl/Basics/Compound operator.pl b/perl/Basics/Compound operator.pl new file mode 100644 index 0000000..58d769d --- /dev/null +++ b/perl/Basics/Compound operator.pl @@ -0,0 +1,13 @@ + +#!/usr/bin/perl -w + +$a = 6 * 9; +print "Six nines are ", $a, "\n"; +$a += 3; +print "Plus three is ", $a, "\n"; +$a /= 3; +print "All over three is ", $a, "\n"; +$a += 1; +print "Add one is ", $a, "\n"; + + \ No newline at end of file diff --git a/perl/Basics/Demonstrates the difference between pre- and postincrement.pl b/perl/Basics/Demonstrates the difference between pre- and postincrement.pl new file mode 100644 index 0000000..ccf6678 --- /dev/null +++ b/perl/Basics/Demonstrates the difference between pre- and postincrement.pl @@ -0,0 +1,11 @@ + +$c = 5; +$d = 5; + +print $c, " "; +print $c++, " "; +print $c, "\n"; + +print $d, " "; +print ++$d, " "; +print $d, "\n"; diff --git a/perl/Basics/Getting Input in Perl Scripts.pl b/perl/Basics/Getting Input in Perl Scripts.pl new file mode 100644 index 0000000..c20cd9f --- /dev/null +++ b/perl/Basics/Getting Input in Perl Scripts.pl @@ -0,0 +1,14 @@ +# Note the extra space after the question mark. +print "What is your favorite scripting language? "; + +$subLang = ; + +chomp($subLang); + +if ( $subLang eq "perl" ) { + print "you chose perl!\n"; +} else { + print "$subLang "; +} + + \ No newline at end of file diff --git a/perl/Basics/Increment and Decrement Operations.pl b/perl/Basics/Increment and Decrement Operations.pl new file mode 100644 index 0000000..26d163e --- /dev/null +++ b/perl/Basics/Increment and Decrement Operations.pl @@ -0,0 +1,14 @@ +#! /usr/local/bin/perl +$a=15; +$b = ++$a -15; +$c = $a++ - 15; + +print "The increment operation occurs first on the left side\n"; +print "$b = ++$a - 15 results in $b equal "; +print "$b\n"; +print "The increment operation occurs after other operations when on the right side\n"; +print "$c = $a- - 15 results in $c equal "; +print "$c\n"; + + + \ No newline at end of file diff --git a/perl/Basics/Logical Word Operators.pl b/perl/Basics/Logical Word Operators.pl new file mode 100644 index 0000000..bc1edcb --- /dev/null +++ b/perl/Basics/Logical Word Operators.pl @@ -0,0 +1,11 @@ +$num1=50; +$num2=100; +$num3=0; +print "\nOutput using the word operators.\n\n"; +print "\n$num1 and $num2: ",($num1 and $num2), "\n"; +print "\n$num1 or $num3: ", ($num1 or $num3), "\n"; +print "\n$num1 xor $num3: ",($num1 xor $num3), "\n"; +print "\nnot $num3: ", not $num3; +print "\n"; + + \ No newline at end of file diff --git a/perl/Basics/Logical operators are defined.pl b/perl/Basics/Logical operators are defined.pl new file mode 100644 index 0000000..a7429f2 --- /dev/null +++ b/perl/Basics/Logical operators are defined.pl @@ -0,0 +1,12 @@ + + +$a || $b # logical or: true if either is nonzero +$a && $b # logical and: true only if both are nonzero +! $a # logical not: true if $a is zero +Perl 5 also defines these logical operators: +$a or $b # another form of logical or +$a and $b # another form of logical and +not $a # another form of logical not +$a xor $b # logical xor: true if either $a or $b is nonzero, but not both + + \ No newline at end of file diff --git a/perl/Basics/OPERATOR PURPOSENumeric operators.pl b/perl/Basics/OPERATOR PURPOSENumeric operators.pl new file mode 100644 index 0000000..29bb536 --- /dev/null +++ b/perl/Basics/OPERATOR PURPOSENumeric operators.pl @@ -0,0 +1,51 @@ +OPERATOR PURPOSE + ++ Computes the additive value of the two operands. + + Computes the difference between the two operands. + +* Computes the multiplication of the two operands. + +/ Computes the division between the two operands. + +% Computes the modulus (remainder) of the two operands. + +== Returns True if the two operands are equal, False otherwise. + +!= Returns True if the two operands are not equal, False otherwise. + +>= Greater than. + +<= Less than. + +> + +<=> Returns -1 if the left operand is less than the right, +1 if is it greater than, and 0 (False) otherwise. + +&& a logical AND operation. + +|| a logical OR operation. + +& Returns the value of the two operators bitwise ANDed. + +| Returns the value of the two operators bitwise ORed. + +~ Returns the value of the two operators bitwise XORed. + +++ Increment operator. Increments the variable's value by 1. + +-- Decrement operator. Decrements the variable's value by 1. + +xx Computes the power of the left value to the power of the right value. + ++= Adds the value of the right operand to the value of the left operand. + +-= Subtracts the value of the right operand from the value of the left operand. + +x= Multiplies the value of the left operand with the value of the right operand. + +>> Shifts the left operand right by the number of bits specified by the right operand. + +<< Shifts the left operand left by the number of bits specified by the right operand. + +~ Performs a 1s complement of the operator. This is a unary operator. \ No newline at end of file diff --git a/perl/Basics/Operating and Assigning at Once.pl b/perl/Basics/Operating and Assigning at Once.pl new file mode 100644 index 0000000..c9f507b --- /dev/null +++ b/perl/Basics/Operating and Assigning at Once.pl @@ -0,0 +1,14 @@ + +#!/usr/bin/perl + +use warnings; +$a = 6 * 9; +print "Six nines are ", $a, "\n"; +$a += 3; +print "Plus three is ", $a, "\n"; +$a /= 3; +print "All over three is ", $a, "\n"; +$a += 1; +print "Add one is ", $a, "\n"; + + \ No newline at end of file diff --git a/perl/Basics/Post-increment operation..pl b/perl/Basics/Post-increment operation..pl new file mode 100644 index 0000000..43ce2c7 --- /dev/null +++ b/perl/Basics/Post-increment operation..pl @@ -0,0 +1,7 @@ + +#!/usr/local/bin/perl +$value = 0; +while ($value++ <= 5) { + print("value is now $value\n"); +} +print("all done\n"); diff --git a/perl/Basics/Precedence and Associativity.pl b/perl/Basics/Precedence and Associativity.pl new file mode 100644 index 0000000..9a1f271 --- /dev/null +++ b/perl/Basics/Precedence and Associativity.pl @@ -0,0 +1,22 @@ +Operator Description Associativity +() [ ] { } Function call, array subscripts Left to right +** Exponentiation Right to left +! ~ \ + - Logical not, bitwise not, backslash, plus,minus Right to left +=~ !~ Match and not match Left to right +* / % x Multiply, divide, modulus, string repetition Left to right ++ -. Add, subtract, string concatenation Left to right +<< >> Bitwise left shift, right shift Left to right +-r -w -x -o etc. File test operators None +< <= > >= lt le gt ge Numeric and string: less than, greater than, etc. None +== != <=> eq ne cmp Numeric and string: equal to, not equal to, etc. None +& Bitwise and Left to right +| ^ Bitwise or, exclusive or (xor) Left to right +&& Logical and Left to right +|| Logical or Left to right +.. Range operator None +? : Ternary, conditional Right to left += += -= *= /= %= Assignment Right to left +, => Left to right +not ! Right +and && Left to right +or xor ||, ^ Left to right \ No newline at end of file diff --git a/perl/Basics/Precedence with word operators and short-circuit operators.pl b/perl/Basics/Precedence with word operators and short-circuit operators.pl new file mode 100644 index 0000000..4792408 --- /dev/null +++ b/perl/Basics/Precedence with word operators and short-circuit operators.pl @@ -0,0 +1,12 @@ + +$x=5; +$y=6; +$z=0; +$result=$x && $y && $z; # Precedence of = lower than && +print "Result: $result\n"; + +$result2 = $x and $y and $z; # Precedence of = higher than and +print "Result: $result2\n"; + +$result3 = ( $x and $y and $z ); +print "Result: $result3\n"; diff --git a/perl/Basics/Read user input and use if statement to check it.pl b/perl/Basics/Read user input and use if statement to check it.pl new file mode 100644 index 0000000..4e5e145 --- /dev/null +++ b/perl/Basics/Read user input and use if statement to check it.pl @@ -0,0 +1,24 @@ + +#!/usr/bin/perl + +use warnings; +use strict; +my $weather = "good"; +print "How hot is it, in degrees? "; +my $temperature = ; +print "And how many emails left to reply to? "; +my $work = ; +chomp($weather, $temperature); +if ($weather eq "snowing") { + print "OK, let's go!\n"; +} elsif ($weather eq "raining") { + print "No way, sorry, I'm staying in.\n"; +} elsif ($temperature < 18) { + print "Too cold for me!\n"; +} elsif ($work > 30) { + print "Sorry just too busy.\n"; +} else { + print "Well, why not?\n"; +} + + \ No newline at end of file diff --git a/perl/Basics/Remainder and power.pl b/perl/Basics/Remainder and power.pl new file mode 100644 index 0000000..f453045 --- /dev/null +++ b/perl/Basics/Remainder and power.pl @@ -0,0 +1,26 @@ +#!C:\perl\bin + +$b = 7; +$size = 25; +$othervalue = 12; +$mass = 10; +$acceleration = 14; +$minutes = 600; +$num = 12; + +$a = $b + 5; + +$size = $size - $othervalue; +print "\$size = $size\n\n"; + +$speed = $mass * $acceleration; +print "\$speed = $speed\n\n"; + +$hours = $minutes / 60; +print "\$hours = $hours\n\n"; + +$remainder = 5 % 2; +print "\$remainder = $remainder\n\n"; + +$square = $num ** 2; +print "\$square = $square\n\n"; \ No newline at end of file diff --git a/perl/Basics/Short-circuit operators.pl b/perl/Basics/Short-circuit operators.pl new file mode 100644 index 0000000..b730cd5 --- /dev/null +++ b/perl/Basics/Short-circuit operators.pl @@ -0,0 +1,15 @@ +#!/usr/bin/perl + +$num1=50; +$num2=100; +$num3=0; + +print $num1 && $num3, "\n"; +print $num3 && $num1, "\n"; +print $num1 && $num2, "\n"; +print $num2 && $num1, "\n\n"; + +print $num1 || $num3, "\n"; +print $num3 || $num1, "\n"; +print $num1 || $num2, "\n"; +print $num2 || $num1, "\n"; \ No newline at end of file diff --git a/perl/Basics/Square $var.pl b/perl/Basics/Square $var.pl new file mode 100644 index 0000000..6bf68bd --- /dev/null +++ b/perl/Basics/Square $var.pl @@ -0,0 +1,6 @@ +#!/usr/bin/perl + +$var=0; + +$var **= 2; # Square $var +print "\$var squared is $var\n"; diff --git a/perl/Basics/Subtract 1 from $var.pl b/perl/Basics/Subtract 1 from $var.pl new file mode 100644 index 0000000..20e9f29 --- /dev/null +++ b/perl/Basics/Subtract 1 from $var.pl @@ -0,0 +1,7 @@ + +#!/usr/bin/perl + +$var=0; + +$var -= 1; # Subtract 1 from $var +print "\$var -= 1 is $var\n"; diff --git a/perl/Basics/The assignment operators.pl b/perl/Basics/The assignment operators.pl new file mode 100644 index 0000000..2643fdb --- /dev/null +++ b/perl/Basics/The assignment operators.pl @@ -0,0 +1,11 @@ +Operator Operations performed += Assignment only ++= Addition and assignment +-= Subtraction and assignment +*= Multiplication and assignment +/= Division and assignment +%= Remainder and assignment +**= Exponentiation and assignment +&= Bitwise AND and assignment +|= Bitwise OR and assignment +^= Bitwise XOR and assignment diff --git a/perl/Basics/The autoincrement operator.pl b/perl/Basics/The autoincrement operator.pl new file mode 100644 index 0000000..c2ec299 --- /dev/null +++ b/perl/Basics/The autoincrement operator.pl @@ -0,0 +1,9 @@ + +#!/usr/bin/perl + +use warnings; +$a = "A9"; print ++$a, "\n"; +$a = "bc"; print ++$a, "\n"; +$a = "Zc"; print ++$a, "\n"; +$a = "z9"; print ++$a, "\n"; +$a = "9z"; print ++$a, "\n"; diff --git a/perl/Basics/To set a variable, use the = operator.pl b/perl/Basics/To set a variable, use the = operator.pl new file mode 100644 index 0000000..65a11c9 --- /dev/null +++ b/perl/Basics/To set a variable, use the = operator.pl @@ -0,0 +1,6 @@ +# Setting scalar variables. +$var = "Text"; +$number_var = 44.5; + +print $var; +print $number_var; diff --git a/perl/Basics/Use parentheses wherever possible to force precedence.pl b/perl/Basics/Use parentheses wherever possible to force precedence.pl new file mode 100644 index 0000000..f53e8dd --- /dev/null +++ b/perl/Basics/Use parentheses wherever possible to force precedence.pl @@ -0,0 +1,22 @@ + + + #!/usr/local/bin/perl -w + + print "Enter the first number : "; + my $num1 = ; chomp $num1; + print "Enter the second number: "; + my $num2 = ; chomp $num2; + print "Enter the third number : "; + my $num3 = ; chomp $num3; + + # A*B-C + my $answer = $num1 * $num2 - $num3; + print "$num1 * $num2 - $num3 = $answer \n"; + + # (A*B)-C + $answer = ($num1 * $num2) - $num3; + print "($num1 * $num2) - $num3 = $answer \n"; + + # A*(B-C) + $answer = $num1 * ($num2 - $num3); + print "$num1 * ($num2 - $num3) = $answer \n"; diff --git a/perl/Basics/Using Assignment Operators on Scalar Variables.pl b/perl/Basics/Using Assignment Operators on Scalar Variables.pl new file mode 100644 index 0000000..7bf8e34 --- /dev/null +++ b/perl/Basics/Using Assignment Operators on Scalar Variables.pl @@ -0,0 +1,16 @@ +#How do you place data in a scalar variable? +#You use the assignment operator. + +$variable1 = 5; + +#String assignments work much the same way: + +$variable1 = "Hello there!"; + +#Besides single assignments, you can create multiple assignments in the same statement like this: + +$x = $y = $z = 1; +print join (", ", $x, $y, $z); + + + \ No newline at end of file diff --git a/perl/Basics/Using auto-increment operator for a string with digits.pl b/perl/Basics/Using auto-increment operator for a string with digits.pl new file mode 100644 index 0000000..9d7977e --- /dev/null +++ b/perl/Basics/Using auto-increment operator for a string with digits.pl @@ -0,0 +1,6 @@ + +#!/usr/bin/perl -w + +$a = "A9"; print ++$a, "\n"; +$a = "z9"; print ++$a, "\n"; +$a = "9z"; print ++$a, "\n"; diff --git a/perl/Basics/Using auto-increment operator for a string.pl b/perl/Basics/Using auto-increment operator for a string.pl new file mode 100644 index 0000000..327f0f4 --- /dev/null +++ b/perl/Basics/Using auto-increment operator for a string.pl @@ -0,0 +1,5 @@ + +#!/usr/bin/perl -w + +$a = "bz"; print ++$a, "\n"; +$a = "Zz"; print ++$a, "\n"; diff --git a/perl/README.md b/perl/README.md new file mode 100644 index 0000000..2dead60 --- /dev/null +++ b/perl/README.md @@ -0,0 +1,3 @@ +# Perl programming language + +Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more. \ No newline at end of file diff --git a/php/Basics/Add two numbers Program in PHP.php b/php/Basics/Add two numbers Program in PHP.php new file mode 100644 index 0000000..9c4a746 --- /dev/null +++ b/php/Basics/Add two numbers Program in PHP.php @@ -0,0 +1,11 @@ + + +/* Output : Sum: 30*/ \ No newline at end of file diff --git a/php/Basics/Armstrong number Program in PHP.php b/php/Basics/Armstrong number Program in PHP.php new file mode 100644 index 0000000..a9b4ccd --- /dev/null +++ b/php/Basics/Armstrong number Program in PHP.php @@ -0,0 +1,26 @@ + + +/* +Output + +Armstrong number \ No newline at end of file diff --git a/php/Basics/Even Odd number program in PHP.php b/php/Basics/Even Odd number program in PHP.php new file mode 100644 index 0000000..e965ef0 --- /dev/null +++ b/php/Basics/Even Odd number program in PHP.php @@ -0,0 +1,14 @@ + \ No newline at end of file diff --git a/php/Basics/Factorial of a number in PHP.php b/php/Basics/Factorial of a number in PHP.php new file mode 100644 index 0000000..4242e53 --- /dev/null +++ b/php/Basics/Factorial of a number in PHP.php @@ -0,0 +1,16 @@ +=1; $x--) +{ + $factorial = $factorial * $x; +} +echo "Factorial of $num is $factorial"; + +?> + +/* +Output + +Factorial of 4 is 24 \ No newline at end of file diff --git a/php/Basics/Fibonacci Series Program in PHP.php b/php/Basics/Fibonacci Series Program in PHP.php new file mode 100644 index 0000000..4e15c5d --- /dev/null +++ b/php/Basics/Fibonacci Series Program in PHP.php @@ -0,0 +1,30 @@ + +/* Output Fibonacci Series 0 1 1 2 3 5 */ \ No newline at end of file diff --git a/php/Basics/Number Pattern Problems in PHP.php b/php/Basics/Number Pattern Problems in PHP.php new file mode 100644 index 0000000..19ef43f --- /dev/null +++ b/php/Basics/Number Pattern Problems in PHP.php @@ -0,0 +1,59 @@ +/* Print number Pattern in PHP */ +=1; $b--) +{ +echo "$b"; +} +echo "
"; +} + +?> +/* Output + +1 +21 +321 +4321 */ + /* Print number Pattern in PHP */ +=1; $a--) +{ +for($b=1; $b<=$a; $b++) +{ +echo $b; +} + echo "
"; +} + +?> + /* Output + +12345 +1234 +123 +12 +1 */ +/* Print number Pattern in PHP */ +=1; $a--) +{ +for($b=5; $b>=$a; $b--) +{ +echo $b; +} + echo "
"; +} + +?> + /* Output + +5 +54 +543 +5432 +54321 */ \ No newline at end of file diff --git a/php/Basics/PHP Program for Bubble sorting in PHP.php b/php/Basics/PHP Program for Bubble sorting in PHP.php new file mode 100644 index 0000000..0cec82d --- /dev/null +++ b/php/Basics/PHP Program for Bubble sorting in PHP.php @@ -0,0 +1,24 @@ +// Write a Program for Bubble sorting in PHP + + $numbers[$d+1]) /* For decreasing order use < */ + { + $swap = $numbers[$d]; + $numbers[$d] = $numbers[$d+1]; + $numbers[$d+1] = $swap; + } + } + } + +echo "Sorted list in ascending order
"; + + for ( $c = 0 ; $c < $n ; $c++ ) + echo $numbers[$c]." "; + +?> \ No newline at end of file diff --git a/php/Basics/PHP Program for finding the biggest number in an array without using any array functions.php b/php/Basics/PHP Program for finding the biggest number in an array without using any array functions.php new file mode 100644 index 0000000..7645db5 --- /dev/null +++ b/php/Basics/PHP Program for finding the biggest number in an array without using any array functions.php @@ -0,0 +1,15 @@ +// Write a Program for finding the biggest number in an array without using any array functions. + +$max) + { + $max=$numbers[$i]; + } + } +echo "The biggest number is ".$max; +?> \ No newline at end of file diff --git a/php/Basics/PHP Program for finding the smallest number in an array.php b/php/Basics/PHP Program for finding the smallest number in an array.php new file mode 100644 index 0000000..178fa55 --- /dev/null +++ b/php/Basics/PHP Program for finding the smallest number in an array.php @@ -0,0 +1,16 @@ +// Write a Program for finding the smallest number in an array + + \ No newline at end of file diff --git a/php/Basics/PHP Program to find whether a year is LEAP year or not.php b/php/Basics/PHP Program to find whether a year is LEAP year or not.php new file mode 100644 index 0000000..896dad6 --- /dev/null +++ b/php/Basics/PHP Program to find whether a year is LEAP year or not.php @@ -0,0 +1,14 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to add the digits of a positive integer repeatedly until the result has a single digit..php b/php/Basics/PHP program to add the digits of a positive integer repeatedly until the result has a single digit..php new file mode 100644 index 0000000..4ebf312 --- /dev/null +++ b/php/Basics/PHP program to add the digits of a positive integer repeatedly until the result has a single digit..php @@ -0,0 +1,16 @@ + 0) + { + return ($num - 1) % 9 + 1; + } + else + { + return 0; + } +} + +print_r(add_digits(48)."\n"); +print_r(add_digits(59)."\n"); +?> \ No newline at end of file diff --git a/php/Basics/PHP program to check a sequence of numbers is a geometric progression or not..php b/php/Basics/PHP program to check a sequence of numbers is a geometric progression or not..php new file mode 100644 index 0000000..63cf4ed --- /dev/null +++ b/php/Basics/PHP program to check a sequence of numbers is a geometric progression or not..php @@ -0,0 +1,28 @@ + + +Output: +Geometric sequence +Not an geometric sequence \ No newline at end of file diff --git a/php/Basics/PHP program to check a sequence of numbers is an arithmetic progression or not..php b/php/Basics/PHP program to check a sequence of numbers is an arithmetic progression or not..php new file mode 100644 index 0000000..2c03c26 --- /dev/null +++ b/php/Basics/PHP program to check a sequence of numbers is an arithmetic progression or not..php @@ -0,0 +1,20 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to check if a given positive integer is a power of four..php b/php/Basics/PHP program to check if a given positive integer is a power of four..php new file mode 100644 index 0000000..d329366 --- /dev/null +++ b/php/Basics/PHP program to check if a given positive integer is a power of four..php @@ -0,0 +1,22 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to check if a given positive integer is a power of three..php b/php/Basics/PHP program to check if a given positive integer is a power of three..php new file mode 100644 index 0000000..eb05867 --- /dev/null +++ b/php/Basics/PHP program to check if a given positive integer is a power of three..php @@ -0,0 +1,22 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to check if a given positive integer is a power of two..php b/php/Basics/PHP program to check if a given positive integer is a power of two..php new file mode 100644 index 0000000..6502375 --- /dev/null +++ b/php/Basics/PHP program to check if a given positive integer is a power of two..php @@ -0,0 +1,16 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to check if a given string is an anagram of another given string..php b/php/Basics/PHP program to check if a given string is an anagram of another given string..php new file mode 100644 index 0000000..3ee13ef --- /dev/null +++ b/php/Basics/PHP program to check if a given string is an anagram of another given string..php @@ -0,0 +1,15 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to check if an integer is the power of another integer..php b/php/Basics/PHP program to check if an integer is the power of another integer..php new file mode 100644 index 0000000..f9cd662 --- /dev/null +++ b/php/Basics/PHP program to check if an integer is the power of another integer..php @@ -0,0 +1,23 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to check whether a given number is an ugly number..php b/php/Basics/PHP program to check whether a given number is an ugly number..php new file mode 100644 index 0000000..139a5a4 --- /dev/null +++ b/php/Basics/PHP program to check whether a given number is an ugly number..php @@ -0,0 +1,31 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to compute and return the square root of a given number..php b/php/Basics/PHP program to compute and return the square root of a given number..php new file mode 100644 index 0000000..cba7e46 --- /dev/null +++ b/php/Basics/PHP program to compute and return the square root of a given number..php @@ -0,0 +1,15 @@ + $y) + { + $x = ($x + $y)/2; + $y = $n/$x; + } + return $x; +} +print_r(my_sqrt(16)."\n"); +print_r(my_sqrt(14)."\n"); +?> \ No newline at end of file diff --git a/php/Basics/PHP program to compute the sum of the two reversed numbers and display the sum in reversed form..php b/php/Basics/PHP program to compute the sum of the two reversed numbers and display the sum in reversed form..php new file mode 100644 index 0000000..c2a8fda --- /dev/null +++ b/php/Basics/PHP program to compute the sum of the two reversed numbers and display the sum in reversed form..php @@ -0,0 +1,21 @@ + 0) + { + $reverse = $reverse * 10; + $reverse = $reverse + $n % 10; + $n = (int)($n/10); + } + return $reverse; +} +print_r(reverse_sum(13, 14)."\n"); +print_r(reverse_sum(130, 1)."\n"); +print_r(reverse_sum(305, 794)."\n"); +?> \ No newline at end of file diff --git a/php/Basics/PHP program to find HCF of two numbers.php b/php/Basics/PHP program to find HCF of two numbers.php new file mode 100644 index 0000000..842712f --- /dev/null +++ b/php/Basics/PHP program to find HCF of two numbers.php @@ -0,0 +1,37 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to find a missing number(s) from an array.php b/php/Basics/PHP program to find a missing number(s) from an array.php new file mode 100644 index 0000000..3f5a69f --- /dev/null +++ b/php/Basics/PHP program to find a missing number(s) from an array.php @@ -0,0 +1,14 @@ +function missing_number($num_list) +{ + +// construct a new array +$new_arr = range($num_list[0],max($num_list)); + +// use array_diff to find the missing elements +return array_diff($new_arr, $num_list); + +} + +print_r(missing_number(array(1,2,3,6,7,8))); +print_r(missing_number(array(10,11,12,14,15,16,17))); +?> \ No newline at end of file diff --git a/php/Basics/PHP program to find a single element in an array where every element appears three times except for one..php b/php/Basics/PHP program to find a single element in an array where every element appears three times except for one..php new file mode 100644 index 0000000..d4a7e0b --- /dev/null +++ b/php/Basics/PHP program to find a single element in an array where every element appears three times except for one..php @@ -0,0 +1,24 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to find a single number in an array that doesn't occur twice..php b/php/Basics/PHP program to find a single number in an array that doesn't occur twice..php new file mode 100644 index 0000000..de4753e --- /dev/null +++ b/php/Basics/PHP program to find a single number in an array that doesn't occur twice..php @@ -0,0 +1,20 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to find factor of any number.php b/php/Basics/PHP program to find factor of any number.php new file mode 100644 index 0000000..ec01f1a --- /dev/null +++ b/php/Basics/PHP program to find factor of any number.php @@ -0,0 +1,17 @@ +// Write a program to find factor of any number + + \ No newline at end of file diff --git a/php/Basics/PHP program to find majority element in an array..php b/php/Basics/PHP program to find majority element in an array..php new file mode 100644 index 0000000..555baee --- /dev/null +++ b/php/Basics/PHP program to find majority element in an array..php @@ -0,0 +1,29 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to find table of a number.php b/php/Basics/PHP program to find table of a number.php new file mode 100644 index 0000000..d900937 --- /dev/null +++ b/php/Basics/PHP program to find table of a number.php @@ -0,0 +1,16 @@ +//Write a program to find table of a number + +

Table of " .$num."
"; + for($i=1;$i<=10;$i++) + { + echo $num*$i; + echo "
"; + } + + } + + ?> \ No newline at end of file diff --git a/php/Basics/PHP program to find the length of the last word in a string..php b/php/Basics/PHP program to find the length of the last word in a string..php new file mode 100644 index 0000000..6b327d3 --- /dev/null +++ b/php/Basics/PHP program to find the length of the last word in a string..php @@ -0,0 +1,23 @@ +1) + return strlen(substr($s, strrpos($s, ' ') + 1)); + else + return "Single word"; + + +} +print_r(length_of_last_word("PHP Exercises")."\n"); +print_r(length_of_last_word("PHP")."\n"); +print_r(length_of_last_word("")."\n"); +print_r(length_of_last_word(" ")."\n"); +?> \ No newline at end of file diff --git a/php/Basics/PHP program to find the single element appears once in an array where every element appears twice except for one.php b/php/Basics/PHP program to find the single element appears once in an array where every element appears twice except for one.php new file mode 100644 index 0000000..b8f6d74 --- /dev/null +++ b/php/Basics/PHP program to find the single element appears once in an array where every element appears twice except for one.php @@ -0,0 +1,15 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to find the single number which occurs odd numbers and other numbers occur even number..php b/php/Basics/PHP program to find the single number which occurs odd numbers and other numbers occur even number..php new file mode 100644 index 0000000..844fb54 --- /dev/null +++ b/php/Basics/PHP program to find the single number which occurs odd numbers and other numbers occur even number..php @@ -0,0 +1,19 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to find three numbers from an array such that the sum of three consecutive numbers equal to a given number..php b/php/Basics/PHP program to find three numbers from an array such that the sum of three consecutive numbers equal to a given number..php new file mode 100644 index 0000000..bece5b6 --- /dev/null +++ b/php/Basics/PHP program to find three numbers from an array such that the sum of three consecutive numbers equal to a given number..php @@ -0,0 +1,17 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to find three numbers from an array such that the sum of three consecutive numbers equal to zero.php b/php/Basics/PHP program to find three numbers from an array such that the sum of three consecutive numbers equal to zero.php new file mode 100644 index 0000000..52daa43 --- /dev/null +++ b/php/Basics/PHP program to find three numbers from an array such that the sum of three consecutive numbers equal to zero.php @@ -0,0 +1,20 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to find whether a number is Armstrong or not.php b/php/Basics/PHP program to find whether a number is Armstrong or not.php new file mode 100644 index 0000000..e01668e --- /dev/null +++ b/php/Basics/PHP program to find whether a number is Armstrong or not.php @@ -0,0 +1,26 @@ +// If the sum of cubes of individual digits of a number is equal to the number itslef then it is called Armstrong Number. + \ No newline at end of file diff --git a/php/Basics/PHP program to get the Hamming numbers upto a given numbers also check whether a given number is a Hamming number..php b/php/Basics/PHP program to get the Hamming numbers upto a given numbers also check whether a given number is a Hamming number..php new file mode 100644 index 0000000..b0a0fc6 --- /dev/null +++ b/php/Basics/PHP program to get the Hamming numbers upto a given numbers also check whether a given number is a Hamming number..php @@ -0,0 +1,41 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to print Reverse of any number.php b/php/Basics/PHP program to print Reverse of any number.php new file mode 100644 index 0000000..46f799f --- /dev/null +++ b/php/Basics/PHP program to print Reverse of any number.php @@ -0,0 +1,14 @@ +=1) + { + $re=$num%10; + $rev=$rev*10+$re; + $num=$num/10; + } +} +?> \ No newline at end of file diff --git a/php/Basics/PHP program to push all zeros to the end of an array..php b/php/Basics/PHP program to push all zeros to the end of an array..php new file mode 100644 index 0000000..2c79107 --- /dev/null +++ b/php/Basics/PHP program to push all zeros to the end of an array..php @@ -0,0 +1,28 @@ + \ No newline at end of file diff --git a/php/Basics/PHP program to reverse the bits of an integer (32 bits unsigned)..php b/php/Basics/PHP program to reverse the bits of an integer (32 bits unsigned)..php new file mode 100644 index 0000000..6caa6c7 --- /dev/null +++ b/php/Basics/PHP program to reverse the bits of an integer (32 bits unsigned)..php @@ -0,0 +1,15 @@ +>= 1; + } + return $result; + +} +print_r(reverse_integer(1234)."\n"); +?> \ No newline at end of file diff --git a/php/Basics/PHP program to reverse the digits of an integer..php b/php/Basics/PHP program to reverse the digits of an integer..php new file mode 100644 index 0000000..0754ff9 --- /dev/null +++ b/php/Basics/PHP program to reverse the digits of an integer..php @@ -0,0 +1,15 @@ + 0) + { + $reverse = $reverse * 10; + $reverse = $reverse + $n % 10; + $n = (int)($n/10); + } + return $reverse; +} +print_r(reverse_integer(1234)."\n"); +print_r(reverse_integer(23)."\n"); +?> \ No newline at end of file diff --git a/php/Basics/PHP program where you take any positive integer n, if n is even, divide it by 2 to get n (by) 2..php b/php/Basics/PHP program where you take any positive integer n, if n is even, divide it by 2 to get n (by) 2..php new file mode 100644 index 0000000..cf2aa70 --- /dev/null +++ b/php/Basics/PHP program where you take any positive integer n, if n is even, divide it by 2 to get n (by) 2..php @@ -0,0 +1,26 @@ + 1) + { + if ($x % 2 == 0) + { + $x = $x / 2; + } + else + { + $x = 3 * $x + 1; + } + # Added line + array_push($num_seq, $x); + } + return $num_seq; +} +print_r(collatz_sequence(12)); +print_r(collatz_sequence(19)); +?> \ No newline at end of file diff --git a/php/Basics/Palindrome number Program in PHP.php b/php/Basics/Palindrome number Program in PHP.php new file mode 100644 index 0000000..6862f27 --- /dev/null +++ b/php/Basics/Palindrome number Program in PHP.php @@ -0,0 +1,24 @@ + +/* +Output + +121 is palindrome number \ No newline at end of file diff --git a/php/Basics/Pattern Problems in PHP.php b/php/Basics/Pattern Problems in PHP.php new file mode 100644 index 0000000..78fb9fe --- /dev/null +++ b/php/Basics/Pattern Problems in PHP.php @@ -0,0 +1,406 @@ +/* Pattern problems in PHP */ +/* 1 */ + +"; +} + +?> +/* +Output + +* +* +* +* +* +*/ +/* Print Triangle of Stars in PHP */ + +"; +} + +?> + +/* +Output + +* * * * * +* * * * * +* * * * * +* * * * * +* * * * * +*/ + +/*Print Star Pattern in PHP */ + +"; +} + +?> + +/* + +Output + +* +* * +* * * +* * * * +* * * * * +* * * * * * +* * * * * * * +*/ +/* Print Star Pattern in PHP */ +=1;$j--) +{ +echo "* "; +} +echo "
"; +} + +?> + +/* +Output + +* * * * * * * +* * * * * * +* * * * * +* * * * +* * * +* * +* +*/ + +/* Print Triangle of Stars in PHP */ + +=1; $a--) +{ +if($a%2 != 0) +{ +for($b=5; $b>=$a; $b--) +{ +echo "* "; +} +echo "
"; +} +} +for($a=2; $a<=5; $a++) +{ + if($a%2 != 0) +{ + for($b=5; $b>=$a; $b--) +{ +echo "* "; +} +echo "
"; +} +} + +?> + +/* +Output + +* +* * * +* * * * * +* * * +* +*/ +/* +Print Star Pattern in PHP*/ + + 3 ? 6 - $row : $row); $col++) + { + echo '* '; + } + + echo "
"; +} + +?> +/* +Output + +* +* * +* * * +* * +* +*/ + +/* Print Triangle of Stars in PHP*/ + +=$i;$k--) +{ +echo " "; +} +for($j=1;$j<=$i;$j++) +{ +echo "* "; +} +echo "
"; +} +for($i=5;$i>=1;$i--) +{ +for($k=6;$k>=$i;$k--) +{ +echo " "; +} +for($j=1;$j<=$i;$j++) +{ +echo "* "; +} +echo "
"; +} + +?> +/* +Output + +* +* * +* * * +* * * * +* * * * * +* * * * * * +* * * * * * * +* * * * * * +* * * * * +* * * * +* * * +* * +* +*/ + +* * * * * * * * * * * * * * * +* * * * * * * * * * * * * +* * * * * * * * * * * +* * * * * * * * * +* * * * * * * +* * * * * +* * * +* + +=1;--$i) + { + for($space=0;$space<$rows-$i;++$space) + echo " "; + for($j=$i;$j<=2*$i-1;++$j) + echo "* "; + for($j=0;$j<$i-1;++$j) + echo "* "; + echo "
"; + } + } + ?> + +Program to print below format. +1 2 3 4 5 6 7 8 +1 2 3 4 5 6 7 +1 2 3 4 5 6 +1 2 3 4 5 +1 2 3 4 +1 2 3 +1 2 +1 +Hide Answer +=1;--$i) + { + for($j=1;$j<=$i;++$j) + { + echo $j; + } + echo "
"; + } + } + ?> + + Program to print below format +* +* * +* * * +* * * * +* * * * * +* * * * * * +* * * * * * * +* * * * * * * * +* * * * * * * * * +Hide Answer +"; + } + } + ?> + + /* Write a program to print below format +1 +1 2 +1 2 3 +1 2 3 4 +1 2 3 4 5 +1 2 3 4 5 6 +1 2 3 4 5 6 7 +1 2 3 4 5 6 7 8 +*/ +"; + } + } + +/* + Write a program to print the below format : +1 5 9 +2 6 10 +3 7 11 +4 8 12 +*/ +"; +} + + +?> + + +Write a program for this Pattern: +***** +* * +* * +* * +***** +Hide Answer +"; + } +?> + + + +How to write a Floyd's Triangle? +1 +23 +456 +78910 +1112131415 +Hide Answer + '; +} +?> + +Write a program to make a chess: + +Hide Answer + + + "; + for($col=1;$col<=8;$col++) + { + $total=$row+$col; + if($total%2==0) + { + echo ""; + } + else + { + echo ""; + } + } + echo ""; + } + ?> +
+ diff --git a/php/Basics/Print Table of aby number Program in PHP.php b/php/Basics/Print Table of aby number Program in PHP.php new file mode 100644 index 0000000..e3fa982 --- /dev/null +++ b/php/Basics/Print Table of aby number Program in PHP.php @@ -0,0 +1,23 @@ +'; +} + +?> + +/* +3 +6 +9 +12 +15 +18 +21 +24 +27 +30 \ No newline at end of file diff --git a/php/Basics/Print an array in PHP.php b/php/Basics/Print an array in PHP.php new file mode 100644 index 0000000..3c11200 --- /dev/null +++ b/php/Basics/Print an array in PHP.php @@ -0,0 +1,16 @@ +".$v; + } + +?> \ No newline at end of file diff --git a/php/Basics/Print an array using foreach in php.php b/php/Basics/Print an array using foreach in php.php new file mode 100644 index 0000000..ed9b8dd --- /dev/null +++ b/php/Basics/Print an array using foreach in php.php @@ -0,0 +1,11 @@ +"; + } + +?> \ No newline at end of file diff --git a/php/Basics/Program to combine the array elements into a string with given delimiter..php b/php/Basics/Program to combine the array elements into a string with given delimiter..php new file mode 100644 index 0000000..593a91d --- /dev/null +++ b/php/Basics/Program to combine the array elements into a string with given delimiter..php @@ -0,0 +1,7 @@ + \ No newline at end of file diff --git a/php/Basics/Program to create a Simple Calculator..php b/php/Basics/Program to create a Simple Calculator..php new file mode 100644 index 0000000..678a320 --- /dev/null +++ b/php/Basics/Program to create a Simple Calculator..php @@ -0,0 +1,33 @@ + + +
+Calculator +
+No1: +
+No2: +
+Res: +
+ + + + +
\ No newline at end of file diff --git a/php/Basics/Program to create simple Login and Logout example using sessions.php b/php/Basics/Program to create simple Login and Logout example using sessions.php new file mode 100644 index 0000000..329257c --- /dev/null +++ b/php/Basics/Program to create simple Login and Logout example using sessions.php @@ -0,0 +1,56 @@ +login.php + + + +Login Form + + +

Login Form

+
+User Id:
+Password:
+ +
+ + + +checklogin.php + + + +securepage.php + +"; + echo "Logout"; + } + else + { + header("location:login.php"); + } +?> + +logout.php + + \ No newline at end of file diff --git a/php/Basics/Program to find number of elements in an array..php b/php/Basics/Program to find number of elements in an array..php new file mode 100644 index 0000000..97397d2 --- /dev/null +++ b/php/Basics/Program to find number of elements in an array..php @@ -0,0 +1,7 @@ + \ No newline at end of file diff --git a/php/Basics/Program to find prime numbers in between a Range.php b/php/Basics/Program to find prime numbers in between a Range.php new file mode 100644 index 0000000..532974f --- /dev/null +++ b/php/Basics/Program to find prime numbers in between a Range.php @@ -0,0 +1,33 @@ +/* +Output + +Prime Number : 2 +Prime Number : 3 +Prime Number : 5 +Prime Number : 7 +Prime Number : 11 +Prime Number : 13 +Prime Number : 17 +Prime Number : 19 +Prime Number : 23 \ No newline at end of file diff --git a/php/Basics/Program to find the product of elements in an array..php b/php/Basics/Program to find the product of elements in an array..php new file mode 100644 index 0000000..d79f61c --- /dev/null +++ b/php/Basics/Program to find the product of elements in an array..php @@ -0,0 +1,6 @@ + \ No newline at end of file diff --git a/php/Basics/Program to find the sum of elements in an array..php b/php/Basics/Program to find the sum of elements in an array..php new file mode 100644 index 0000000..f9d36c2 --- /dev/null +++ b/php/Basics/Program to find the sum of elements in an array..php @@ -0,0 +1,6 @@ + \ No newline at end of file diff --git a/php/Basics/Program to join the array elements into a string..php b/php/Basics/Program to join the array elements into a string..php new file mode 100644 index 0000000..dead124 --- /dev/null +++ b/php/Basics/Program to join the array elements into a string..php @@ -0,0 +1,7 @@ + \ No newline at end of file diff --git a/php/Basics/Program to merge two arrays into a new array..php b/php/Basics/Program to merge two arrays into a new array..php new file mode 100644 index 0000000..7e71e02 --- /dev/null +++ b/php/Basics/Program to merge two arrays into a new array..php @@ -0,0 +1,9 @@ + \ No newline at end of file diff --git a/php/Basics/Program to remove the duplicate values from an array..php b/php/Basics/Program to remove the duplicate values from an array..php new file mode 100644 index 0000000..02a9923 --- /dev/null +++ b/php/Basics/Program to remove the duplicate values from an array..php @@ -0,0 +1,6 @@ + \ No newline at end of file diff --git a/php/Basics/Program to sort elements in an array in ascending order..php b/php/Basics/Program to sort elements in an array in ascending order..php new file mode 100644 index 0000000..0ab59a2 --- /dev/null +++ b/php/Basics/Program to sort elements in an array in ascending order..php @@ -0,0 +1,7 @@ + \ No newline at end of file diff --git a/php/Basics/Program to sort elements in an array in descending order..php b/php/Basics/Program to sort elements in an array in descending order..php new file mode 100644 index 0000000..faf863c --- /dev/null +++ b/php/Basics/Program to sort elements in an array in descending order..php @@ -0,0 +1,7 @@ + \ No newline at end of file diff --git a/php/Basics/Program to split a string into an array elements based on delimiter..php b/php/Basics/Program to split a string into an array elements based on delimiter..php new file mode 100644 index 0000000..3443655 --- /dev/null +++ b/php/Basics/Program to split a string into an array elements based on delimiter..php @@ -0,0 +1,7 @@ + \ No newline at end of file diff --git a/php/Basics/Reverse String Program in PHP.php b/php/Basics/Reverse String Program in PHP.php new file mode 100644 index 0000000..a7bfc79 --- /dev/null +++ b/php/Basics/Reverse String Program in PHP.php @@ -0,0 +1,25 @@ +=$a;$i--) + +{ + +$c[]=$a[$i]; + + + + } + + echo implode($c,); + + + +?> \ No newline at end of file diff --git a/php/Basics/Swap two number using third variable program in PHP.php b/php/Basics/Swap two number using third variable program in PHP.php new file mode 100644 index 0000000..300477d --- /dev/null +++ b/php/Basics/Swap two number using third variable program in PHP.php @@ -0,0 +1,23 @@ +"; +echo "Value of b: $b
"; + +$temp=$a; +$a=$b; +$b=$temp; + +echo "Value of a: $a
"; +echo "Value of b: $b
"; + +?> + +/* +Output +Value of a: 10 +Value of b: 20 +Value of a: 20 +Value of b: 10 \ No newline at end of file diff --git a/php/Basics/Swap two number without using third variable program in PHP.php b/php/Basics/Swap two number without using third variable program in PHP.php new file mode 100644 index 0000000..0769a89 --- /dev/null +++ b/php/Basics/Swap two number without using third variable program in PHP.php @@ -0,0 +1,24 @@ +"; +echo "Value of b: $b
"; + +$a=$a+$b; +$b=$a-$b; +$a=$a-$b; + +echo "Value of a: $a
"; +echo "Value of b: $b
"; + +?> +/* + +Output + +Value of a: 10 +Value of b: 20 +Value of a: 20 +Value of b: 10 \ No newline at end of file diff --git a/php/README.md b/php/README.md new file mode 100644 index 0000000..2e07f32 --- /dev/null +++ b/php/README.md @@ -0,0 +1,3 @@ +# Hypertext Preprocessor (PHP) + +PHP is a general-purpose programming language originally designed for web development. \ No newline at end of file diff --git a/python/Basics/Accept the base and height of a triangle and compute the area.py b/python/Basics/Accept the base and height of a triangle and compute the area.py new file mode 100644 index 0000000..90ba5ac --- /dev/null +++ b/python/Basics/Accept the base and height of a triangle and compute the area.py @@ -0,0 +1,6 @@ +b = int(input("Input the base : ")) +h = int(input("Input the height : ")) + +area = b*h/2 + +print("area = ", area) \ No newline at end of file diff --git a/python/Basics/Access and print a URL's content to the console.py b/python/Basics/Access and print a URL's content to the console.py new file mode 100644 index 0000000..8c583ee --- /dev/null +++ b/python/Basics/Access and print a URL's content to the console.py @@ -0,0 +1,7 @@ +from http.client import HTTPConnection +conn = HTTPConnection("example.com") +conn.request("GET", "/") +result = conn.getresponse() +# retrieves the entire contents. +contents = result.read() +print(contents) \ No newline at end of file diff --git a/python/Basics/Access environment variables.py b/python/Basics/Access environment variables.py new file mode 100644 index 0000000..e375b2d --- /dev/null +++ b/python/Basics/Access environment variables.py @@ -0,0 +1,10 @@ +import os +# Access all environment variables +print('*----------------------------------*') +print(os.environ) +print('*----------------------------------*') +# Access a particular environment variable +print(os.environ['HOME']) +print('*----------------------------------*') +print(os.environ['PATH']) +print('*----------------------------------*') \ No newline at end of file diff --git a/python/Basics/Calculate midpoints of a line.py b/python/Basics/Calculate midpoints of a line.py new file mode 100644 index 0000000..479d551 --- /dev/null +++ b/python/Basics/Calculate midpoints of a line.py @@ -0,0 +1,15 @@ +print('\nCalculate the midpoint of a line :') + +x1 = float(input('The value of x (the first endpoint) ')) +y1 = float(input('The value of y (the first endpoint) ')) + +x2 = float(input('The value of x (the first endpoint) ')) +y2 = float(input('The value of y (the first endpoint) ')) + +x_m_point = (x1 + x2)/2 +y_m_point = (y1 + y2)/2 +print(); +print("The midpoint of line is :") +print( "The midpoint's x value is: ",x_m_point) +print( "The midpoint's y value is: ",y_m_point) +print(); \ No newline at end of file diff --git a/python/Basics/Calculate number of days between two dates.py b/python/Basics/Calculate number of days between two dates.py new file mode 100644 index 0000000..2fe74d3 --- /dev/null +++ b/python/Basics/Calculate number of days between two dates.py @@ -0,0 +1,6 @@ +from datetime import date + +f_date = date(2014, 7, 2) +l_date = date(2014, 7, 11) +delta = l_date - f_date +print(delta.days) \ No newline at end of file diff --git a/python/Basics/Calculate the hypotenuse of a right angled triangle.py b/python/Basics/Calculate the hypotenuse of a right angled triangle.py new file mode 100644 index 0000000..082da02 --- /dev/null +++ b/python/Basics/Calculate the hypotenuse of a right angled triangle.py @@ -0,0 +1,7 @@ +from math import sqrt +print("Input lengths of shorter triangle sides:") +a = float(input("a: ")) +b = float(input("b: ")) + +c = sqrt(a**2 + b**2) +print("The length of the hypotenuse is", c ) \ No newline at end of file diff --git a/python/Basics/Calculate the sum of the digits in an integer.py b/python/Basics/Calculate the sum of the digits in an integer.py new file mode 100644 index 0000000..fc43b2f --- /dev/null +++ b/python/Basics/Calculate the sum of the digits in an integer.py @@ -0,0 +1,6 @@ +num = int(input("Input a four digit numbers: ")) +x = num //1000 +x1 = (num - x*1000)//100 +x2 = (num - x*1000 - x1*100)//10 +x3 = num - x*1000 - x1*100 - x2*10 +print("The sum of digits in the number is", x+x1+x2+x3) \ No newline at end of file diff --git a/python/Basics/Calculate the sum of three given numbers, if the values are equal then return thrice of their sum.py b/python/Basics/Calculate the sum of three given numbers, if the values are equal then return thrice of their sum.py new file mode 100644 index 0000000..77b1baf --- /dev/null +++ b/python/Basics/Calculate the sum of three given numbers, if the values are equal then return thrice of their sum.py @@ -0,0 +1,10 @@ +def sum_thrice(x, y, z): + + sum = x + y + z + + if x == y == z: + sum = sum * 3 + return sum + +print(sum_thrice(1, 2, 3)) +print(sum_thrice(3, 3, 3)) \ No newline at end of file diff --git a/python/Basics/Check whether Python shell is executing in 32bit or 64bit mode on OS.py b/python/Basics/Check whether Python shell is executing in 32bit or 64bit mode on OS.py new file mode 100644 index 0000000..c6d4142 --- /dev/null +++ b/python/Basics/Check whether Python shell is executing in 32bit or 64bit mode on OS.py @@ -0,0 +1,3 @@ +# For 32 bit it will return 32 and for 64 bit it will return 64 +import struct +print(struct.calcsize("P") * 8) \ No newline at end of file diff --git a/python/Basics/Compute the distance between two points.py b/python/Basics/Compute the distance between two points.py new file mode 100644 index 0000000..e4fad5f --- /dev/null +++ b/python/Basics/Compute the distance between two points.py @@ -0,0 +1,7 @@ +import math + +p1 = [4, 0] +p2 = [6, 6] +distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) ) + +print(distance) \ No newline at end of file diff --git a/python/Basics/Concatenate all elements in a list into a string.py b/python/Basics/Concatenate all elements in a list into a string.py new file mode 100644 index 0000000..68d36c9 --- /dev/null +++ b/python/Basics/Concatenate all elements in a list into a string.py @@ -0,0 +1,7 @@ +def concatenate_list_data(list): + result= '' + for element in list: + result += str(element) + return result + +print(concatenate_list_data([1, 5, 12, 2])) \ No newline at end of file diff --git a/python/Basics/Convert all units of time into seconds.py b/python/Basics/Convert all units of time into seconds.py new file mode 100644 index 0000000..ee4cd99 --- /dev/null +++ b/python/Basics/Convert all units of time into seconds.py @@ -0,0 +1,8 @@ +days = int(input("Input days: ")) * 3600 * 24 +hours = int(input("Input hours: ")) * 3600 +minutes = int(input("Input minutes: ")) * 60 +seconds = int(input("Input seconds: ")) + +time = days + hours + minutes + seconds + +print("The amounts of seconds", time) \ No newline at end of file diff --git a/python/Basics/Convert height (in feet and inches) to centimeters.py b/python/Basics/Convert height (in feet and inches) to centimeters.py new file mode 100644 index 0000000..0e2ac23 --- /dev/null +++ b/python/Basics/Convert height (in feet and inches) to centimeters.py @@ -0,0 +1,8 @@ +print("Input your height: ") +h_ft = int(input("Feet: ")) +h_inch = int(input("Inches: ")) + +h_inch += h_ft * 12 +h_cm = round(h_inch * 2.54, 1) + +print("Your height is : %d cm." % h_cm) \ No newline at end of file diff --git a/python/Basics/Convert pressure in kilopascals to pounds.py b/python/Basics/Convert pressure in kilopascals to pounds.py new file mode 100644 index 0000000..d0e9b2c --- /dev/null +++ b/python/Basics/Convert pressure in kilopascals to pounds.py @@ -0,0 +1,7 @@ +kpa = float(input("Input pressure in in kilopascals> ")) +psi = kpa / 6.89475729 +mmhg = kpa * 760 / 101.325 +atm = kpa / 101.325 +print("The pressure in pounds per square inch: %.2f psi" % (psi)) +print("The pressure in millimeter of mercury: %.2f mmHg" % (mmhg)) +print("Atmosphere pressure: %.2f atm." % (atm)) \ No newline at end of file diff --git a/python/Basics/Convert the distance in feet to inches, yards, and miles.py b/python/Basics/Convert the distance in feet to inches, yards, and miles.py new file mode 100644 index 0000000..4f59a40 --- /dev/null +++ b/python/Basics/Convert the distance in feet to inches, yards, and miles.py @@ -0,0 +1,8 @@ +d_ft = int(input("Input distance in feet: ")) +d_inches = d_ft * 12 +d_yards = d_ft / 3.0 +d_miles = d_ft / 5280.0 + +print("The distance in inches is %i inches." % d_inches) +print("The distance in yards is %.2f yards." % d_yards) +print("The distance in miles is %.2f miles." % d_miles) \ No newline at end of file diff --git a/python/Basics/Create a histogram from a given list of integers.py b/python/Basics/Create a histogram from a given list of integers.py new file mode 100644 index 0000000..b3b4ded --- /dev/null +++ b/python/Basics/Create a histogram from a given list of integers.py @@ -0,0 +1,10 @@ +def histogram( items ): + for n in items: + output = '' + times = n + while( times > 0 ): + output += '*' + times = times - 1 + print(output) + +histogram([2, 3, 6, 5]) \ No newline at end of file diff --git a/python/Basics/Determine profiling of Python programs.py b/python/Basics/Determine profiling of Python programs.py new file mode 100644 index 0000000..e04e202 --- /dev/null +++ b/python/Basics/Determine profiling of Python programs.py @@ -0,0 +1,4 @@ +import cProfile +def sum(): + print(1+2) +cProfile.run('sum()') \ No newline at end of file diff --git a/python/Basics/Find out the number of CPUs using.py b/python/Basics/Find out the number of CPUs using.py new file mode 100644 index 0000000..51a01df --- /dev/null +++ b/python/Basics/Find out the number of CPUs using.py @@ -0,0 +1,2 @@ +import multiprocessing +print(multiprocessing.cpu_count()) \ No newline at end of file diff --git a/python/Basics/Generate a list and tuple with comma-separated numbers.py b/python/Basics/Generate a list and tuple with comma-separated numbers.py new file mode 100644 index 0000000..77f0d1c --- /dev/null +++ b/python/Basics/Generate a list and tuple with comma-separated numbers.py @@ -0,0 +1,5 @@ +values = input("Input some comma seprated numbers : ") +list = values.split(",") +tuple = tuple(list) +print('List : ',list) +print('Tuple : ',tuple) \ No newline at end of file diff --git a/python/Basics/Get OS name, platform and release information.py b/python/Basics/Get OS name, platform and release information.py new file mode 100644 index 0000000..62f2bc8 --- /dev/null +++ b/python/Basics/Get OS name, platform and release information.py @@ -0,0 +1,5 @@ +import platform +import os +print(os.name) +print(platform.system()) +print(platform.release()) \ No newline at end of file diff --git a/python/Basics/Get a string which is n (non-negative integer) copies of a given string.py b/python/Basics/Get a string which is n (non-negative integer) copies of a given string.py new file mode 100644 index 0000000..d3f7bb3 --- /dev/null +++ b/python/Basics/Get a string which is n (non-negative integer) copies of a given string.py @@ -0,0 +1,8 @@ +def larger_string(str, n): + result = "" + for i in range(n): + result = result + str + return result + +print(larger_string('abc', 2)) +print(larger_string('.py', 3)) \ No newline at end of file diff --git a/python/Basics/Get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference.py b/python/Basics/Get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference.py new file mode 100644 index 0000000..83f6ee3 --- /dev/null +++ b/python/Basics/Get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference.py @@ -0,0 +1,8 @@ +def difference(n): + if n <= 17: + return 17 - n + else: + return (n - 17) * 2 + +print(difference(22)) +print(difference(14)) \ No newline at end of file diff --git a/python/Basics/Get the path and name of the file that is currently executing.py b/python/Basics/Get the path and name of the file that is currently executing.py new file mode 100644 index 0000000..0716553 --- /dev/null +++ b/python/Basics/Get the path and name of the file that is currently executing.py @@ -0,0 +1,2 @@ +import os +print("Current File Name : ",os.path.realpath(__file__)) \ No newline at end of file diff --git a/python/Basics/Input a filename and print the extension of that.py b/python/Basics/Input a filename and print the extension of that.py new file mode 100644 index 0000000..dff0367 --- /dev/null +++ b/python/Basics/Input a filename and print the extension of that.py @@ -0,0 +1,3 @@ +filename = input("Input the Filename: ") +f_extns = filename.split(".") +print ("The extension of the file is : " + repr(f_extns[-1])) \ No newline at end of file diff --git a/python/Basics/Input an integer (n) and computes the value of n+nn+nnn.py b/python/Basics/Input an integer (n) and computes the value of n+nn+nnn.py new file mode 100644 index 0000000..5a51e2d --- /dev/null +++ b/python/Basics/Input an integer (n) and computes the value of n+nn+nnn.py @@ -0,0 +1,5 @@ +a = int(input("Input an integer : ")) +n1 = int( "%s" % a ) +n2 = int( "%s%s" % (a,a) ) +n3 = int( "%s%s%s" % (a,a,a) ) +print (n1+n2+n3) \ No newline at end of file diff --git a/python/Basics/Input the radius of a circle and compute the area.py b/python/Basics/Input the radius of a circle and compute the area.py new file mode 100644 index 0000000..9e721d9 --- /dev/null +++ b/python/Basics/Input the radius of a circle and compute the area.py @@ -0,0 +1,3 @@ +from math import pi +r = float(input ("Input the radius of the circle : ")) +print ("The area of the circle with radius " + str(r) + " is: " + str(pi * r**2)) \ No newline at end of file diff --git a/python/Basics/List all files in a directory in Python.py b/python/Basics/List all files in a directory in Python.py new file mode 100644 index 0000000..98ea65b --- /dev/null +++ b/python/Basics/List all files in a directory in Python.py @@ -0,0 +1,4 @@ +from os import listdir +from os.path import isfile, join +files_list = [f for f in listdir('/home/students') if isfile(join('/home/students', f))] +print(files_list); \ No newline at end of file diff --git a/python/Basics/Measure execution time.py b/python/Basics/Measure execution time.py new file mode 100644 index 0000000..15d8192 --- /dev/null +++ b/python/Basics/Measure execution time.py @@ -0,0 +1,11 @@ +import time +def sum_of_n_numbers(n): + start_time = time.time() + s = 0 + for i in range(1,n+1): + s = s + i + end_time = time.time() + return s,end_time-start_time + +n = 5 +print("\nTime to sum of 1 to ",n," and required time to calculate is :",sum_of_n_numbers(n)) \ No newline at end of file diff --git a/python/Basics/Print first and last name in reverse order with a space between them.py b/python/Basics/Print first and last name in reverse order with a space between them.py new file mode 100644 index 0000000..1deaca5 --- /dev/null +++ b/python/Basics/Print first and last name in reverse order with a space between them.py @@ -0,0 +1,3 @@ +fname = input("Input your First Name : ") +lname = input("Input your Last Name : ") +print ("Hello " + lname + " " + fname) \ No newline at end of file diff --git a/python/Basics/Program to add two numbers.py b/python/Basics/Program to add two numbers.py new file mode 100644 index 0000000..90236ef --- /dev/null +++ b/python/Basics/Program to add two numbers.py @@ -0,0 +1,10 @@ +# This program adds two numbers + +num1 = 1.5 +num2 = 6.3 + +# Add two numbers +sum = float(num1) + float(num2) + +# Display the sum +print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) \ No newline at end of file diff --git a/python/Basics/Program to calculate the square root.py b/python/Basics/Program to calculate the square root.py new file mode 100644 index 0000000..32796f5 --- /dev/null +++ b/python/Basics/Program to calculate the square root.py @@ -0,0 +1,9 @@ +# Python Program to calculate the square root + +# Note: change this value for a different result +num = 8 + +# uncomment to take the input from the user +#num = float(input('Enter a number: ')) +num_sqrt = num ** 0.5 +print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) \ No newline at end of file diff --git a/python/Basics/Program to generate a random number between 0 and 9.py b/python/Basics/Program to generate a random number between 0 and 9.py new file mode 100644 index 0000000..8bf1dde --- /dev/null +++ b/python/Basics/Program to generate a random number between 0 and 9.py @@ -0,0 +1,6 @@ +# Program to generate a random number between 0 and 9 + +# import the random module +import random + +print(random.randint(0,9)) \ No newline at end of file diff --git a/python/Basics/Python Program To Display Powers of 2 Using Anonymous Function.py b/python/Basics/Python Program To Display Powers of 2 Using Anonymous Function.py new file mode 100644 index 0000000..e1c5564 --- /dev/null +++ b/python/Basics/Python Program To Display Powers of 2 Using Anonymous Function.py @@ -0,0 +1,29 @@ +# Python Program to display the powers of 2 using anonymous function + +# Change this value for a different result +terms = 10 + +# Uncomment to take number of terms from user +#terms = int(input("How many terms? ")) + +# use anonymous function +result = list(map(lambda x: 2 ** x, range(terms))) + +# display the result + +print("The total terms is:",terms) +for i in range(terms): + print("2 raised to power",i,"is",result[i]) + + Output: + The total terms is: 10 +2 raised to power 0 is 1 +2 raised to power 1 is 2 +2 raised to power 2 is 4 +2 raised to power 3 is 8 +2 raised to power 4 is 16 +2 raised to power 5 is 32 +2 raised to power 6 is 64 +2 raised to power 7 is 128 +2 raised to power 8 is 256 +2 raised to power 9 is 512 \ No newline at end of file diff --git a/python/Basics/Python Program to Add Two Matrices.py b/python/Basics/Python Program to Add Two Matrices.py new file mode 100644 index 0000000..9cc8310 --- /dev/null +++ b/python/Basics/Python Program to Add Two Matrices.py @@ -0,0 +1,22 @@ +# Program to add two matrices using nested loop + +X = [[12,7,3], + [4 ,5,6], + [7 ,8,9]] + +Y = [[5,8,1], + [6,7,3], + [4,5,9]] + +result = [[0,0,0], + [0,0,0], + [0,0,0]] + +# iterate through rows +for i in range(len(X)): + # iterate through columns + for j in range(len(X[0])): + result[i][j] = X[i][j] + Y[i][j] + +for r in result: + print(r) \ No newline at end of file diff --git a/python/Basics/Python Program to Check Armstrong Number.py b/python/Basics/Python Program to Check Armstrong Number.py new file mode 100644 index 0000000..b805177 --- /dev/null +++ b/python/Basics/Python Program to Check Armstrong Number.py @@ -0,0 +1,20 @@ +# Python program to check if the number provided by the user is an Armstrong number or not + +# take input from the user +# num = int(input("Enter a number: ")) + +# initialize sum +sum = 0 + +# find the sum of the cube of each digit +temp = num +while temp > 0: + digit = temp % 10 + sum += digit ** 3 + temp //= 10 + +# display the result +if num == sum: + print(num,"is an Armstrong number") +else: + print(num,"is not an Armstrong number") \ No newline at end of file diff --git a/python/Basics/Python Program to Check Leap Year.py b/python/Basics/Python Program to Check Leap Year.py new file mode 100644 index 0000000..0a463c3 --- /dev/null +++ b/python/Basics/Python Program to Check Leap Year.py @@ -0,0 +1,17 @@ +# Python program to check if the input year is a leap year or not + +year = 2000 + +# To get year (integer input) from the user +# year = int(input("Enter a year: ")) + +if (year % 4) == 0: + if (year % 100) == 0: + if (year % 400) == 0: + print("{0} is a leap year".format(year)) + else: + print("{0} is not a leap year".format(year)) + else: + print("{0} is a leap year".format(year)) +else: + print("{0} is not a leap year".format(year)) \ No newline at end of file diff --git a/python/Basics/Python Program to Check Prime Number.py b/python/Basics/Python Program to Check Prime Number.py new file mode 100644 index 0000000..ac467de --- /dev/null +++ b/python/Basics/Python Program to Check Prime Number.py @@ -0,0 +1,22 @@ +# Python program to check if the input number is prime or not + +num = 407 + +# take input from the user +# num = int(input("Enter a number: ")) + +# prime numbers are greater than 1 +if num > 1: + # check for factors + for i in range(2,num): + if (num % i) == 0: + print(num,"is not a prime number") + print(i,"times",num//i,"is",num) + break + else: + print(num,"is a prime number") + +# if input number is less than +# or equal to 1, it is not prime +else: + print(num,"is not a prime number") \ No newline at end of file diff --git a/python/Basics/Python Program to Check Whether a String is Palindrome or Not.py b/python/Basics/Python Program to Check Whether a String is Palindrome or Not.py new file mode 100644 index 0000000..f7f3134 --- /dev/null +++ b/python/Basics/Python Program to Check Whether a String is Palindrome or Not.py @@ -0,0 +1,17 @@ +# Program to check if a string +# is palindrome or not + +# change this value for a different output +my_str = 'aIbohPhoBiA' + +# make it suitable for caseless comparison +my_str = my_str.casefold() + +# reverse the string +rev_str = reversed(my_str) + +# check if the string is equal to its reverse +if list(my_str) == list(rev_str): + print("It is palindrome") +else: + print("It is not palindrome") \ No newline at end of file diff --git a/python/Basics/Python Program to Check if a Number is Odd or Even.py b/python/Basics/Python Program to Check if a Number is Odd or Even.py new file mode 100644 index 0000000..ad604f8 --- /dev/null +++ b/python/Basics/Python Program to Check if a Number is Odd or Even.py @@ -0,0 +1,5 @@ +num = int(input("Enter a number: ")) +if (num % 2) == 0: + print("{0} is Even".format(num)) +else: + print("{0} is Odd".format(num)) \ No newline at end of file diff --git a/python/Basics/Python Program to Convert Celsius To Fahrenheit.py b/python/Basics/Python Program to Convert Celsius To Fahrenheit.py new file mode 100644 index 0000000..e7897f9 --- /dev/null +++ b/python/Basics/Python Program to Convert Celsius To Fahrenheit.py @@ -0,0 +1,8 @@ +# Python Program to convert temperature in celsius to fahrenheit + +# change this value for a different result +celsius = 37.5 + +# calculate fahrenheit +fahrenheit = (celsius * 1.8) + 32 +print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit)) \ No newline at end of file diff --git a/python/Basics/Python Program to Convert Decimal to Binary Using Recursion.py b/python/Basics/Python Program to Convert Decimal to Binary Using Recursion.py new file mode 100644 index 0000000..b8fead5 --- /dev/null +++ b/python/Basics/Python Program to Convert Decimal to Binary Using Recursion.py @@ -0,0 +1,11 @@ +def convertToBinary(n): + """Function to print binary number + for the input decimal using recursion""" + if n > 1: + convertToBinary(n//2) + print(n % 2,end = '') + +# decimal number +dec = 34 + +convertToBinary(dec) \ No newline at end of file diff --git a/python/Basics/Python Program to Convert Decimal to Binary, Octal and Hexadecimal.py b/python/Basics/Python Program to Convert Decimal to Binary, Octal and Hexadecimal.py new file mode 100644 index 0000000..854a6ad --- /dev/null +++ b/python/Basics/Python Program to Convert Decimal to Binary, Octal and Hexadecimal.py @@ -0,0 +1,9 @@ +# Python program to convert decimal number into binary, octal and hexadecimal number system + +# Change this line for a different result +dec = 344 + +print("The decimal value of",dec,"is:") +print(bin(dec),"in binary.") +print(oct(dec),"in octal.") +print(hex(dec),"in hexadecimal.") \ No newline at end of file diff --git a/python/Basics/Python Program to Convert Kilometers to Miles.py b/python/Basics/Python Program to Convert Kilometers to Miles.py new file mode 100644 index 0000000..e5cfb3a --- /dev/null +++ b/python/Basics/Python Program to Convert Kilometers to Miles.py @@ -0,0 +1,11 @@ +kilometers = 5.5 + +# To take kilometers from the user, uncomment the code below +kilometers = input("Enter value in kilometers") + +# conversion factor +conv_fac = 0.621371 + +# calculate miles +miles = kilometers * conv_fac +print('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles)) \ No newline at end of file diff --git a/python/Basics/Python Program to Count the Number of Each Vowel.py b/python/Basics/Python Program to Count the Number of Each Vowel.py new file mode 100644 index 0000000..be0b21b --- /dev/null +++ b/python/Basics/Python Program to Count the Number of Each Vowel.py @@ -0,0 +1,23 @@ +# Program to count the number of each vowel in a string + +# string of vowels +vowels = 'aeiou' + +# change this value for a different result +ip_str = 'Hello, have you tried our turorial section yet?' + +# uncomment to take input from the user +#ip_str = input("Enter a string: ") + +# make it suitable for caseless comparisions +ip_str = ip_str.casefold() + +# make a dictionary with each vowel a key and value 0 +count = {}.fromkeys(vowels,0) + +# count the vowels +for char in ip_str: + if char in count: + count[char] += 1 + +print(count) \ No newline at end of file diff --git a/python/Basics/Python Program to Display Calendar.py b/python/Basics/Python Program to Display Calendar.py new file mode 100644 index 0000000..09d3bc8 --- /dev/null +++ b/python/Basics/Python Program to Display Calendar.py @@ -0,0 +1,14 @@ +# Python program to display calendar of given month of the year + +# import module +import calendar + +yy = 2014 +mm = 11 + +# To ask month and year from the user +# yy = int(input("Enter year: ")) +# mm = int(input("Enter month: ")) + +# display the calendar +print(calendar.month(yy, mm)) \ No newline at end of file diff --git a/python/Basics/Python Program to Display Fibonacci Sequence Using Recursion.py b/python/Basics/Python Program to Display Fibonacci Sequence Using Recursion.py new file mode 100644 index 0000000..feccb19 --- /dev/null +++ b/python/Basics/Python Program to Display Fibonacci Sequence Using Recursion.py @@ -0,0 +1,23 @@ +# Python program to display the Fibonacci sequence up to n-th term using recursive functions + +def recur_fibo(n): + """Recursive function to + print Fibonacci sequence""" + if n <= 1: + return n + else: + return(recur_fibo(n-1) + recur_fibo(n-2)) + +# Change this value for a different result +nterms = 10 + +# uncomment to take input from the user +#nterms = int(input("How many terms? ")) + +# check if the number of terms is valid +if nterms <= 0: + print("Plese enter a positive integer") +else: + print("Fibonacci sequence:") + for i in range(nterms): + print(recur_fibo(i)) \ No newline at end of file diff --git a/python/Basics/Python Program to Display the multiplication Table.py b/python/Basics/Python Program to Display the multiplication Table.py new file mode 100644 index 0000000..c4fcaa8 --- /dev/null +++ b/python/Basics/Python Program to Display the multiplication Table.py @@ -0,0 +1,11 @@ +''' Python program to find the +multiplication table (from 1 to 10)''' + +num = 12 + +# To take input from the user +# num = int(input("Display multiplication table of? ")) + +# use for loop to iterate 10 times +for i in range(1, 11): + print(num,'x',i,'=',num*i) \ No newline at end of file diff --git a/python/Basics/Python Program to Find ASCII Value of Character.py b/python/Basics/Python Program to Find ASCII Value of Character.py new file mode 100644 index 0000000..1052ff8 --- /dev/null +++ b/python/Basics/Python Program to Find ASCII Value of Character.py @@ -0,0 +1,9 @@ +# Program to find the ASCII value of the given character + +# Change this value for a different result +c = 'p' + +# Uncomment to take character from user +#c = input("Enter a character: ") + +print("The ASCII value of '" + c + "' is",ord(c)) \ No newline at end of file diff --git a/python/Basics/Python Program to Find Armstrong Number in an Interval.py b/python/Basics/Python Program to Find Armstrong Number in an Interval.py new file mode 100644 index 0000000..530a3f8 --- /dev/null +++ b/python/Basics/Python Program to Find Armstrong Number in an Interval.py @@ -0,0 +1,26 @@ +# Program to check Armstrong numbers in certain interval + +lower = 100 +upper = 2000 + +# To take input from the user +# lower = int(input("Enter lower range: ")) +# upper = int(input("Enter upper range: ")) + +for num in range(lower, upper + 1): + + # order of number + order = len(str(num)) + + # initialize sum + sum = 0 + + # find the sum of the cube of each digit + temp = num + while temp > 0: + digit = temp % 10 + sum += digit ** order + temp //= 10 + + if num == sum: + print(num) \ No newline at end of file diff --git a/python/Basics/Python Program to Find Factorial of Number Using Recursion.py b/python/Basics/Python Program to Find Factorial of Number Using Recursion.py new file mode 100644 index 0000000..3fb9da6 --- /dev/null +++ b/python/Basics/Python Program to Find Factorial of Number Using Recursion.py @@ -0,0 +1,23 @@ +# Python program to find the factorial of a number using recursion + +def recur_factorial(n): + """Function to return the factorial + of a number using recursion""" + if n == 1: + return n + else: + return n*recur_factorial(n-1) + +# Change this value for a different result +num = 7 + +# uncomment to take input from the user +#num = int(input("Enter a number: ")) + +# check is the number is negative +if num < 0: + print("Sorry, factorial does not exist for negative numbers") +elif num == 0: + print("The factorial of 0 is 1") +else: + print("The factorial of",num,"is",recur_factorial(num)) \ No newline at end of file diff --git a/python/Basics/Python Program to Find Factors of Number.py b/python/Basics/Python Program to Find Factors of Number.py new file mode 100644 index 0000000..3ed6213 --- /dev/null +++ b/python/Basics/Python Program to Find Factors of Number.py @@ -0,0 +1,18 @@ +# Python Program to find the factors of a number + +# define a function +def print_factors(x): + # This function takes a number and prints the factors + + print("The factors of",x,"are:") + for i in range(1, x + 1): + if x % i == 0: + print(i) + +# change this value for a different result. +num = 320 + +# uncomment the following line to take input from the user +#num = int(input("Enter a number: ")) + +print_factors(num) \ No newline at end of file diff --git a/python/Basics/Python Program to Find HCF or GCD.py b/python/Basics/Python Program to Find HCF or GCD.py new file mode 100644 index 0000000..cef7ef9 --- /dev/null +++ b/python/Basics/Python Program to Find HCF or GCD.py @@ -0,0 +1,26 @@ +# Python program to find the H.C.F of two input number + +# define a function +def computerHCF(x, y): + """This function takes two + integers and returns the H.C.F""" + + # choose the smaller number + if x > y: + smaller = y + else: + smaller = x + + for i in range(1,smaller + 1): + if((x % i == 0) and (y % i == 0)): + hcf = i + return hcf + +num1 = 54 +num2 = 24 + +# take input from the user +# num1 = int(input("Enter first number: ")) +# num2 = int(input("Enter second number: ")) + +print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2)) \ No newline at end of file diff --git a/python/Basics/Python Program to Find Hash of File.py b/python/Basics/Python Program to Find Hash of File.py new file mode 100644 index 0000000..e79f80a --- /dev/null +++ b/python/Basics/Python Program to Find Hash of File.py @@ -0,0 +1,27 @@ +# Python rogram to find the SHA-1 message digest of a file + +# import hashlib module +import hashlib + +def hash_file(filename): + """"This function returns the SHA-1 hash + of the file passed into it""" + + # make a hash object + h = hashlib.sha1() + + # open file for reading in binary mode + with open(filename,'rb') as file: + + # loop till the end of the file + chunk = 0 + while chunk != b'': + # read only 1024 bytes at a time + chunk = file.read(1024) + h.update(chunk) + + # return the hex representation of digest + return h.hexdigest() + +message = hash_file("track1.mp3") +print(message) \ No newline at end of file diff --git a/python/Basics/Python Program to Find LCM.py b/python/Basics/Python Program to Find LCM.py new file mode 100644 index 0000000..fbba211 --- /dev/null +++ b/python/Basics/Python Program to Find LCM.py @@ -0,0 +1,30 @@ +# Python Program to find the L.C.M. of two input number + +# define a function +def lcm(x, y): + """This function takes two + integers and returns the L.C.M.""" + + # choose the greater number + if x > y: + greater = x + else: + greater = y + + while(True): + if((greater % x == 0) and (greater % y == 0)): + lcm = greater + break + greater += 1 + + return lcm + +# change the values of num1 and num2 for a different result +num1 = 54 +num2 = 24 + +# uncomment the following lines to take input from the user +#num1 = int(input("Enter first number: ")) +#num2 = int(input("Enter second number: ")) + +print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2)) \ No newline at end of file diff --git a/python/Basics/Python Program to Find Numbers Divisible by Another Number.py b/python/Basics/Python Program to Find Numbers Divisible by Another Number.py new file mode 100644 index 0000000..8ce9c45 --- /dev/null +++ b/python/Basics/Python Program to Find Numbers Divisible by Another Number.py @@ -0,0 +1,10 @@ +# Python Program to find numbers divisible by thirteen from a list using anonymous function + +# Take a list of numbers +my_list = [12, 65, 54, 39, 102, 339, 221,] + +# use anonymous function to filter +result = list(filter(lambda x: (x % 13 == 0), my_list)) + +# display the result +print("Numbers divisible by 13 are",result) \ No newline at end of file diff --git a/python/Basics/Python Program to Find Sum of Natural Numbers Using Recursion.py b/python/Basics/Python Program to Find Sum of Natural Numbers Using Recursion.py new file mode 100644 index 0000000..c560063 --- /dev/null +++ b/python/Basics/Python Program to Find Sum of Natural Numbers Using Recursion.py @@ -0,0 +1,20 @@ +# Python program to find the sum of natural numbers up to n using recursive function + +def recur_sum(n): + """Function to return the sum + of natural numbers using recursion""" + if n <= 1: + return n + else: + return n + recur_sum(n-1) + +# change this value for a different result +num = 16 + +# uncomment to take input from the user +#num = int(input("Enter a number: ")) + +if num < 0: + print("Enter a positive number") +else: + print("The sum is",recur_sum(num)) \ No newline at end of file diff --git a/python/Basics/Python Program to Find the Factorial of a Number.py b/python/Basics/Python Program to Find the Factorial of a Number.py new file mode 100644 index 0000000..b5347e3 --- /dev/null +++ b/python/Basics/Python Program to Find the Factorial of a Number.py @@ -0,0 +1,19 @@ +# Python program to find the factorial of a number provided by the user. + +# change the value for a different result +num = 7 + +# uncomment to take input from the user +#num = int(input("Enter a number: ")) + +factorial = 1 + +# check if the number is negative, positive or zero +if num < 0: + print("Sorry, factorial does not exist for negative numbers") +elif num == 0: + print("The factorial of 0 is 1") +else: + for i in range(1,num + 1): + factorial = factorial*i + print("The factorial of",num,"is",factorial) \ No newline at end of file diff --git a/python/Basics/Python Program to Find the Largest Among Three Numbers.py b/python/Basics/Python Program to Find the Largest Among Three Numbers.py new file mode 100644 index 0000000..b8d12e8 --- /dev/null +++ b/python/Basics/Python Program to Find the Largest Among Three Numbers.py @@ -0,0 +1,21 @@ +# Python program to find the largest number among the three input numbers + +# change the values of num1, num2 and num3 +# for a different result +num1 = 10 +num2 = 14 +num3 = 12 + +# uncomment following lines to take three numbers from user +#num1 = float(input("Enter first number: ")) +#num2 = float(input("Enter second number: ")) +#num3 = float(input("Enter third number: ")) + +if (num1 > num2) and (num1 > num3): + largest = num1 +elif (num2 > num1) and (num2 > num3): + largest = num2 +else: + largest = num3 + +print("The largest number between",num1,",",num2,"and",num3,"is",largest) \ No newline at end of file diff --git a/python/Basics/Python Program to Find the Size (Resolution) of Image.py b/python/Basics/Python Program to Find the Size (Resolution) of Image.py new file mode 100644 index 0000000..ff18f5c --- /dev/null +++ b/python/Basics/Python Program to Find the Size (Resolution) of Image.py @@ -0,0 +1,26 @@ + # Python Program to find the resolution of a jpeg image without using external libraries + + def jpeg_res(filename): + """"This function prints the resolution + of the jpeg image file passed into it""" + + # open image for reading in binary mode + with open(filename,'rb') as img_file: + + # height of image (in 2 bytes) is at 164th position + img_file.seek(163) + + # read the 2 bytes + a = img_file.read(2) + + # calculate height + height = (a[0] << 8) + a[1] + + # next 2 bytes is width + a = img_file.read(2) + + # calculate width + width = (a[0] << 8) + a[1] + + print("The resolution of the image is",width,"x",height) + jpeg_res("img1.jpg") \ No newline at end of file diff --git a/python/Basics/Python Program to Find the Size (Resolution) of a Image.py b/python/Basics/Python Program to Find the Size (Resolution) of a Image.py new file mode 100644 index 0000000..c4d89e2 --- /dev/null +++ b/python/Basics/Python Program to Find the Size (Resolution) of a Image.py @@ -0,0 +1,24 @@ +def jpeg_res(filename): + """"This function prints the resolution of the jpeg image file passed into it""" + + # open image for reading in binary mode + with open(filename,'rb') as img_file: + + # height of image (in 2 bytes) is at 164th position + img_file.seek(163) + + # read the 2 bytes + a = img_file.read(2) + + # calculate height + height = (a[0] << 8) + a[1] + + # next 2 bytes is width + a = img_file.read(2) + + # calculate width + width = (a[0] << 8) + a[1] + + print("The resolution of the image is",width,"x",height) + +jpeg_res("img1.jpg") \ No newline at end of file diff --git a/python/Basics/Python Program to Find the Sum of Natural Numbers.py b/python/Basics/Python Program to Find the Sum of Natural Numbers.py new file mode 100644 index 0000000..a8efd63 --- /dev/null +++ b/python/Basics/Python Program to Find the Sum of Natural Numbers.py @@ -0,0 +1,17 @@ +# Python program to find the sum of natural numbers up to n where n is provided by user + +# change this value for a different result +num = 16 + +# uncomment to take input from the user +#num = int(input("Enter a number: ")) + +if num < 0: + print("Enter a positive number") +else: + sum = 0 + # use while loop to iterate un till zero + while(num > 0): + sum += num + num -= 1 + print("The sum is",sum) \ No newline at end of file diff --git a/python/Basics/Python Program to Illustrate Different Set Operations.py b/python/Basics/Python Program to Illustrate Different Set Operations.py new file mode 100644 index 0000000..f3b27e2 --- /dev/null +++ b/python/Basics/Python Program to Illustrate Different Set Operations.py @@ -0,0 +1,17 @@ +# Program to perform different set operations like in mathematics + +# define three sets +E = {0, 2, 4, 6, 8}; +N = {1, 2, 3, 4, 5}; + +# set union +print("Union of E and N is",E | N) + +# set intersection +print("Intersection of E and N is",E & N) + +# set difference +print("Difference of E and N is",E - N) + +# set symmetric difference +print("Symmetric difference of E and N is",E ^ N) \ No newline at end of file diff --git a/python/Basics/Python Program to Make a Simple Calculator.py b/python/Basics/Python Program to Make a Simple Calculator.py new file mode 100644 index 0000000..41aa2e3 --- /dev/null +++ b/python/Basics/Python Program to Make a Simple Calculator.py @@ -0,0 +1,44 @@ +''' Program make a simple calculator that can add, subtract, multiply and divide using functions ''' + +# define functions +def add(x, y): + """This function adds two numbers""" + return x + y + +def subtract(x, y): + """This function subtracts two numbers""" + return x - y + +def multiply(x, y): + """This function multiplies two numbers""" + return x * y + +def divide(x, y): + """This function divides two numbers""" + return x / y + +# take input from the user +print("Select operation.") +print("1.Add") +print("2.Subtract") +print("3.Multiply") +print("4.Divide") + +choice = input("Enter choice(1/2/3/4):") + +num1 = int(input("Enter first number: ")) +num2 = int(input("Enter second number: ")) + +if choice == '1': + print(num1,"+",num2,"=", add(num1,num2)) + +elif choice == '2': + print(num1,"-",num2,"=", subtract(num1,num2)) + +elif choice == '3': + print(num1,"*",num2,"=", multiply(num1,num2)) + +elif choice == '4': + print(num1,"/",num2,"=", divide(num1,num2)) +else: + print("Invalid input") \ No newline at end of file diff --git a/python/Basics/Python Program to Merge Mails.py b/python/Basics/Python Program to Merge Mails.py new file mode 100644 index 0000000..08b1a26 --- /dev/null +++ b/python/Basics/Python Program to Merge Mails.py @@ -0,0 +1,20 @@ +# Python program to mail merger +# Names are in the file names.txt +# Body of the mail is in body.txt + +# open names.txt for reading +with open("names.txt",'r',encoding = 'utf-8') as names_file: + + # open body.txt for reading + with open("body.txt",'r',encoding = 'utf-8') as body_file: + + # read entire content of the body + body = body_file.read() + + # iterate over names + for name in names_file: + mail = "Hello "+name+body + + # write the mails to individual files + with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file: + mail_file.write(mail) \ No newline at end of file diff --git a/python/Basics/Python Program to Multiply Two Matrices.py b/python/Basics/Python Program to Multiply Two Matrices.py new file mode 100644 index 0000000..d0a0cf2 --- /dev/null +++ b/python/Basics/Python Program to Multiply Two Matrices.py @@ -0,0 +1,25 @@ +# Program to multiply two matrices using nested loops + +# 3x3 matrix +X = [[12,7,3], + [4 ,5,6], + [7 ,8,9]] +# 3x4 matrix +Y = [[5,8,1,2], + [6,7,3,0], + [4,5,9,1]] +# result is 3x4 +result = [[0,0,0,0], + [0,0,0,0], + [0,0,0,0]] + +# iterate through rows of X +for i in range(len(X)): + # iterate through columns of Y + for j in range(len(Y[0])): + # iterate through rows of Y + for k in range(len(Y)): + result[i][j] += X[i][k] * Y[k][j] + +for r in result: + print(r) \ No newline at end of file diff --git a/python/Basics/Python Program to Print all Prime Numbers in an Interval.py b/python/Basics/Python Program to Print all Prime Numbers in an Interval.py new file mode 100644 index 0000000..3eb7fc8 --- /dev/null +++ b/python/Basics/Python Program to Print all Prime Numbers in an Interval.py @@ -0,0 +1,20 @@ +# Python program to display all the prime numbers within an interval + +# change the values of lower and upper for a different result +lower = 900 +upper = 1000 + +# uncomment the following lines to take input from the user +#lower = int(input("Enter lower range: ")) +#upper = int(input("Enter upper range: ")) + +print("Prime numbers between",lower,"and",upper,"are:") + +for num in range(lower,upper + 1): + # prime numbers are greater than 1 + if num > 1: + for i in range(2,num): + if (num % i) == 0: + break + else: + print(num) \ No newline at end of file diff --git a/python/Basics/Python Program to Print the Fibonacci sequence.py b/python/Basics/Python Program to Print the Fibonacci sequence.py new file mode 100644 index 0000000..4a7285c --- /dev/null +++ b/python/Basics/Python Program to Print the Fibonacci sequence.py @@ -0,0 +1,29 @@ +# Program to display the Fibonacci sequence up to n-th term where n is provided by the user + +# change this value for a different result +nterms = 10 + +# uncomment to take input from the user +#nterms = int(input("How many terms? ")) + +# first two terms +n1 = 0 +n2 = 1 +count = 2 + +# check if the number of terms is valid +if nterms <= 0: + print("Please enter a positive integer") +elif nterms == 1: + print("Fibonacci sequence upto",nterms,":") + print(n1) +else: + print("Fibonacci sequence upto",nterms,":") + print(n1,",",n2,end=', ') + while count < nterms: + nth = n1 + n2 + print(nth,end=' , ') + # update values + n1 = n2 + n2 = nth + count += 1 \ No newline at end of file diff --git a/python/Basics/Python Program to Remove Punctuations From a String.py b/python/Basics/Python Program to Remove Punctuations From a String.py new file mode 100644 index 0000000..51c8b93 --- /dev/null +++ b/python/Basics/Python Program to Remove Punctuations From a String.py @@ -0,0 +1,16 @@ +# define punctuation +punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' + +my_str = "Hello!!!, he said ---and went." + +# To take input from the user +# my_str = input("Enter a string: ") + +# remove punctuation from the string +no_punct = "" +for char in my_str: + if char not in punctuations: + no_punct = no_punct + char + +# display the unpunctuated string +print(no_punct) \ No newline at end of file diff --git a/python/Basics/Python Program to Shuffle Deck of Cards.py b/python/Basics/Python Program to Shuffle Deck of Cards.py new file mode 100644 index 0000000..64864d3 --- /dev/null +++ b/python/Basics/Python Program to Shuffle Deck of Cards.py @@ -0,0 +1,15 @@ +# Python program to shuffle a deck of card using the module random and draw 5 cards + +# import modules +import itertools, random + +# make a deck of cards +deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club'])) + +# shuffle the cards +random.shuffle(deck) + +# draw five cards +print("You got:") +for i in range(5): + print(deck[i][0], "of", deck[i][1]) \ No newline at end of file diff --git a/python/Basics/Python Program to Solve the quadratic equation.py b/python/Basics/Python Program to Solve the quadratic equation.py new file mode 100644 index 0000000..87424b8 --- /dev/null +++ b/python/Basics/Python Program to Solve the quadratic equation.py @@ -0,0 +1,22 @@ +# Solve the quadratic equation ax**2 + bx + c = 0 + +# import complex math module +import cmath + +a = 1 +b = 5 +c = 6 + +# To take coefficient input from the users +# a = float(input('Enter a: ')) +# b = float(input('Enter b: ')) +# c = float(input('Enter c: ')) + +# calculate the discriminant +d = (b**2) - (4*a*c) + +# find two solutions +sol1 = (-b-cmath.sqrt(d))/(2*a) +sol2 = (-b+cmath.sqrt(d))/(2*a) + +print('The solution are {0} and {1}'.format(sol1,sol2)) \ No newline at end of file diff --git a/python/Basics/Python Program to Sort Words in Alphabetic Order.py b/python/Basics/Python Program to Sort Words in Alphabetic Order.py new file mode 100644 index 0000000..11f6db9 --- /dev/null +++ b/python/Basics/Python Program to Sort Words in Alphabetic Order.py @@ -0,0 +1,19 @@ +# Program to sort alphabetically the words form a string provided by the user + +# change this value for a different result +my_str = "Hello this Is an Example With cased letters" + +# uncomment to take input from the user +#my_str = input("Enter a string: ") + +# breakdown the string into a list of words +words = my_str.split() + +# sort the list +words.sort() + +# display the sorted words + +print("The sorted words are:") +for word in words: + print(word) \ No newline at end of file diff --git a/python/Basics/Python Program to Transpose a Matrix.py b/python/Basics/Python Program to Transpose a Matrix.py new file mode 100644 index 0000000..623d8ef --- /dev/null +++ b/python/Basics/Python Program to Transpose a Matrix.py @@ -0,0 +1,17 @@ +# Program to transpose a matrix using nested loop + +X = [[12,7], + [4 ,5], + [3 ,8]] + +result = [[0,0,0], + [0,0,0]] + +# iterate through rows +for i in range(len(X)): + # iterate through columns + for j in range(len(X[0])): + result[j][i] = X[i][j] + +for r in result: + print(r) \ No newline at end of file diff --git a/python/Basics/Python Program to find the area of triangle.py b/python/Basics/Python Program to find the area of triangle.py new file mode 100644 index 0000000..cf34cf0 --- /dev/null +++ b/python/Basics/Python Program to find the area of triangle.py @@ -0,0 +1,17 @@ +# Python Program to find the area of triangle + +a = 5 +b = 6 +c = 7 + +# Uncomment below to take inputs from the user +# a = float(input('Enter first side: ')) +# b = float(input('Enter second side: ')) +# c = float(input('Enter third side: ')) + +# calculate the semi-perimeter +s = (a + b + c) / 2 + +# calculate the area +area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 +print('The area of the triangle is %0.2f' %area) \ No newline at end of file diff --git a/python/Basics/Python program that accepts a comma separated sequence of words as input and prints the unique words in sorted form (alphanumerically).py b/python/Basics/Python program that accepts a comma separated sequence of words as input and prints the unique words in sorted form (alphanumerically).py new file mode 100644 index 0000000..7d99aaa --- /dev/null +++ b/python/Basics/Python program that accepts a comma separated sequence of words as input and prints the unique words in sorted form (alphanumerically).py @@ -0,0 +1,3 @@ +items = input("Input comma separated sequence of words") +words = [word for word in items.split(",")] +print(",".join(sorted(list(set(words))))) \ No newline at end of file diff --git a/python/Basics/Python program to count the number of characters (character frequency) in a string.py b/python/Basics/Python program to count the number of characters (character frequency) in a string.py new file mode 100644 index 0000000..1890f8f --- /dev/null +++ b/python/Basics/Python program to count the number of characters (character frequency) in a string.py @@ -0,0 +1,10 @@ +def char_frequency(str1): + dict = {} + for n in str1: + keys = dict.keys() + if n in keys: + dict[n] += 1 + else: + dict[n] = 1 + return dict +print(char_frequency('google.com')) \ No newline at end of file diff --git a/python/Basics/Python program to count the occurrences of each word in a given sentence.py b/python/Basics/Python program to count the occurrences of each word in a given sentence.py new file mode 100644 index 0000000..a994916 --- /dev/null +++ b/python/Basics/Python program to count the occurrences of each word in a given sentence.py @@ -0,0 +1,13 @@ +def word_count(str): + counts = dict() + words = str.split() + + for word in words: + if word in counts: + counts[word] += 1 + else: + counts[word] = 1 + + return counts + +print( word_count('the quick brown fox jumps over the lazy dog.')) \ No newline at end of file diff --git a/python/Basics/Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.py b/python/Basics/Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.py new file mode 100644 index 0000000..e33d485 --- /dev/null +++ b/python/Basics/Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.py @@ -0,0 +1,9 @@ +def change_char(str1): + char = str1[0] + length = len(str1) + str1 = str1.replace(char, '$') + str1 = char + str1[1:] + + return str1 + +print(change_char('restart')) \ No newline at end of file diff --git a/python/Basics/Python program to get a string made of the first 2 and the last 2 chars from a given a string.py b/python/Basics/Python program to get a string made of the first 2 and the last 2 chars from a given a string.py new file mode 100644 index 0000000..350c517 --- /dev/null +++ b/python/Basics/Python program to get a string made of the first 2 and the last 2 chars from a given a string.py @@ -0,0 +1,9 @@ +def string_both_ends(str): + if len(str) < 2: + return '' + + return str[0:2] + str[-2:] + +print(string_both_ends('w3resource')) +print(string_both_ends('w3')) +print(string_both_ends('w')) \ No newline at end of file diff --git a/python/Basics/Python program to get the the volume of a sphere with radius 6.py b/python/Basics/Python program to get the the volume of a sphere with radius 6.py new file mode 100644 index 0000000..f720644 --- /dev/null +++ b/python/Basics/Python program to get the the volume of a sphere with radius 6.py @@ -0,0 +1,4 @@ +pi = 3.1415926535897931 +r= 6.0 +V= 4.0/3.0*pi* r**3 +print('The volume of the sphere is: ',V) \ No newline at end of file diff --git a/python/Basics/Python program to swap two variables.py b/python/Basics/Python program to swap two variables.py new file mode 100644 index 0000000..0716dce --- /dev/null +++ b/python/Basics/Python program to swap two variables.py @@ -0,0 +1,16 @@ +# Python program to swap two variables + +# To take input from the user +# x = input('Enter value of x: ') +# y = input('Enter value of y: ') + +x = 5 +y = 10 + +# create a temporary variable and swap the values +temp = x +x = y +y = temp + +print('The value of x after swapping: {}'.format(x)) +print('The value of y after swapping: {}'.format(y)) \ No newline at end of file diff --git a/python/Basics/Python script that takes input from the user and displays that input back in upper and lower cases.py b/python/Basics/Python script that takes input from the user and displays that input back in upper and lower cases.py new file mode 100644 index 0000000..2961a85 --- /dev/null +++ b/python/Basics/Python script that takes input from the user and displays that input back in upper and lower cases.py @@ -0,0 +1,3 @@ +user_input = input("What's your favourite language? ") +print("My favourite language is ", user_input.upper()) +print("My favourite language is ", user_input.lower()) \ No newline at end of file diff --git a/python/Basics/Return true if the two given int values are equal or their sum or difference is 5.py b/python/Basics/Return true if the two given int values are equal or their sum or difference is 5.py new file mode 100644 index 0000000..9804503 --- /dev/null +++ b/python/Basics/Return true if the two given int values are equal or their sum or difference is 5.py @@ -0,0 +1,9 @@ +def test_number5(x, y): + if x == 5 or y == 5 or abs(x-y) == 5 or (x+y) == 5: + return True + else: + return False + +print(test_number5(7, 2)) +print(test_number5(3, 2)) +print(test_number5(2, 2)) \ No newline at end of file diff --git a/python/Basics/Sort files by date.py b/python/Basics/Sort files by date.py new file mode 100644 index 0000000..7bc0e36 --- /dev/null +++ b/python/Basics/Sort files by date.py @@ -0,0 +1,6 @@ +import glob +import os + +files = glob.glob("*.txt") +files.sort(key=os.path.getmtime) +print("\n".join(files)) \ No newline at end of file diff --git a/python/Basics/Sum of the first n positive integers.py b/python/Basics/Sum of the first n positive integers.py new file mode 100644 index 0000000..813573e --- /dev/null +++ b/python/Basics/Sum of the first n positive integers.py @@ -0,0 +1,3 @@ +n = int(input("Input a number: ")) +sum_num = (n * (n + 1)) / 2 +print(sum_num) \ No newline at end of file diff --git a/python/Basics/Test whether a number is within 100 of 1000 or 2000.py b/python/Basics/Test whether a number is within 100 of 1000 or 2000.py new file mode 100644 index 0000000..606450e --- /dev/null +++ b/python/Basics/Test whether a number is within 100 of 1000 or 2000.py @@ -0,0 +1,6 @@ +def near_thousand(n): + return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100)) +print(near_thousand(1000)) +print(near_thousand(900)) +print(near_thousand(800)) +print(near_thousand(2200)) \ No newline at end of file diff --git a/python/Basics/Test whether a passed letter is a vowel or not.py b/python/Basics/Test whether a passed letter is a vowel or not.py new file mode 100644 index 0000000..f6d659a --- /dev/null +++ b/python/Basics/Test whether a passed letter is a vowel or not.py @@ -0,0 +1,5 @@ +def is_vowel(char): + all_vowels = 'aeiou' + return char in all_vowels +print(is_vowel('c')) +print(is_vowel('e')) \ No newline at end of file diff --git a/python/README.md b/python/README.md new file mode 100644 index 0000000..a9ce571 --- /dev/null +++ b/python/README.md @@ -0,0 +1,3 @@ +# Python programming language + +Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace. \ No newline at end of file diff --git a/ruby/Basics/CheckForPowerOfTwo.rb b/ruby/Basics/CheckForPowerOfTwo.rb new file mode 100644 index 0000000..340c5eb --- /dev/null +++ b/ruby/Basics/CheckForPowerOfTwo.rb @@ -0,0 +1,13 @@ +#Given a number,check if it is power of 2 or not without using division or modulo operator. +#Algorithm: For any power of 2,say x, the bitwise and of x and x-1 is always 0. +#e.g. 64 = 1000000, 63= 0111111 now 1000000&0111111==0000000 + +def check_power(x) + if x&(x-1)==0 + print "#{x} is power of two" + else + print "#{x} is not power of two" + end +end +check_power(126) # => 126 is not power of two +check_power(1024) # => 1024 is power of two \ No newline at end of file diff --git a/ruby/Basics/CheckIFEvenOrOdd.rb b/ruby/Basics/CheckIFEvenOrOdd.rb new file mode 100644 index 0000000..fedfdf3 --- /dev/null +++ b/ruby/Basics/CheckIFEvenOrOdd.rb @@ -0,0 +1,12 @@ +#Given a number,check if it is even or odd using bit operations. +#Algorithm: let num be x +#find x&1 ,if result is 0 then even else odd. +#The Least significant bit of odd number is always 1 and even is always 0,hence x&1 will be 0 if even else odd. + +def check_evenOdd(x) + if x&1==0 + print "#{x} is even" + else + print "#{x} is odd" + end +end \ No newline at end of file diff --git a/ruby/Basics/CountSetBits.rb b/ruby/Basics/CountSetBits.rb new file mode 100644 index 0000000..0cfd13b --- /dev/null +++ b/ruby/Basics/CountSetBits.rb @@ -0,0 +1,12 @@ +#Given a number "n",count the number of set bits in it. +#Algorithm: Brian Kernighan's method(set count=0 ,while n>0 set n:=n&(n-1) and increment count, return count) +#Time-complexity:O(logn) + +def count_set_bits(num) + count=0 + while num>0 + num&=(num-1) + count+=1 + end + return count +end \ No newline at end of file diff --git a/ruby/Basics/UnsetRightmostSetBit.rb b/ruby/Basics/UnsetRightmostSetBit.rb new file mode 100644 index 0000000..b823b33 --- /dev/null +++ b/ruby/Basics/UnsetRightmostSetBit.rb @@ -0,0 +1,8 @@ +#Given a binary number unset the rightmost set bit. +#Algorithm: The biwise "&" of any number n with n-1 unsets the rightmost set bit +#e.g. 5=101 ,5-1=4=100 ,5&4=(101)&(100)=100(result with rightmost bit unset) + +def unset_rightmost(n) + return n&(n-1) +end +unset_rightmost(3) # => 2 \ No newline at end of file diff --git a/ruby/Basics/auth.rb b/ruby/Basics/auth.rb new file mode 100644 index 0000000..ee22bdd --- /dev/null +++ b/ruby/Basics/auth.rb @@ -0,0 +1,45 @@ +require "csv" +require "logger" + +class AuthenticationError < StandardError +end + +class User + attr_reader :username + attr_reader :password + + def initialize(username, password) + raise ArgumentError unless /^[A-Za-z0-9_-]{3,16}$/.match(username) + raise ArgumentError unless /^[A-Za-z0-9!@#$%^&*()_+-=]{6,16}$/.match(password) + @username = username + @password = password + end +end + +class Application + def initialize + @logger = Logger.new(STDOUT) + @users = {} + @is_authenticated = false + end + + def load_users(filename) + # Your code goes here + end + + def login + until @is_authenticated + # Your code goes here + end + + @logger.info("Login successful!") + end + + def run + login + end +end + +application = Application.new +application.load_users("users.csv") +application.run diff --git a/ruby/Basics/basic_game.rb b/ruby/Basics/basic_game.rb new file mode 100644 index 0000000..c7edc56 --- /dev/null +++ b/ruby/Basics/basic_game.rb @@ -0,0 +1,19 @@ +class Player + # Your code goes here +end + +class Game + # Your code goes here +end + +game = Game.new("RPS") + +players = [ + Player.new("John"), + Player.new("Lizzy"), + Player.new("Clair"), + Player.new("Brad"), + 15 +] + +players.each { |player| game.add_player(player) } diff --git a/ruby/Basics/card_deck.rb b/ruby/Basics/card_deck.rb new file mode 100644 index 0000000..aa68fb2 --- /dev/null +++ b/ruby/Basics/card_deck.rb @@ -0,0 +1,14 @@ +# Create a standard 52 card deck +# Sort card suits according to Hearts, Diamonds, Clubs, then Spades. +# Sort cards in ascending order, from 2 to Ace. + +def create_deck + # Your code goes here +end + + +card_deck = create_deck + +puts card_deck[0] == "2h" # 2 of Hearts +puts card_deck[8] == "10h" # 10 of Hearts +puts card_deck[51] == "As" # Ace of Spades diff --git a/ruby/Basics/dependency_inversion.rb b/ruby/Basics/dependency_inversion.rb new file mode 100644 index 0000000..196e16c --- /dev/null +++ b/ruby/Basics/dependency_inversion.rb @@ -0,0 +1,48 @@ +# The Dependency Inversion Principle has to do with high-level (think business +# logic) objects not depending on low-level (think database querying and IO) +# implementation details. This can be achieved with duck typing and the +# Dependency Inversion Principle. Often this pattern is used to achieve the +# Open/Closed Principle that we discussed above. In fact, we can even reuse +# that same example as a demonstration of this principle. + +# Now there is a formatter class, but I've hardcoded it on the Report class, +# thus creating a dependency from the Report to the JSONFormatter. Since the +# Report is a more abstract (high-level) concept than the JSONFormatter, we're +# effectively breaking the DIP. + +class Report + def body + # Implementation + end + + def print + JSONFormatter.new.format(body) + end +end + +class JSONFormatter + def format(body) + # Implementation + end +end + +# Solution + +# This way the Report does not depend on the JSONFormatter and can use any type +# of formatter that has a method called format (this is known as duck typing). +# Another thing of note is that we've used, once again, dependency injection to +# solve a problem. This technique is a very powerful one when our goal is +# decoupling objects, and even though it has the same initials as the dependency +# inversion principle (vs dependency injection pattern), they are completely +# different concepts. + +class Report + def body + # Implementation + end + + def print(formatter: JSONFormatter.new) + formatter.format body + end +end + diff --git a/ruby/Basics/family.rb b/ruby/Basics/family.rb new file mode 100644 index 0000000..b20700e --- /dev/null +++ b/ruby/Basics/family.rb @@ -0,0 +1,8 @@ +# Ages of family members +mom = 48 +dad = 51 +john = 18 +mary = 16 + +# Your code goes here + diff --git a/ruby/Basics/fibers.rb b/ruby/Basics/fibers.rb new file mode 100644 index 0000000..be1bad3 --- /dev/null +++ b/ruby/Basics/fibers.rb @@ -0,0 +1,22 @@ +# Fibers are primitives for implementing light weight cooperative concurrency in +# Ruby. Basically they are a means of creating code blocks that can be paused +# and resumed, much like threads. The main difference is that they are never +# preempted and that the scheduling must be done by the programmer and not the VM. + +require 'fiber' + +f = Fiber.new do |value| + first = value + puts "first call fiber with args: #{first ? first : 'not passed'}" + second = Fiber.yield + puts "second call fiber with args: #{second ? second : 'not passed'}" + other = Fiber.yield + puts "First: #{first}, Second: #{second}, Other: #{other ? other : 'not passed'}" + puts "Last call" +end + +f.resume('First argument') +f.resume('Second argument') +f.resume +# f.resume call error if try call one more time fiber is dead + diff --git a/ruby/Basics/fibonacci.rb b/ruby/Basics/fibonacci.rb new file mode 100644 index 0000000..a81c6fa --- /dev/null +++ b/ruby/Basics/fibonacci.rb @@ -0,0 +1,4 @@ +# Print out all the Fibonacci numbers from 1 to 10 in order + +# Your code goes here + diff --git a/ruby/Basics/fighter.rb b/ruby/Basics/fighter.rb new file mode 100644 index 0000000..4cee2d4 --- /dev/null +++ b/ruby/Basics/fighter.rb @@ -0,0 +1,23 @@ +require "logger" +require_relative "mixins" + +module Logging + # Provided for your convenience + def logger + Logging.logger + end + + def self.logger + @logger ||= Logger.new(STDOUT) + end +end + +class Fighter + # Your code goes here +end + +fighter = Fighter.new("Bruce Lee") +fighter.uppercut +fighter.block +fighter.riposte +fighter.straight_kick diff --git a/ruby/Basics/game_rankings.rb b/ruby/Basics/game_rankings.rb new file mode 100644 index 0000000..e3fab17 --- /dev/null +++ b/ruby/Basics/game_rankings.rb @@ -0,0 +1,17 @@ +# Top 10 Nintendo 64 games from Gamerankings + +game_rankings = { + "The Legend of Zelda: Ocarina of Time" => 0.9754, + "Super Mario 64" => 0.9641, + "GoldenEye 007" => 0.9470, + "Perfect Dark" => 0.9455, + "The Legend of Zelda: Majora's Mask" => 0.9195, + "1080: TenEighty Snowboarding" => 0.8960, + "Conker's Bad Fur Day" => 0.8928, + "Excitebike 64" => 0.8907, + "Turok 2: Seeds of Evil" => 0.8896, + "Paper Mario" => 0.8881 +} + +# Your code goes here + diff --git a/ruby/Basics/gil.rb b/ruby/Basics/gil.rb new file mode 100644 index 0000000..a167168 --- /dev/null +++ b/ruby/Basics/gil.rb @@ -0,0 +1,25 @@ +# This simple fact is what makes threads so powerful, and also what makes them +# difficult to work with. I've already given you an idea of why threads are +# good; here's a simple program to illustrate their difficulty. + +shared_array = Array.new + +10.times.map do + Thread.new do + 1000.times do + shared_array << nil + end + end +end.each(&:join) + +# Here you can see that we have 10 * 10000 elements in array + +puts shared_array.size + +# Note that different ruby can show different result +# GIL exist only in MRI ruby + +# $ ruby => 10000 +# $ jruby => 7521 +# $ rbx => 8541 + diff --git a/ruby/Basics/inheritance robots.rb b/ruby/Basics/inheritance robots.rb new file mode 100644 index 0000000..7f1ef4a --- /dev/null +++ b/ruby/Basics/inheritance robots.rb @@ -0,0 +1,15 @@ +class Robot + # Your code goes here +end + +class Ultron < Robot + # Your code goes here +end + +class MegaMan < Robot + # Your code goes here +end + +class Glados < Robot + # Your code goes here +end diff --git a/ruby/Basics/interface_segregation.rb b/ruby/Basics/interface_segregation.rb new file mode 100644 index 0000000..d2c990b --- /dev/null +++ b/ruby/Basics/interface_segregation.rb @@ -0,0 +1,96 @@ +# The principle states that a client should not be forced to depend on methods +# that it does not use + +# In this example, there are Computer, Programmer and Technician classes. Both, +# Programmer and Technician use the Computer in a different way. The programmer +# uses the computer for typing, but the technician knows how to change the +# computer hard drive. What Interface Segregation Principle (ISP) enforces is +# that one class should not depend on methods it does not use. +# In our case, Programmer is unnecessarily coupled to the +# Computer#change_hard_drive method because it does not use it, but the state +# changes that this method enforces can affect the Programmer. Let's refactor +# the code to obey the LSP. + +class Computer + def turn_on + # Implementation + end + + def type + # Implementation + end + + def change_hard_drive + # Implementation + end +end + +class User + attr_reader :computer + + def initialize(computer) + @computer = computer + end +end + +class Programmer < User + def use_computer + computer.turn_on + computer.type + end +end + +class Technician < User + def fix_computer + computer.change_hard_drive + end +end + +# Solution + +# After this refactor the Technician uses a different object from the type +# ComputerInternals which is isolated from the state of the Computer. The state +# of the Computer object can be influenced by the Programmer but the changes +# wont affect the Technician in any way. + +class Computer + def turn_on + # Implementation + end + + def type + # Implementation + end +end + +class ComputerInternals + def change_hard_drive + # Implementation + end +end + +class Programmer + attr_reader :computer + + def initialize(computer) + @computer = computer + end + + def use_computer + computer.turn_on + computer.type + end +end + +class Technician + attr_reader :computer_internals + + def initialize(computer_internals) + @computer_internals = computer_internals + end + + def fix_computer + computer_internals.change_hard_drive + end +end + diff --git a/ruby/Basics/liskov_substitution.rb b/ruby/Basics/liskov_substitution.rb new file mode 100644 index 0000000..2293448 --- /dev/null +++ b/ruby/Basics/liskov_substitution.rb @@ -0,0 +1,82 @@ +# Liskov’s principle tends to be the most difficult to understand. The principle +# states that you should be able to replace any instances of a parent class +# with an instance of one of its children without creating any unexpected or +# incorrect behaviors. + +class Rectangle + def initialize(height, width) + @height = height + @width = width + end + + def set_height(height) + @height = height + end + + def set_width(width) + @width = width + end + + def square + @width * @height + end +end + +# Solution + +# LSP says is if we know the interface of Rectangle, We need to be able to guess +# the interface of subtype class Square +# Square.new(3).square => 9 + +class Square < Rectangle + def initialize(side) + super(side, side) + end + + def set_height(height) + super(height) + @width = height + end + + def set_width(width) + super(width) + @height = width + end +end + +# Another common instance of a Liskov violation is raising an exception for an +# overridden method in a child class. It’s also not uncommon to see methods +# overridden with modified method signatures causing branching on type in +# classes that depend on objects of the parent’s type. All of these either +# lead to unstable code or unnecessary and ugly branching. + +class Animal + def walk + 'walking_as_animal' + end +end + +class Cat < Animal + def run + 'run_as_cat' + end +end + +# Solution + +class Animal + def walk + 'walking_as_animal' + end + + def run + raise NotImplementedError + end +end + +class Cat < Animal + def run + 'run_as_cat' + end +end + diff --git a/ruby/Basics/mixins.rb b/ruby/Basics/mixins.rb new file mode 100644 index 0000000..964f537 --- /dev/null +++ b/ruby/Basics/mixins.rb @@ -0,0 +1,15 @@ +module WingChunMixin + # Your code goes here +end + +module BoxingMixin + # Your code goes here +end + +module FencingMixin + # Your code goes here +end + +module JeetKuneDoMixin + # Your code goes here +end diff --git a/ruby/Basics/mutex.rb b/ruby/Basics/mutex.rb new file mode 100644 index 0000000..c3acd6b --- /dev/null +++ b/ruby/Basics/mutex.rb @@ -0,0 +1,46 @@ +# Mutexes provide a mechanism for multiply threads to synchronize access to a +# critical portion of code. It helps bring some order and some guaranty to the +# world of multi-threaded chaos. +# In this program, since any thread has to lock the mutex before it can push to +# the Array, there's a guarantee that no two threads will be performing this +# operation at the same time. In other words, this operation can no longer be +# interrupted before it's completed. Once one thread begins pushing to the +# Array, no other threads will be able to enter that portion of code until the +# first thread is finished. This operation is now thread-safe. + +shared_array = Array.new +# Notice that the mutex is shared among all the threads. The guarantee only +# works if the threads are sharing the same Mutex instance. In this way, when +# one thread locks a mutex, others have to wait for it to be unlocked. +mutex = Mutex.new + +10.times.map do + Thread.new do + 1000.times do + # Thread lock mutex and become owner, could be one one owner + # Now only one thread can run wrapper code and update + mutex.lock + shared_array << nil + mutex.unlock + # After unlock mutex other threads can lock mutex + + # Other convenience method to do same + # mutex.synchronize { shared_array << nil } + end + end +end.each(&:join) + +# Here you can see that we have 10 * 10000 elements in array + +puts shared_array.size + +# Now all are same, because of mutex/ +# The mutex sets up same boundaries for the thread. The first thread that hits +# this bit of code will lock the mutex. it then becomes the owner of that mutex. +# Until the owning thread unlocks the mutex, no other thread can lock it. + + +# $ ruby => 10000 +# $ jruby => 10000 +# $ rbx => 1000 + diff --git a/ruby/Basics/names.rb b/ruby/Basics/names.rb new file mode 100644 index 0000000..e360f0d --- /dev/null +++ b/ruby/Basics/names.rb @@ -0,0 +1,8 @@ +# Game of Thrones characters +name1 = "Joffrey Baratheon" +name2 = "Arya Stark" +name3 = "Beric Dondarrion" +name4 = "Melisandre" + +# Your code goes here + diff --git a/ruby/Basics/netflix.rb b/ruby/Basics/netflix.rb new file mode 100644 index 0000000..494c8c9 --- /dev/null +++ b/ruby/Basics/netflix.rb @@ -0,0 +1,41 @@ +class Movie + attr_reader :title + + def initialize(title) + @title = title + end +end + +class NetflixAccount + # Your code goes here + + def initialize(username) + @username = username + @my_list = [] + @recently_watched = [] + end + + def add_to_my_list(movie) + # Your code goes here + end + + def remove_from_my_list(movie) + # Your code goes here + end + + def watch(movie) + # Your code goes here + end +end + +movies = [ + Movie.new("Seven Samurai"), + Movie.new("Wall Street"), + Movie.new("Big Hero 6") +] + +account = NetflixAccount.new("user123") +account.watch(movies[0]) +account.add_to_my_list(movies[1]) +account.add_to_my_list(movies[2]) +account.remove_from_my_list(movies[2]) diff --git a/ruby/Basics/open_close.rb b/ruby/Basics/open_close.rb new file mode 100644 index 0000000..3cc3362 --- /dev/null +++ b/ruby/Basics/open_close.rb @@ -0,0 +1,84 @@ +# The Open/Closed Principle states that classes or methods should be open for +# extension, but closed for modification. This tells us we should strive for +# modular designs that make it possible for us to change the behavior of the +# system without making modifications to the classes themselves. This is +# generally achieved through the use of patterns such as the strategy pattern. + +# In the below example we can see that we’ll have to modify our file parser +# anytime we add a client that reports usage information to us in a different +# file format. This violates the Open/Closed Principle. + +class FileParser + attr_reader :file + + def initialize(file) + @file = file + end + + def parse + # If we want add new parser we must to edit this method and in private method + case file.format + when :xml + parse_xml + when :cvs + parse_cvs + # when :json + # parse_json + else + # Implementation + end + + end + + private + + def parse_xml + # Implementation + end + + def parse_cvs + # Implementation + end + + # New parse method + # def parse_json + # # Implementation + # end +end + +# Solution + +# With this refactor we’ve made it possible to add new parsers without changing any code. Any additional behavior will only require the addition of a new handler. This makes our FileParser reusable and in many cases will keep us in compliance with the Single Responsibility Principle as well by encouraging us to create smaller more focused classes. + +class FileParser + attr_reader :parser + + def initialize(parser) + @parser = parser + end + + def parse(file) + # Now if we want new parser just write new Class and pass it to method + Data.new(parser.parse file) + end +end + +class JsonParser + # We write new class for extension solution. + def self.parse(file) + # Implementation + end +end + +class XmlParser + def self.parse(file) + # Implementation + end +end + +class CvsParser + def self.parse(file) + # Implementation + end +end + diff --git a/ruby/Basics/order.rb b/ruby/Basics/order.rb new file mode 100644 index 0000000..8668d94 --- /dev/null +++ b/ruby/Basics/order.rb @@ -0,0 +1,59 @@ +require "bigdecimal" +require "yaml" + +class Item + attr_reader :name + attr_reader :price + + def initialize(name, price) + @name = name + @price = price + end +end + +class Order + @@WIDTH1 = 20 + @@WIDTH2 = 8 + @@SALES_TAX_RATE = 0.08875 + attr_reader :items + + def initialize + @items = [] + end + + def add(item) + # Your code goes here + end + + def print_receipt + @items.each do |item| + puts "#{item.name.ljust(@@WIDTH1)}" + + "#{item.price.truncate(2).to_s("F").rjust(@@WIDTH2)}" + end + puts "".ljust(@@WIDTH1 + @@WIDTH2, "=") + puts "#{"Total".ljust(@@WIDTH1)}" + + "#{base.truncate(2).to_s("F").rjust(@@WIDTH2)}" + puts "#{"Tax".ljust(@@WIDTH1)}#{tax.truncate(2).to_s("F").rjust(@@WIDTH2)}" + puts "".ljust(@@WIDTH1 + @@WIDTH2, "=") + puts "#{"Grand Total".ljust(@@WIDTH1)}" + + "#{total_cost.truncate(2).to_s("F").rjust(@@WIDTH2)}" + end + + private + def base + # Your code goes here + end + + private + def tax + # Your code goes here + end + + private + def total_cost + # Your code goes here + end +end + +order = YAML.load_file "order.yml" +order.print_receipt diff --git a/ruby/Basics/phones.rb b/ruby/Basics/phones.rb new file mode 100644 index 0000000..ece2971 --- /dev/null +++ b/ruby/Basics/phones.rb @@ -0,0 +1,30 @@ +require "date" + +class Phone + # Your code goes here +end + +phones = [ + { + :brand => "Apple", + :model => "iPhone 1st gen", + :operating_system => "iPhone OS 1.0", + :release_date => Date.new(2007, 6, 29) + }, + { + :brand => "Google", + :model => "Nexus One", + :operating_system => "Android 2.1 Eclair", + :release_date => Date.new(2010, 1, 5) + }, + { + :brand => "Samsung", + :model => "Galaxy S", + :operating_system => "Android 2.3.6 Gingerbread", + :release_date => Date.new(2010, 6, 4) + } +] + +new_phones = [] + +# Your code goes here diff --git a/ruby/Basics/rails.rb b/ruby/Basics/rails.rb new file mode 100644 index 0000000..590ed51 --- /dev/null +++ b/ruby/Basics/rails.rb @@ -0,0 +1,56 @@ +# config.threadsafe!: what does it do? +# Let’s take a look at the threadsafe! method: + +def threadsafe! + @preload_frameworks = true + @cache_classes = true + @dependency_loading = false + @allow_concurrency = true + self +end + +# Calling this method sets four options in our app configuration. Let’s walk +# through each option and talk about what it does. + +# Preloading Frameworks +# The first option @preload_frameworks does pretty much what it says, it forces +# the Rails framework to be eagerly loaded on boot. When this option is not +# enabled, framework classes are loaded lazily via autoload. In multi-threaded +# environments, the framework needs to be eagerly loaded before any threads are +# created because of thread safety issues with autoload. We know that loading +# the framework isn’t threadsafe, so the strategy is to load it all up before +# any threads are ready to handle requests. + +# Caching classes +# The @cache_classes option controls whether or not classes get reloaded. +# Remember when you’re doing “TDD” in your application? You modify a controller, +# then reload the page to “test” it and see that things changed? Ya, that’s what +# this option controls. When this option is false, as in development, your +# classes will be reloaded when they are modified. Without this option, we +# wouldn’t be able to do our “F5DD” (yes, that’s F5 Driven Development). +# In production, we know that classes aren’t going to be modified on the fly, +# so doing the work to figure out whether or not to reload classes is just +# wasting resources, so it makes sense to never reload class definitions. + +# Dependency loading +# This option, @dependency_loading controls code loading when missing constants +# are encountered. For example, a controller references the User model, but the +# User constant isn’t defined. In that case, if @dependency_loading is true, +# Rails will find the file that contains the User constant, and load that file. +# We already talked about how code loading is not thread safe, so the idea here +# is that we should load the framework, then load all user code, then disable +# dependency loading. Once dependency loading is disabled, framework code and +# app code should be loaded, and any missing constants will just raise an +# exception rather than attempt to load code. +# We justify disabling this option in production because (as was mentioned +# earlier) code loading is not threadsafe, and we expect to have all code loaded +# before any threads can handle requests. + +# Allowing concurrency +# @allow_concurrency option controls whether or not the Rack::Lock middleware +# is used in your stack. Rack::Lock wraps a mutex around your request. The idea +# being that if you have code that is not threadsafe, this mutex will prevent +# multiple threads from executing your controller code at the same time. When +# threadsafe! is set, this middleware is removed, and controller code can be +# executed in parallel. + diff --git a/ruby/Basics/single_responsibility.rb b/ruby/Basics/single_responsibility.rb new file mode 100644 index 0000000..e245c7d --- /dev/null +++ b/ruby/Basics/single_responsibility.rb @@ -0,0 +1,92 @@ +# The Single Responsibility Principle is the most abstract of the bunch. It +# helps keep classes and methods small and maintainable. In addition to keeping +# classes small and focused it also makes them easier to understand. + +# While we all agree that focusing on a single responsibility is important, it’s +# difficult to determine what a class’s responsibility is. Generally, it is said +# that anything that gives a class a reason to change can be viewed as a +# responsibility. By change I am talking about structural changes to the class +# itself (as in modifying the code in the class’s file, not the object’s +# in-memory state). +# In the below class we have a single command interface that processes +# commission payments for deals. At first glance the class seems simple enough, +# but let’s look at reasons we might want to change this class. Any change in +# how we calculate commissions would require a change to this class. We could +# introduce new commission rules or strategies that would cause our +# calculate_commission method to change. For instance, we might want to vary +# the percentage based on deal amount. Any change in the steps required to mark +# a deal as processed in the mark_deal_processed method would result in a change +# in the file as well. An example of this might be adding support for sending an +# email summary of a specific person’s commissions after marking a deal +# processed. The fact that we can identify multiple reasons to change signals a +# violation of the Single Responsibility Principle. + +class DealProcessor + attr_reader :deals + + def initialize(deals) + @deals = deals + end + + def process + deals.each do |deal| + # Here we calculate commission and create instance of Commission + Commission.create(deal: deal, amount: calculate_commission(deal)) + mark_deal_processed + end + end + + private + + def mark_deal_processed + # Implementation + end + + def calculate_commission(deal) + deal.amount * 0.05 + end +end + +class Commission + # Implementation +end + +# Solution + +class DealProcessor + attr_reader :deals + + def initialize(deals) + @deals = deals + end + + def process + deals.each do |deal| + # Now we call calculator in one operation, all logic now in it + CommissionCalculator.create_commission(deal) if mark_deal_processed + end + end + + private + + def mark_deal_processed + # Implementation + end +end + +class CommissionCalculator + def self.create_commission(deal) + Commission.new(deal: deal, amount: calculate(deal)) + end + + private + + def self.calculate(deal) + deal.amount * 0.05 + end +end + +class Commission + # Implementation +end + diff --git a/ruby/Basics/sites.rb b/ruby/Basics/sites.rb new file mode 100644 index 0000000..cdcbc63 --- /dev/null +++ b/ruby/Basics/sites.rb @@ -0,0 +1,10 @@ +require "open-uri" + +urls = [ + "https://www.reddit.com", + "https://www.facebook.com", + "https://www.spotify.com" +] + +# Your code goes here + diff --git a/ruby/Basics/towers.rb b/ruby/Basics/towers.rb new file mode 100644 index 0000000..6bf2ce8 --- /dev/null +++ b/ruby/Basics/towers.rb @@ -0,0 +1,16 @@ +# Height in meters +towers = [ + { :name => "Berliner Fernsehturm", :height => 368.0 }, + { :name => "Canton Tower", :height => 600.0 }, + { :name => "Eiffel Tower", :height => 324.0 }, + { :name => "Tokyo Tower", :height => 332.6 }, + { :name => "Stratosphere Tower", :height => 350.2 } +] + +factor = 100/2.54 # Converts centimeters to inches + +conversion = lambda do |x| + # Your code goes here +end + +# Your code goes here diff --git a/ruby/README.md b/ruby/README.md new file mode 100644 index 0000000..c9402e6 --- /dev/null +++ b/ruby/README.md @@ -0,0 +1,3 @@ +# Ruby programming language + +Ruby is an interpreted, high-level, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan. Ruby is dynamically typed and uses garbage collection. \ No newline at end of file