From 37a6470034629108c66d599aa5d65ab0e230eb28 Mon Sep 17 00:00:00 2001 From: Omar Belkady <31806568+omarbelkady@users.noreply.github.com> Date: Sun, 5 Sep 2021 13:47:30 +0100 Subject: [PATCH 01/21] Queues were mentioned twice instead of once --- MustKnow/README.md | 34 +++++++++++++++------------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/MustKnow/README.md b/MustKnow/README.md index 64e43db..e92d1da 100644 --- a/MustKnow/README.md +++ b/MustKnow/README.md @@ -73,12 +73,23 @@ 4. Queues -- Movie Theatre +- People waiting in line in the Movie Theatre +- Linear - FIFO -- aka people waiting in line +- Pushes To The End +- Pops From The Front - Ordered Collection - Operations: add(), remove() - +- Part of the java.util.* package +- Part of the collection Interface +- Two Classes Implement the Queue Interface: + - Linked List + - Priority Queue +- Supports all the methods in the Collection Interface +- Element & Remove Method Throws NoSuchElementException if the queue is empty +- Poll Method removes the head of the queue and returns it + - if the queue is empty the poll method call returns null + 5. Hash Table @@ -145,21 +156,6 @@ - -9. Queues - -- FIFO DS -- Linear -- Pushes To The End -- Pops From The Front -- Part of the java.util.* package -- Part of the collection Interface -- Two Classes Implement the Queue Interface: - - Linked List - - Priority Queue -- Supports all the methods in the Collection Interface -- Element & Remove Method Throws NoSuchElementException if the queue is empty -- Poll Method removes the head of the queue and returns it - - if the queue is empty the poll method call returns null 1. When the sample size increases of an Array what should you do? @@ -492,4 +488,4 @@ public class myclass{ //Total: O(1) + O(n) + O(n^2) ≈ O(n^2) } } -``` \ No newline at end of file +``` From a4af42c35e8778839c2c6049674d3c24528ca5c0 Mon Sep 17 00:00:00 2001 From: Omar Belkady <31806568+omarbelkady@users.noreply.github.com> Date: Wed, 8 Sep 2021 14:06:22 +0000 Subject: [PATCH 02/21] Encapsulation Concept is now fully complete --- Encapsulation/README.md | 83 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Encapsulation/README.md diff --git a/Encapsulation/README.md b/Encapsulation/README.md new file mode 100644 index 0000000..0d55687 --- /dev/null +++ b/Encapsulation/README.md @@ -0,0 +1,83 @@ +### Encapsulation + +- One of the 4 pillars of OOP(A,E,I,P): +- I have 3 elements: + - Class + - Method + - Variables +- I wrap the variables and the code implementation which interacts with the methods as one +- Variables within my class cannot be accessed by other classes +- Only the methods of that particular class can access them +- All in all, it is the process by which I group information + + +#### Good Practice + +- Class Variables should always be declared private +- Setter and Getter Methods should be public + + +#### Example Encapsulating Class + +```java +public class EncapsulatingThis{ + + + + private String myFullName; + private String myIdentifNum; + private int myAge; + + + + public int getMyAge(){ + return myAge; + } + + public void setMyAge(int theAge){ + myAge = theAge; + } + + public String getMyId(){ + return myIdentifNum; + } + + public void setMyId(String myNewId){ + myIdentifNum = myNewId; + } + + + public String getMyName(){ + return myFullName; + } + + public void setMyName(String fullName){ + myFullName = fullName; + } + + //overriding the toString() method + @Override + public String toString() + { + return ("Hi my Name is: " + getMyName() + " and I am " + getMyAge() + " and my ID is: " + getMyId()); + } + +} +``` + + +#### Main Class + +```java +import java.util.*; +public class RunnerClass{ + public static void main(String [] args){ + EncapsulatingThis encapsObj = new EncapsulatingThis(); + encapsObj.setMyName("Omar"); + encapsObj.setMyAge(27); + encapsObj.setMyId("165X70B15D"); + + System.out.println(encapsObj.toString()); + } +} +``` \ No newline at end of file From 2ea09fd929e447aebacde36715a25048565ef054 Mon Sep 17 00:00:00 2001 From: Omar Belkady <31806568+omarbelkady@users.noreply.github.com> Date: Fri, 10 Sep 2021 11:48:04 +0000 Subject: [PATCH 03/21] Maven And Fibonacci Stuff --- Dynamic_Pro/{ => Fibonacci}/Fib.class | Bin Dynamic_Pro/{ => Fibonacci}/Fib.java | 0 Dynamic_Pro/README.md | 46 ++++ Maven/README.md | 301 ++++++++++++++++++++++++++ MustKnow/README.md | 58 ++++- 5 files changed, 399 insertions(+), 6 deletions(-) rename Dynamic_Pro/{ => Fibonacci}/Fib.class (100%) rename Dynamic_Pro/{ => Fibonacci}/Fib.java (100%) create mode 100644 Maven/README.md diff --git a/Dynamic_Pro/Fib.class b/Dynamic_Pro/Fibonacci/Fib.class similarity index 100% rename from Dynamic_Pro/Fib.class rename to Dynamic_Pro/Fibonacci/Fib.class diff --git a/Dynamic_Pro/Fib.java b/Dynamic_Pro/Fibonacci/Fib.java similarity index 100% rename from Dynamic_Pro/Fib.java rename to Dynamic_Pro/Fibonacci/Fib.java diff --git a/Dynamic_Pro/README.md b/Dynamic_Pro/README.md index 423adf3..db9496e 100644 --- a/Dynamic_Pro/README.md +++ b/Dynamic_Pro/README.md @@ -1 +1,47 @@ ### Dynamic Programming + + + +#### Fibonacci Algorithm + +- A Tree like data structure +- Any computation I made within the tree that I plug into the formula ... +- I shouldn't have to compute again thanks to memoization it stores the value +- in an object and spits it out whenever there is a call to it +- I store the answer within the memo and caches that result +- My key is the nth number in the fibonacci sequence +- My value is the value i.e. output +- When making recursive calls, thanks to memoization, it outputs a stored value + - and doesn't have to travel through any further subtrees +- So memoizing my fib function ends up reducing the number of recursive calls I make + +##### Runtime Complexity + +- Memoizing my algo I see a linear functional call pattern +- i.e. I have n node and that's why the runtime complexity is O(n) +- where n is the top level call + +##### Space Time Complexity + +- O(n) + + +#### Grid Traveler + +- You want to travel +- You start at the top left corner and your goal is to end in the bottom right corner +- You can only go down or to the right +- You CANNOT move up or left or diagonally +- Find the # of different ways you can travel +- gridTravelTo(2,3) means how many different ways you can travel +- ...from the top left to bottom right in a 2x3(2 rows by 3 columns) + - 3 dif ways: + - right, right, down + - right,down, right, + - down, right, right +- gridTravelTo(1) means do nothing because you are already there +- gridTravelTo(0,1) means 0 rows and 1 column i.e. the grid is empty +- gridTravelTo(1,0) means 1 row and 0 columns i.e. the grid is empty +- gridTravelTo(8,0) means 8 rows and 0 columns i.e. the grid is empty +- gridTravelTo(0,0) means 0 rows and 0 columns i.e. the grid is empty +- base case: if one of your dimensions is empty then there is no grid diff --git a/Maven/README.md b/Maven/README.md new file mode 100644 index 0000000..9f232f8 --- /dev/null +++ b/Maven/README.md @@ -0,0 +1,301 @@ +## Maven + +- PM tool for JVM Languages + +- Used To Perform Major Tasks: + - Build Your Source Code + + - Testing Your Code + + - Packaging Your Code(JAR, WAR, EAR) + + - Generate Java docs + + - Dependency Management + + - Handling, Versioning Your Artifacts + + +### How To Install: + + - Head over to: https://maven.apache.org/download.cgi + - Download the Binary Zip Archive + - Extract It + +### 2- Create an environment variable in your system name it M2_HOME + + - This is where Other SW and libraries look for the Maven Installation + - Give it a path in the bin folder + +### Checking if the installation is successful + +```bash +mvn --version +``` + +### File Structure + +``` +├── /my-project-demo + ├── /.idea + ├── /src + ├── /main + ├── /java + └── /resources + ├── /test + └── /java + ├── /target + └── pom.xml +├── /External Libraries +└── /Scratches and Consoles +``` + +- All the static files go in our resources folder +- e.g. Property Files, or any file we need to read from(xml, csv,html, css, js) +- test file I store all my unit tests and integration tests +- pom.xml holds all the metadata of my Application i.e. project dependencies +- target folder holds all the java compiled class files + + +### Creating A Project + + - Give it an artifact id(this is usually the name of your project) e.g. my-project-demo + - Give it group Id(this is usually the name of your company id in reverse order i.e. com.herokuapp.omarbelkady) + - Give it a version number e.g. 1.0-SNAPSHOT + + +### 3rd Party JAR files i.e. Dependencies + +- External Libraries are called "dependencies" +- Maven provides me with functionality on how to manage my dependencies +- ...thanks to the pom.xml file + + +### Life Without Maven + +- I have to manually download the JAR files from the internet +- then I add them one by one + + +### Dependency Section Thanks To Maven + +- Maven provides me with a dependency section where I can specify the info of the JAR I require in my project + - artifactid + - groupid + - version +- Maven will then automatically download these dependency specified, from the internet and load them into my project +- Load each dependency in a "dependency" tag +- And all your depenency tags should be in between 1 dependencies tag + +< dependencies > + < dependencyA > + + < /dependencyA > + + < dependencyB > + + < /dependencyB > +< dependencies > + +- To add a dependency go to https://www.mvnrepository.com/ + + +- Click on the Maven Icon to force IntelliJ to download the dependencies you have specified + + +### Transitive Dependencies + +- Dependencies of my dependencies + + +``` +├── /my-project-demo + ├── /.idea + ├── /src + ├── /main + ├── /java + └── /resources + ├── /test + └── /java + ├── /target + └── pom.xml +├── /External Libraries +└── /Scratches_and_Consoles +``` + +- All the static files go in our resources folder +- e.g. Property Files, or any file we need to read from(xml, csv,html, css, js) +- test file I store all my unit tests and integration tests +- pom.xml holds all the metadata of my Application i.e. project dependencies +- target folder holds all the java compiled class files + +### Maven Dependency +- Can be categorized into two categories: + - Snapshot Dependency + - This dependency was created when the software was in active development + - Unstable + - Release Dependency: + - This dependency was created after the software was developed and is ready to be released i.e. ready to be deployed for production + - Stable + +- In all, when I am developing the software I use the snapshot versions for the dependencies. When the software is released, I use the release versions + +--- +### Dependency Scopes + +- enables me to control the visibility of a Maven depenendency +- 4 types: +1. **Compile**: made available at compile time within classpath [default scope] +2. **Provided**: dependency provided at runtime by JDK or webserver, e.g. Servlet API dependency. The web server which is running my project provides me with the java servlet-api during runtime. This means that the dependency will be available in the class path of the project but will not be packaged in the JAR file nor the WAR file +3. **Runtime**: dependency provided ONLY at runtime and NOT at compile time e.g. MySQL JDBC connector dependency. I mark the dependency as runtime to make sure I do not use the MySQL JDBC classes in my code instead of standard jdbc api +4. **Tests**: dependency only available at the time of writing and running my unit tests e.g. junit, spring-boot-starter-test +5. **System**: the path to the JAR should be specified manually using the < systemPath > tag. The only restriction is that I must specify the exact path of where to locate this dependency within my system. + +### Repositories +- a special directory called a **repository** is the location where Maven stores my dependencies +- Local Repository[directory/folder in your machine] +- Remote Repository[Maven Website] where I can download the Maven dependencies +- If a dependency I specified in my pom is not in my local repository it goes ahead and connects to the remote repository and downloads the remote repository and stores the dependency within my local repository + +##### How To Define A Repository within my POM always after my closing dependency tag +```xml + + + my-internal-website + https://myserver/repo + + +``` + + +### Build Lifecycle Within Maven + +- How Does Maven Build Our Projects? + 1. default + 2. clean + 3. site + +#### Default Lifecycle Build Step Phases +1. validate + - Makes sure pom.xml is validated or not validated +2. compile + - Compiles my source code +3. test + - Runs the unit tests in my project +4. package + - Packages the source code into an artifact +5. integration-test + - Executes the integration tests +6. verify + - Verifies the results of the integrations tests +7. install + - Installs the newly created package files(JAR or any other artifact) within my local repository + - Maven +8. deploy + - Deploy the newly created package to the remote repository + - If the newly created package is configured in the pom.xml file it will deploy the new package into the remote repository + + +### Command +```java +mvn clean install +``` + +- This command compiles the source code +- Runs the unit tests +- Creates the JAR file +- Install the JAR file into your local repository + +### Site Step + +- generate Java documentation that is present in my project + + +### Plugins and Goals + +- To be able to execute the different lifecyle phases, Maven provides me with different plugins in order for me to perform each task in the lifecycle +- Every plugin has a relationship to a goal which is linked to the lifecycle phase(e.g. compile) +- To declare a plugin simple place in between a **plugin** tag that is within the **plugins** tag +- Any plugin I want to define must be within the build tag +- The build tag will usually be right below the dependencies section + +```xml + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + + +``` + +- The plugin above is in charge of compiling any test files or source files I have within my project. This is familiar to running +```java +javac nameofclass.java +``` + + +#### To trigger the compile lifecycle phase +```java +mvn compiler:compile +``` + +### Maven tab⇒ Plugin section ⇒ Hit Expand ⇒ Click on Compile Goal + +- Compilation fails +- Java compiler of Maven within IntelliJ is configured to Java version 1.X +- To fix: +      0. Go to your pom.xml +      1. Head to build section +      2. Plugins ⇒ plugin +      3. Configuration Tag +      4. Change the source & target properties to the java version installed on your machine + +### Maven Install Plugin + +- This plugin is used to run the install lifecycle phase within the maven build lifecycle +1. Compiles My Source Code +2. Runs Our Unit Tests +3. Package The Cource Code into an Artifact +4. Installs The Artifact Within My Local Repository + + +### Maven Deploy Plugin + +- Self-explanatory plugin +- runs all the phases which are part of the install phase +- deploys the created artifact to the remote repository +0. To deploy the artifact to the remote repo you have to specify the remote repo details within your pom +1. Create a tag right above your dependencies tag and give it a name of **distributionManagement** +2. Within the distributionManagement tag create a tag named **repository** and place the information of your repository there +3. To uniquely identify a repository I specify the **id**, **name** and **url** +4. Run the command below to deploy your plugin + +```java +mvn clean deploy +``` + +### Maven Profiles + +- Profiles can be used within maven to create customized build configurations within my project +- I can customize the behavior of a build based upon specific conditions +- e.g. I can skip the test execution due to the fact that my build process may take a long time +- I create a profile that will skip the test execution phase + +##### How To Create + +- Right below your build tag create a **profiles** tag + +- Within your profiles tag create a **profile** tag I give it an: + - *id* + - *properties* + +- After creating a profile for the above example Maven will make sure to skip the test execution + +- I head over to the terminal and run the following command: +- -P flag indicates the id of the profile +```java +mvn -Pskip-tests clean install +``` \ No newline at end of file diff --git a/MustKnow/README.md b/MustKnow/README.md index e92d1da..501a14d 100644 --- a/MustKnow/README.md +++ b/MustKnow/README.md @@ -51,6 +51,8 @@ - LIFO/FILO - Dinner Plates - When items are pushed they are placed on the top +- Only can push/pop an element from this DS at one end only +- Requires You To Have One Reference Pointer i.e. "TOP" 2. Linked List @@ -76,8 +78,9 @@ - People waiting in line in the Movie Theatre - Linear - FIFO -- Pushes To The End -- Pops From The Front +- Has Side A and Side B +- Pushes On Side A i.e. Enqueue +- Pops On Side B i.e. Dequeue - Ordered Collection - Operations: add(), remove() - Part of the java.util.* package @@ -89,6 +92,7 @@ - Element & Remove Method Throws NoSuchElementException if the queue is empty - Poll Method removes the head of the queue and returns it - if the queue is empty the poll method call returns null +- Requires You To Have Two Reference Pointers i.e. "FRONT" & "REAR" @@ -100,6 +104,7 @@ - Cannot store null as a key nor as a value - First parameter within your Hash Table declaration is the data type of the key - Second parameter within your Hash Table declaration is the data type of the value +- Restaurant Pager i.e. you give your name and they assign a number to you when a seat frees up you get an empty table 6. Trees @@ -127,19 +132,22 @@ - no duplicate vals - val on the left most subtree of the node is always smaller than the val on its immediate right - Node on the left is always less than the node on the right +- Linux File Structure +- Classification Tree in Biology 7. Heap - Special Tree Based DS - Binary Tree -- Patients Being Admitted to the Hospital - - Patients with life-threatning situation get taken care of first - - Patients that don't have threatening situation wait in line - Parent node makes a comparison with its child nodes and are arranged accordingly - Two Scenarios: - Key present at the root node is the greatest among all of its children and successors - Key present at the root node is the smallest among all of its children and successors +- Patients Being Admitted to the Hospital + - Patients with life-threatning situation get taken care of first + - Patients that don't have threatening situation wait in line + 8. Graphs @@ -153,7 +161,7 @@ - Undirected - Simple Graph: Each edge connects to two different vertices whereby no two edges connect to the same group of vertices - Multigraph: An edge can connect to the same pair of vertices -- +- Google Maps Usage of Connecting Roads i.e. vertex therefore, I use an algo to determine the shortest path between vertex A & B @@ -209,6 +217,44 @@ But actually the runtime is O(n) because when we calculate runtime we drop the c - In the worst case scenario, if the number I am looking for is at the end of the array then I have to inspect one index at a time - The more items I have the longer the operation will take +```java +import java.util.*; + +public class LinSearch{ + + public static void main(String [] args){ + int [] myArr = {18, 34, 65, 92, 32, 94, 15, 10, 16, 8, 26}; + int elem,elemExistsTimes=0; + Scanner sc = new Scanner(System.in); + System.out.println("Enter The Element You Are Hunting For: "); + elem = sc.nextInt(); + + for(int x = 0; x<10; x++){ + if(myArr[x] == elem){ + elemExistsTimes= x + 1; + break; + } + + else{ + elemExistsTimes = 0; + } + } + + if(elemExistsTimes != 0) + { + System.out.println("I found the item at location: "+elemExistsTimes); + } + + else{ + System.out.println("Not Found Man"); + } + + } + +} +``` + + ### Example: Binary Search 1. We start by searching in the middle of the array. Is the item in the middle smaller or bigger than the elem I am searching for? From 07fb66f53565618242376d3f95be1c0ab4006fbf Mon Sep 17 00:00:00 2001 From: Omar Belkady <31806568+omarbelkady@users.noreply.github.com> Date: Thu, 16 Sep 2021 10:41:44 +0000 Subject: [PATCH 04/21] Different types of Algorithms --- MustKnow/AlgoTypes/README.md | 33 +++++++++++++++++++++++++++++++++ MustKnow/README.md | 15 +++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 MustKnow/AlgoTypes/README.md diff --git a/MustKnow/AlgoTypes/README.md b/MustKnow/AlgoTypes/README.md new file mode 100644 index 0000000..b2bc520 --- /dev/null +++ b/MustKnow/AlgoTypes/README.md @@ -0,0 +1,33 @@ +## Types of Algorithms + +- Backtracking Algorithm + - recursive problem solving approach + - I come up with N number of solution + - If the first solution does not solve my problem I go back + - I try the second solution and so forth + - I remove the first solution + - Playing soduku you find 4 is in the row, column and box therefore you backtrack and check 5 + - Trying to find your way out in a maze + +- Brute Force Algorithm + - Check every possible solution for the problem to be solved + +- Divide And Conquer Algorithm + - Divide the problem into sub-problems and solve each sub-problem independently + - i.e. Binary Search + +- Dynamic Programming Algorithm + - function X generates the output Y + - I store the result of Y and use it in function D + +- Greedy Algorithm + - Always chooses the best solution + - Solution is built piece by piece + - The subsequent piece chosen by the algorithm is usually the most obvious + - Examples in Various DS: + +- Recursive Algorithm + - an algorithm which calls itself + - i.e. factorial + + diff --git a/MustKnow/README.md b/MustKnow/README.md index 501a14d..e4b2533 100644 --- a/MustKnow/README.md +++ b/MustKnow/README.md @@ -53,6 +53,13 @@ - When items are pushed they are placed on the top - Only can push/pop an element from this DS at one end only - Requires You To Have One Reference Pointer i.e. "TOP" +- Applications: + - Redoing/Undoing stuff within your application + - Memory Management +- Allows you to fully control how memory is allocated and deallocated +- Pitfalls of Stack: + - Cannot access a random element + - Not able to be scaled i.e. not flexible 2. Linked List @@ -131,6 +138,14 @@ - Arranged in some order - no duplicate vals - val on the left most subtree of the node is always smaller than the val on its immediate right + - Btree + - every btree has an order i.e. the number of levels + - A leaf in a btree the i.e. the parent to the last level in a btree(i.e. child nodes) + - ...must always have more nodes than the child so as the keys(1 key... 2 child nodes, 2 keys, 3 child nodes) + - the keys cannot be larger than the leaf nodes + - All leaf nodes are at the same level + - whenever one of the rules is violated, i have to rebalance and restructure my tree + - Root node must have a minimum of two children - Node on the left is always less than the node on the right - Linux File Structure - Classification Tree in Biology From 2fca4a7a74e87facfb0bc5e9932084425afebf43 Mon Sep 17 00:00:00 2001 From: Omar Belkady <31806568+omarbelkady@users.noreply.github.com> Date: Thu, 16 Sep 2021 19:52:20 +0000 Subject: [PATCH 05/21] More Info about the most important DS and implementations of each DS --- MustKnow/Main.java | 30 ------ MustKnow/README.md | 221 +++++++++++++++++++++++++++++++-------------- 2 files changed, 151 insertions(+), 100 deletions(-) delete mode 100644 MustKnow/Main.java diff --git a/MustKnow/Main.java b/MustKnow/Main.java deleted file mode 100644 index 8b15607..0000000 --- a/MustKnow/Main.java +++ /dev/null @@ -1,30 +0,0 @@ -public class Main{ - - public void logLn(Object o){ - System.out.println(o); - } - - public void log(Object o){ - System.out.print(o); - } - - public void printArr(int [] arr){ - logLn(arr[0]); //has one operation and takes constant time to run ===> O(1) - logLn(arr[0]); //has two operation but still O(1) - } - - /* - small small will run fast but as the sample size increase e.g. 1,000,000 items then you will have it running slowly - - cost of algo: linear and is directly proportional to the size of the input therefore the runtime complexity O(n) - */ - public void logging(int [] nums){ - for(int i=0; i myStack= new Stack(); +``` + + 2. Linked List - Sequential Order @@ -71,6 +78,17 @@ - A Node is composed of data and a pointer - Last node has a null pointer i.e. the pointer is used but doesn't point to anything - Folders on your computer(i.e. last folder is null because it has no folder within it) +- Node[0] = Head +- Node[n-1] = Tail + + +```java +import java.util.*; +/* +How To Declare: +LinkedListnameOfLL = new LinkedList() */ +LinkedList mylist=new LinkedList(); +``` 3. Array @@ -79,8 +97,62 @@ - All the elements in the DS must be of the same type - Muffin/Egg Tray - Rectangular in shape +- Good For Storing Multiple items in it +- Address in Memory increases by the size of the datatype you store +- I.e. say I have 6 ints location in memory of the first is 104 second is 108 third is 112 +- because an int = 4 bytes that's why you increment by 4 +- Searching an Array by index is super fast, supply to an idx to the array and it will be super fast to locate it +- Calc of Mem Address Runtime is: O(1) +- Downsides: Static, failure to know size if too large: waste memory too small: array gets filled quickly +- And If I fill it up quickly I must create a 2nd array and copy the elements of the first array into the second + +- Cost of Lookup: O(1) +- Cost of Insertion: O(n) +- Cost Of Removal: O(n) + +1. Best Case: I remove from the end of the array and I delete that index +2. Worst Case: I remove from the beginning of the array and shift all the items in the right one index less to fill +3. Therefore, for the worst case it is O(n) when removing an item in the array + -4. Queues +- Dynamic Array DS in Java: ArrayList +- Grows by 50% of its size everytime I add sth to it +- synchronous aka one 7652626 thread at a time + +#### Declaring an array in Java +```java +import java.util.*; +public class Arr{ + public static void main(String [] args){ + /* + 1. declare the data type of the array + 2. indicate that I want an array data structure by using the brackets.. MUST BE EMPtY + 3. give it a name + 4. use the new operator to allocate memory for the array + 5. repeat the data type of the array + 6. indicate the size of the array + + */ + int [] myArr = new int[7]; + //this output the memory location of the array + //System.out.println(myArr); + + /* + if you know the vals: + + */ + int [] myArrTw = {7, 6, 5, 2, 6, 2, 6} + + //proper way to output + System.out.println(Arrays.toString(myArr)) + } +} +``` + +4. Vector: Grows by 100% of its size everytime I add sth to it... asynchronous aka multiple threads at a time + + +5. Queues - People waiting in line in the Movie Theatre - Linear @@ -101,7 +173,17 @@ - if the queue is empty the poll method call returns null - Requires You To Have Two Reference Pointers i.e. "FRONT" & "REAR" +```java +//How To Declare a Priority Queue of type String +import java.util.*; + +public class queueimpl{ + public static void main(String [] args){ + Queue mypq = new PriorityQueue<>(); + } +} +``` 5. Hash Table @@ -113,6 +195,39 @@ - Second parameter within your Hash Table declaration is the data type of the value - Restaurant Pager i.e. you give your name and they assign a number to you when a seat frees up you get an empty table +```java +/* +How To Declare a Hash Table of type: +- Integer for the key +- String for the value +*/ + +import java.util.*; + +public class HashTable{ + public static void main(String [] args){ + Integer mystr; + Hashtable myhashtable = new Hashtable(); + myhashtable.put(1,"Blue"); + myhashtable.put(2,"Red"); + myhashtable.put(3,"Yellow"); + + //Storage of the keys in the HashTable Set + Set keys = myhashtable.keySet(); + + Iterator itr = keys.iterator(); + + + while (itr.hasNext()) { + // Getting Key + mystr = itr.next(); + System.out.println("Key: "+mystr+"\nValue: "+myhashtable.get(mystr)); + } + } +} + +``` + 6. Trees - Hierarchical Structure where data is org in a hierarchy and everything is linked together @@ -146,6 +261,7 @@ - All leaf nodes are at the same level - whenever one of the rules is violated, i have to rebalance and restructure my tree - Root node must have a minimum of two children + - Node on the left is always less than the node on the right - Linux File Structure - Classification Tree in Biology @@ -269,6 +385,40 @@ public class LinSearch{ } ``` +```java +public class Main{ + + public void logLn(Object o){ + System.out.println(o); + } + + public void log(Object o){ + System.out.print(o); + } + + public void printArr(int [] arr){ + logLn(arr[0]); //has one operation and takes constant time to run ===> O(1) + logLn(arr[0]); //has two operation but still O(1) + } + + /* + small small will run fast but as the sample size increase e.g. 1,000,000 items then you will have it running slowly + + cost of algo: linear and is directly proportional to the size of the input therefore the runtime complexity O(n) + */ + public void logging(int [] nums){ + for(int i=0; i; -//where E is the generic key type -//Integer keyword is the wrapper class around the native/primitive type int -``` -2. Vector: Grows by 100% of its size everytime I add sth to it... asynchronous aka multiple threads at a time - - -### LinkedList - -- We use a LL when wanting to store an object in sequential||7652626 order -- LinkedList are better than arrays because they can grow/shrink auto -- It consists of a group of nodes in seq order. Every node has two pieces of data: - 1. value - 2. address of the next node in the list -- AKA every node (points to)/references the next node in the list -- Node[0] = Head -- Node[n-1] = Tail #### Searching A LL value Time C From d766cd87ba4f0d8f5321de23f16bcd2935e37471 Mon Sep 17 00:00:00 2001 From: Omar Belkady <31806568+omarbelkady@users.noreply.github.com> Date: Fri, 17 Sep 2021 12:20:32 +0000 Subject: [PATCH 06/21] Btree, B* tree and AVL tree info --- MustKnow/README.md | 180 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 171 insertions(+), 9 deletions(-) diff --git a/MustKnow/README.md b/MustKnow/README.md index 4e69088..10b8084 100644 --- a/MustKnow/README.md +++ b/MustKnow/README.md @@ -232,12 +232,13 @@ public class HashTable{ - Hierarchical Structure where data is org in a hierarchy and everything is linked together - Not the same as linked list because LL is linear +- Log(n) runtime complexity where n is the number of levels - Trees are faster to access than a LL because they are non-linear - Node: person who holds our data - Child Node: person who has a parent - Leaf Node: person who has no children - Edge: person who connects two nodes -- Root: Person who is the topmost node +- Root: person who is the topmost node - Node Height: # of edges from the node to the deepest leaf node - Node Depth: # of edges from the root to the node - Tree Height: Depth of the deepest node @@ -245,27 +246,188 @@ public class HashTable{ - Leaves: Person who has no children - Use when you want to store items in a hierarchial fashion - Quicker to access/search than a LL but slower than an Array - - Binary Tree + - AVL Tree: + - Self-balanced trees + - Searching, Inserting, Deleting in the worst case is logarithmic time complexity + - Balance factor is determined by the height of the right subtree tree + - ... minus the height of the left subtree + - I have a height of 1 in the left subtree ... I have a height of 1 in the right subtree + - balance factor = 0 + - Objective: make sure every node is balanced i.e. bf = -1,0,1 + - all nodes must be balanced ... if one node is not balanced the whole tree is unbalanced + - balance factor in relation to its neighboring subtree + - -1 means the right subtree is greater than the left subtree + - 1 means the left subtree is greater than the right subtree + - 0 means the left subtree and right subtree have equal lengths + - LL rotation means I inserted a node in the left subtree of the left subtree of A + - LR rotation means I inserted a node in the right subtree of the left subtree of A + - RR rotation means I inserted a node in the right subtree of the right subtree of A + - RL rotation means I inserted a node in the left subtree of the right subtree of A + - Binary Tree - Can Have 0,1,2 nodes + - right child is always larger & left child is always smaller - Binary Search Tree: - Used for sorting, getting and searching data - Non-linear - Arranged in some order - no duplicate vals - val on the left most subtree of the node is always smaller than the val on its immediate right - - Btree - - every btree has an order i.e. the number of levels - - A leaf in a btree the i.e. the parent to the last level in a btree(i.e. child nodes) + - B-tree + - every b-tree has an order i.e. the number of levels + - Root node must have a minimum of two children + - A leaf in a b-tree the i.e. the parent to the last level in a b-tree(i.e. child nodes) - ...must always have more nodes than the child so as the keys(1 key... 2 child nodes, 2 keys, 3 child nodes) - the keys cannot be larger than the leaf nodes - - All leaf nodes are at the same level - - whenever one of the rules is violated, i have to rebalance and restructure my tree - - Root node must have a minimum of two children - + - All leaf nodes must be at the same level + - whenever you delete a leaf node all you have to do is do a rotation to the values + - if you delete a middle value you must do rebalancing + - whenever one of the rules is violated, I have to rebalance and restructure my tree + - ... by shifting the center value + - once you access one element in the block you have access to all the elements in the block + - B*-tree + - Values in the middle are not essentially referred to as value + - they are just navigation values(go left, go down, go right) + - the parent is always the largest value of its left child subtree + - the number of values I am allowed to store at the leaf level is determined by a parameter k* + - so if k* = 2 that means I am allowed to have a max of 2k* elements at the leaf level + - ...and a minimum of 2 + - m is the order of the tree i.e. the number of the levels + - B* trees have a smaller height than Btrees because all the data is stored in the leaf level - Node on the left is always less than the node on the right - Linux File Structure - Classification Tree in Biology +- Runtime of Operations Performed on A Balanced Tree + +| Operation | Runtime | +| ----------- | ----------- | +| Inserting | log(n) | +| Deleting | log(n) | +| Rebalancing | log(n) | +| Searching | log(n) | +#### 4 Cases of AVL Trees of Balance Factors + +- We will never have to make more rotations than the number of levels +- Number of level is log2(n) + +##### Case A +``` + A(-2) + / \ + B(-1) C(0) height of 3 vs height of 1 + / \ ∴ BF=-2 + D(-1) E(0) + / +F(0) +``` + +- Balance Factor of: -2 +- The left most subtree has a height that is 2 levels greater than the right subtree +- Perform a single right rotation + +``` + B(0) + / \ + D(0) A(0) + / / \ + F(0) E(0) C(0) + +``` +
+
+ + +##### Case B +``` + A(-2) + / \ + B(1) C(0) + / \ +D(0) E(1) + \ + F(0) +``` +
+
+ +- Perform a single left rotation on the subtree +- Make E the root node of the left subtree +- Make B the left child node of E +- Make F the right child node of E +``` + A(-2) + / \ + E C(0) + / \ + B F + / + D +``` + + + + +##### Case C + +``` + A(-2) + / \ + B(1) C(0) + / \ + D(0) E(1) + \ + F(0) +``` + +- Perform a single left rotation +- Make A the root node of the left subtree +- Make E the root node of the right subtree +- Make F the child node of E +- Make B the left child node of A +- Make D the right child node of A + +``` + C(0) + / \ + A(0) E(1) + / \ \ +B(0) D(0) F(0) + +``` + + + + +##### Case D + +``` + A + / \ + B C + / \ + D E + / + F +``` + +1. Perform a single right rotation now we are in Case C +2. That means To Solve Case D I perform a double right-left rotation + +``` + A + / \ + B D + / \ + F C + \ + E +``` + + + + + + 7. Heap From 87ae3ced315a0da054dfb7825b12d05788f81d96 Mon Sep 17 00:00:00 2001 From: Omar Belkady <31806568+omarbelkady@users.noreply.github.com> Date: Wed, 22 Sep 2021 11:56:28 +0000 Subject: [PATCH 07/21] More Did Some Fixing To Interfaces README, more info about Maps, Maven, and Most Used DS in Java --- Interfaces/README.md | 28 ++++-- Maps/README.md | 202 +++++++++++++++++++++++++++---------------- Maven/README.md | 73 +++++++++------- MustKnow/README.md | 7 +- README.md | 3 +- 5 files changed, 197 insertions(+), 116 deletions(-) diff --git a/Interfaces/README.md b/Interfaces/README.md index 38bad94..b6e0cd5 100644 --- a/Interfaces/README.md +++ b/Interfaces/README.md @@ -1,8 +1,20 @@ -Interfaces are a little bit similar in concept to Inheritance. An interface defines behavior. So we have an object and right after it is a biiiig barrier, -this barrier is the interface. The barrier serves as to limit on how we interact with the object. We use an interface to work with an object. -When we program we tell the class that the object has to meet the requirements imposed by interface. Say I have a class Dog. The dog has the following behaviors -which are: walk(), woof(), eat(). We can define the behaviors thanks to interfaces. All in all, interfaces define behavior/characteristics that -classes need to implement. We can define how an animal eats/walks within the interface. Then the class can implement the interface. -A class does not extend an interface, it implements it. Whenever we work with multiple classes as a team of developer. We must believe that every developer will do -their part to implements the works of the interface of the designated class they are working on. Say for example, a class that implements the interface -walking well then we can trust that class that it can walk properly and not limp. An interface can extend interfaces but cannot extend/implement the class. +### Interfaces + +
+ +- Similar in concept to Inheritance. +- defines behavior. So we have an object and right after it is a biiiig barrier, this barrier is the interface +- The barrier serves as to limit on how we interact with the object. We use an interface to work with an object. + +- I tell the class that the object has to meet the requirements imposed by interface. Say I have a class Dog. The dog has the following behaviors which are: + - walk() + - woof() + - eat() +- We can define the behaviors thanks to interfaces. All in all, interfaces define behavior/characteristics that classes need to implement. +- We can define how an animal eats/walks within the interface. Then the class can implement the interface. + +- A class does not extend an interface, it implements it. Whenever we work with multiple classes as a team of developer. We must believe that every developer will do their part to implements the works of the interface of the designated class they are working on. + +- Say for example, a class that implements the interface walking well then we can trust that class that it can walk properly and not limp. + +- An interface can extend interfaces but cannot extend/implement the class. \ No newline at end of file diff --git a/Maps/README.md b/Maps/README.md index c9beb03..c80f71e 100644 --- a/Maps/README.md +++ b/Maps/README.md @@ -1,89 +1,145 @@ -### A map is an object that maps keys and values -### A map cannot contain the same keys -### A map is similar to a dictionary in Python and a Key-Value pair in JS -### Each key must be unique within a map -### Maps are very important to know when dealing with Abstraction in OOP -### Java has three types of maps: HashMap , TreeMap and and LinkedHashMap + +## Maps + + + +- A map is an object that maps keys and values + +- Cannot contain the same keys + +- similar to a dictionary in Python and a Key-Value pair in JS + +- Keys must be unique within a map + +- Maps are very important to know when dealing with Abstraction in OOP + + + +### Java has three types of maps: HashMap , TreeMap and and LinkedHashMap + + + ### Ordering: - 1- HashMap:Key Order - 2- TreeMap: Key Order - 3- LinkedHasMap: Reverse Insertion Order FIFO - -### HashMap: - ``` - Key Order - ``` + + + +
+ +1. HashMap + +- Check if Empty: isEmpty() +- Remove a particular key: .remove() +- Does Not Maintain Insertion Order +- Holds A Value Depending on A Key +- Only Holds Unique Elements +- Lookup & Insertion: O(1) +- Only allowed to store 1 Null Key +- Allowed to store multiple null values + +2. TreeMap + +- Key Order +- Only Holds Unique Elements +- Lookup & Insertion: O(log(n)) +- Cannot Store Null as a key +- Allowed to store multiple null values +- Maintains Ascending Orders + +3. LinkedHasMap: + +- Only Holds Unique Elements +- Allowed to store only one null key +- Allowed to store multiple null values. +- Maintains Insertion Order +- FIFO + + + ```java + import java.util.*; -public class HashMap +public class HashMap { - public static void main(String args[]) - { - //HashMap Declaration - //HashMap
nameOfHashMap= new HashMap
(); - HashMap myHashMap=new HashMap();//Creating HashMap. - - myHashMap.put(2,"Papaya"); //Putting elements in Map. - myHashMap.put(3,"Mango"); - myHashMap.put(1,"Apple"); - myHashMap.put(4,"Lemon"); - - System.out.println(myHashMap); - } - - //Output: {1=Apple, 2=Papaya, 3=Mango, 4=Lemon} meaning Key Order + public static void main(String args[]) + { + //HashMap Declaration + //HashMap
nameOfHashMap= new HashMap
(); + + HashMap myHashMap=new HashMap();//Creating HashMap. + + myHashMap.put(2,"Papaya"); //Putting elements in Map. + + myHashMap.put(3,"Mango"); + + myHashMap.put(1,"Apple"); + + myHashMap.put(4,"Lemon"); + + System.out.println(myHashMap); + } + +//Output: {1=Apple, 2=Papaya, 3=Mango, 4=Lemon} meaning Key Order } + ``` + ### TreeMap + + ```java import java.util.*; -public class Main + +public class Main { - public static void main(String args[]) - { - //Tree Declaration - //TreeMap
nameOfTreeMap= new HashMap
(); - TreeMap myTreeMap=new TreeMap();//Creating HashMap. - - myTreeMap.put(2,"Papaya"); //Putting elements in Map. - myTreeMap.put(3,"Mango"); - myTreeMap.put(1,"Apple"); - myTreeMap.put(4,"Lemon"); - - System.out.println(myTreeMap); - } - - //Output: {1=Apple, 2=Papaya, 3=Mango, 4=Lemon} - //meaning Key Order + public static void main(String args[]) + { + //Tree Declaration + + //TreeMap
nameOfTreeMap= new HashMap
(); + + TreeMap myTreeMap=new TreeMap();//Creating HashMap. + + myTreeMap.put(2,"Papaya"); //Putting elements in Map. + + myTreeMap.put(3,"Mango"); + + myTreeMap.put(1,"Apple"); + + myTreeMap.put(4,"Lemon"); + + System.out.println(myTreeMap); } + +//Output: {1=Apple, 2=Papaya, 3=Mango, 4=Lemon} +//meaning Key Order +} +``` + - - - ``` -### LinkedHashMap - ``` - Ordered by Insertion FIFO - ``` - + ```java import java.util.*; -public class Main +public class Main { - public static void main(String args[]) - { - //LHM Declaration - //LinkedHashMap
nameOfLinkedHashMap= new LinkedHashMap
(); - LinkedHashMap myLHashMap=new LinkedHashMap();//Creating Linked HashMap. - - myLHashMap.put("MW","Calculus3"); //Putting elements in Map. - myLHashMap.put("MWF","OrgCh1"); - myLHashMap.put("T","DS"); - myLHashMap.put("F","Music"); - - System.out.println(myLHashMap); - } - - //Output: {MW=Calculus3, MWF=OrgCh1, T=DS, F=Music} - //meaning Reverse Insertion Order FIFO + public static void main(String args[]) + { + //LHM Declaration + + //LinkedHashMap
nameOfLinkedHashMap= new LinkedHashMap
(); + + LinkedHashMap myLHashMap=newLinkedHashMap();//Creating Linked HashMap. + + myLHashMap.put("MW","Calculus3"); //Putting elements in Map. + + myLHashMap.put("MWF","OrgCh1"); + + myLHashMap.put("T","DS"); + + myLHashMap.put("F","Music"); + + System.out.println(myLHashMap); + } + //Output: {MW=Calculus3, MWF=OrgCh1, T=DS, F=Music} + //meaning Reverse Insertion Order FIFO } - ``` +``` \ No newline at end of file diff --git a/Maven/README.md b/Maven/README.md index 9f232f8..ef521d9 100644 --- a/Maven/README.md +++ b/Maven/README.md @@ -15,8 +15,7 @@ - Handling, Versioning Your Artifacts - -### How To Install: +### How To Install - Head over to: https://maven.apache.org/download.cgi - Download the Binary Zip Archive @@ -56,7 +55,6 @@ mvn --version - pom.xml holds all the metadata of my Application i.e. project dependencies - target folder holds all the java compiled class files - ### Creating A Project - Give it an artifact id(this is usually the name of your project) e.g. my-project-demo @@ -70,13 +68,11 @@ mvn --version - Maven provides me with functionality on how to manage my dependencies - ...thanks to the pom.xml file - ### Life Without Maven - I have to manually download the JAR files from the internet - then I add them one by one - ### Dependency Section Thanks To Maven - Maven provides me with a dependency section where I can specify the info of the JAR I require in my project @@ -87,27 +83,26 @@ mvn --version - Load each dependency in a "dependency" tag - And all your depenency tags should be in between 1 dependencies tag -< dependencies > - < dependencyA > +```xml + + - < /dependencyA > + - < dependencyB > + - < /dependencyB > -< dependencies > - -- To add a dependency go to https://www.mvnrepository.com/ + + +``` +- To add a dependency go to - Click on the Maven Icon to force IntelliJ to download the dependencies you have specified - -### Transitive Dependencies +### Transitive Dependencies - Dependencies of my dependencies - ``` ├── /my-project-demo ├── /.idea @@ -130,6 +125,7 @@ mvn --version - target folder holds all the java compiled class files ### Maven Dependency + - Can be categorized into two categories: - Snapshot Dependency - This dependency was created when the software was in active development @@ -141,23 +137,31 @@ mvn --version - In all, when I am developing the software I use the snapshot versions for the dependencies. When the software is released, I use the release versions --- + ### Dependency Scopes - enables me to control the visibility of a Maven depenendency -- 4 types: +- 5 types: + 1. **Compile**: made available at compile time within classpath [default scope] + 2. **Provided**: dependency provided at runtime by JDK or webserver, e.g. Servlet API dependency. The web server which is running my project provides me with the java servlet-api during runtime. This means that the dependency will be available in the class path of the project but will not be packaged in the JAR file nor the WAR file -3. **Runtime**: dependency provided ONLY at runtime and NOT at compile time e.g. MySQL JDBC connector dependency. I mark the dependency as runtime to make sure I do not use the MySQL JDBC classes in my code instead of standard jdbc api -4. **Tests**: dependency only available at the time of writing and running my unit tests e.g. junit, spring-boot-starter-test + +3. **Runtime**: dependency provided ONLY at runtime and NOT at compile time e.g. MySQL JDBC connector dependency. I mark the dependency as runtime to make sure I do not use the MySQL JDBC classes in my code instead of standard jdbc api + +4. **Tests**: dependency only available at the time of writing and running my unit tests e.g. junit, spring-boot-starter-test + 5. **System**: the path to the JAR should be specified manually using the < systemPath > tag. The only restriction is that I must specify the exact path of where to locate this dependency within my system. ### Repositories + - a special directory called a **repository** is the location where Maven stores my dependencies - Local Repository[directory/folder in your machine] - Remote Repository[Maven Website] where I can download the Maven dependencies - If a dependency I specified in my pom is not in my local repository it goes ahead and connects to the remote repository and downloads the remote repository and stores the dependency within my local repository -##### How To Define A Repository within my POM always after my closing dependency tag +#### How To Define A Repository within my POM always after my closing dependency tag + ```xml @@ -167,7 +171,6 @@ mvn --version ``` - ### Build Lifecycle Within Maven - How Does Maven Build Our Projects? @@ -176,6 +179,7 @@ mvn --version 3. site #### Default Lifecycle Build Step Phases + 1. validate - Makes sure pom.xml is validated or not validated 2. compile @@ -190,27 +194,26 @@ mvn --version - Verifies the results of the integrations tests 7. install - Installs the newly created package files(JAR or any other artifact) within my local repository - - Maven + - Maven 8. deploy - Deploy the newly created package to the remote repository - If the newly created package is configured in the pom.xml file it will deploy the new package into the remote repository - ### Command + ```java mvn clean install ``` - This command compiles the source code - Runs the unit tests -- Creates the JAR file +- Creates the JAR file - Install the JAR file into your local repository ### Site Step - generate Java documentation that is present in my project - ### Plugins and Goals - To be able to execute the different lifecyle phases, Maven provides me with different plugins in order for me to perform each task in the lifecycle @@ -232,12 +235,13 @@ mvn clean install ``` - The plugin above is in charge of compiling any test files or source files I have within my project. This is familiar to running + ```java javac nameofclass.java ``` - #### To trigger the compile lifecycle phase + ```java mvn compiler:compile ``` @@ -251,11 +255,12 @@ mvn compiler:compile      1. Head to build section      2. Plugins ⇒ plugin      3. Configuration Tag -      4. Change the source & target properties to the java version installed on your machine - -### Maven Install Plugin +      4. Change the source & target properties to the java version installed on your machine + +### Maven Install Plugin - This plugin is used to run the install lifecycle phase within the maven build lifecycle + 1. Compiles My Source Code 2. Runs Our Unit Tests 3. Package The Cource Code into an Artifact @@ -267,11 +272,12 @@ mvn compiler:compile - Self-explanatory plugin - runs all the phases which are part of the install phase - deploys the created artifact to the remote repository + 0. To deploy the artifact to the remote repo you have to specify the remote repo details within your pom 1. Create a tag right above your dependencies tag and give it a name of **distributionManagement** 2. Within the distributionManagement tag create a tag named **repository** and place the information of your repository there 3. To uniquely identify a repository I specify the **id**, **name** and **url** -4. Run the command below to deploy your plugin +4. Run the command below to deploy your plugin ```java mvn clean deploy @@ -284,9 +290,9 @@ mvn clean deploy - e.g. I can skip the test execution due to the fact that my build process may take a long time - I create a profile that will skip the test execution phase -##### How To Create +#### How To Create -- Right below your build tag create a **profiles** tag +- Right below your build tag create a **profiles** tag - Within your profiles tag create a **profile** tag I give it an: - *id* @@ -296,6 +302,7 @@ mvn clean deploy - I head over to the terminal and run the following command: - -P flag indicates the id of the profile + ```java mvn -Pskip-tests clean install -``` \ No newline at end of file +``` diff --git a/MustKnow/README.md b/MustKnow/README.md index 10b8084..35212d3 100644 --- a/MustKnow/README.md +++ b/MustKnow/README.md @@ -236,7 +236,7 @@ public class HashTable{ - Trees are faster to access than a LL because they are non-linear - Node: person who holds our data - Child Node: person who has a parent -- Leaf Node: person who has no children +- Leaf: person who has no children - Edge: person who connects two nodes - Root: person who is the topmost node - Node Height: # of edges from the node to the deepest leaf node @@ -446,12 +446,17 @@ B(0) D(0) F(0) - Finite set of vertices, nodes and edges. The edges are what connect one vertex with another - Graphs are connected in a network form +- Vertex: Circle +- Edge: Arrow - Non-linear - Nodes are the vertices(i.e. endpoints) - Edges are the lines/arcs that connect one node with another node - Two Types: - Directed - Undirected +- Traversing Algo Implementing A Graph: + - BFS + - DFS - Simple Graph: Each edge connects to two different vertices whereby no two edges connect to the same group of vertices - Multigraph: An edge can connect to the same pair of vertices - Google Maps Usage of Connecting Roads i.e. vertex therefore, I use an algo to determine the shortest path between vertex A & B diff --git a/README.md b/README.md index 04e7a6a..20850df 100644 --- a/README.md +++ b/README.md @@ -36,9 +36,10 @@ public void theBestMethod() #### Primitive DS: 1. Integer 2. Float -3. Char` +3. Char 4. Pointers + #### Non-Primitive DS: 1. Arrays 2. List From e53cc78fb77614ddc692e9c2f63dc050b9c805bb Mon Sep 17 00:00:00 2001 From: Omar Belkady <31806568+omarbelkady@users.noreply.github.com> Date: Tue, 28 Sep 2021 00:11:37 +0000 Subject: [PATCH 08/21] The static keyword in Java + More Info on LHMap, HMap and TMap --- Maps/README.md | 25 +++++----------- STATIC/README.md | 75 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 18 deletions(-) create mode 100644 STATIC/README.md diff --git a/Maps/README.md b/Maps/README.md index c80f71e..493c697 100644 --- a/Maps/README.md +++ b/Maps/README.md @@ -1,8 +1,6 @@ ## Maps - - - A map is an object that maps keys and values - Cannot contain the same keys @@ -13,15 +11,11 @@ - Maps are very important to know when dealing with Abstraction in OOP +- Java has three types of maps: HashMap, TreeMap and LinkedHashMap +
-### Java has three types of maps: HashMap , TreeMap and and LinkedHashMap - - - -### Ordering: - - +### Ordering
@@ -115,31 +109,26 @@ public class Main } ``` - - ```java import java.util.*; + public class Main { public static void main(String args[]) { - //LHM Declaration + //LHM Declaration //LinkedHashMap
nameOfLinkedHashMap= new LinkedHashMap
(); LinkedHashMap myLHashMap=newLinkedHashMap();//Creating Linked HashMap. myLHashMap.put("MW","Calculus3"); //Putting elements in Map. - myLHashMap.put("MWF","OrgCh1"); - myLHashMap.put("T","DS"); - myLHashMap.put("F","Music"); - + System.out.println(myLHashMap); } - //Output: {MW=Calculus3, MWF=OrgCh1, T=DS, F=Music} - //meaning Reverse Insertion Order FIFO + } ``` \ No newline at end of file diff --git a/STATIC/README.md b/STATIC/README.md new file mode 100644 index 0000000..dc38e49 --- /dev/null +++ b/STATIC/README.md @@ -0,0 +1,75 @@ +## Static Keyword In Java + + +- SUPER IMPORTANT +- Anything I label static means the class can access it directly + +- Instead of: + - Creating An Object + - THEN ACCESSING IT + +- I can: + - Create a variable to store data + - Create a static method + +```java +import java.util.*; + +public class User{ + private String _name; + private String _membership; + public static List administrators; +} +``` + +### Main Class + +```java +import java.util.*; + +public class Main{ + + public static void main(String [] args){ + User.administrators = new ArrayList(); + User.administrators.add(new User("Abraham")); + User.administrators.add(new User("DJ32")); + } +} +``` + + +
+ +### Static Methods + + + +- I access data members directly on the User class + +- System.out.println where **out** is a static data member of the System class + +- e.g. Whenever you want to read Data from a file You can associate it to a user + - Instead of creating a function I create a static method return a list + +- Example: + +```java +public class User{ + public static List administrators; + + public static void print_the_admins(){ + + /* + since List and print_the_admins are both static + I can omit User.administrators + + */ + //for(User j: User.administrators) + for(User j: administrators){ + + System.out.println(j.get_The_Names()) + } + } +} + +``` \ No newline at end of file From 443d31c18801594d3eed0db72f7b5cfd0746d370 Mon Sep 17 00:00:00 2001 From: Omar Belkady Date: Mon, 18 Apr 2022 22:03:35 +0000 Subject: [PATCH 09/21] .equals() vs == --- README.md | 655 +++++++++++++++++++++++++++--------------------------- 1 file changed, 330 insertions(+), 325 deletions(-) diff --git a/README.md b/README.md index 20850df..6e9f0c8 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,11 @@ 6. UI: How We Present the data +### == vs .equals() + +- ==: compares content and reference +- .equals(): compares just the content + ## Class Naming is Pascal Case The case name is = to 2526 fav programming language and fav screen color: ```java class PascalCase{} @@ -26,9 +31,9 @@ ## Method Naming is Camel Case: ```java public void theBestMethod() -{ - logln("2526: 727225, 27736259, 27429, 27375, 746867 ARE THE BEST THINGS EVER and 557 AKA LLP Prog is also my fav!!!"); -} + { + logln("2526: 727225, 27736259, 27429, 27375, 746867 ARE THE BEST THINGS EVER and 557 AKA LLP Prog is also my fav!!!"); + } ``` ## Data Structures @@ -43,12 +48,12 @@ public void theBestMethod() #### Non-Primitive DS: 1. Arrays 2. List - - Linear: - - Stacks - - Queues - - Non-Linear: - - Graphs - - Trees + - Linear: + - Stacks + - Queues + - Non-Linear: + - Graphs + - Trees @@ -72,16 +77,16 @@ $~ java callingProgram.java MethodProgram.java ## What is the "this" keyword in Java and why do we use it ```java class NelanLvsBDAndCSunAndFTN{ - int cobolfb = 2626532; - int pascalfb= 72722532; - - public void setVals(int cobolfb, int pascalfb){ + int cobolfb = 2626532; + int pascalfb= 72722532; + + public void setVals(int cobolfb, int pascalfb){ /*here is where the this keyword comes to play to tell java that I want to use the parameter of my function aka local variables and not the instance variables(up top) */ - this.cobolfb = cobolfb; - this.pascalfb = pascalfb; - } + this.cobolfb = cobolfb; + this.pascalfb = pascalfb; + } } ``` @@ -93,14 +98,14 @@ class NelanLvsBDAndCSunAndFTN{ Raised when you try to call an undeclared variable ```java public class Omar{ - public static void main(String [] args) - { - int a = 1; - int b= 2; - int c= 3; - mean = (a+b+c)/2; - System.out.println(mean); - } + public static void main(String [] args) + { + int a = 1; + int b= 2; + int c= 3; + mean = (a+b+c)/2; + System.out.println(mean); + } } ``` @@ -108,30 +113,30 @@ In line 8 we try to print to the console mean we have set the value of mean but To solve we do this ```java public class Omar{ - public static void main(String [] args) - { - int a = 1; - int b= 2; - int c= 3; - double mean = (a+b+c)/2; - System.out.println(mean); - } + public static void main(String [] args) + { + int a = 1; + int b= 2; + int c= 3; + double mean = (a+b+c)/2; + System.out.println(mean); + } } ``` ### 2- cannot find symbol PART 2 Raised when you try to call an undeclared variable ```java public class Great{ - public static void main(String [] args) - { - the_best_method; - } - - public static void the_best_method() - { + public static void main(String [] args) + { + the_best_method; + } + + public static void the_best_method() + { System.out.println("This is the best method in the world"); - } - + } + } ``` @@ -139,41 +144,41 @@ In line 4 we are incorrectly calling the_best_method but we forget the parenthes ```java public class Great{ - public static void main(String [] args) - { - the_best_method(); - } - - public static void the_best_method() - { + public static void main(String [] args) + { + the_best_method(); + } + + public static void the_best_method() + { System.out.println("This is the best method in the world"); - } - + } + } ``` -### 3- cannot find symbol : -### symbol: class Scanner +### 3- cannot find symbol : +### symbol: class Scanner ### location: class Great Raised when you are using the scanner ```java public class Great{ - public static void main(String [] args) - { - Scanner useInput= new Scanner(); // scanner is not imported - int l = useInput.nextInt(); - } + public static void main(String [] args) + { + Scanner useInput= new Scanner(); // scanner is not imported + int l = useInput.nextInt(); + } } ``` -In line 4 we are using the scanner but we never imported the library that enables us to use it +In line 4 we are using the scanner but we never imported the library that enables us to use it ```java import java.util.Scanner; public class Great{ - public static void main(String [] args) - { - Scanner useInput= new Scanner(); // scanner has no default constructor - int l = useInput.nextInt(); - } + public static void main(String [] args) + { + Scanner useInput= new Scanner(); // scanner has no default constructor + int l = useInput.nextInt(); + } } ``` @@ -182,10 +187,10 @@ public class Great{ ```java public class Thebest -{ - public static void main(String[] args) { - System.out.println("Hello, world!"); - } +{ + public static void main(String[] args) { + System.out.println("Hello, world!"); + } } ``` ## SOOO, I save the file and I name it Lemon.java well, it will error because our class is Thebest so that means our file name should be Thebest.java @@ -196,22 +201,22 @@ This error is raised when I try to write code outside of a method which is unint ```java public class Test { System.out.println("Hello!"); - - public static void main(String[] args) { - System.out.println("World!"); - } - } + + public static void main(String[] args) { + System.out.println("World!"); + } +} ``` - + To fix I just place the print Statement of hello inside of main ```java - public class Test { - public static void main(String[] args) { - System.out.println("Hello!"); - System.out.println("World!"); - } - } + public class Test { + public static void main(String[] args) { + System.out.println("Hello!"); + System.out.println("World!"); + } +} ``` ### 6- illegal start of expression @@ -219,29 +224,29 @@ To fix I just place the print Statement of hello inside of main An "illegal start of expression" error occurs when the compiler when we start a expression before closing the previous one. ```java public class Test { - public static void main(String[] args) { - my_method(); - - - public static void my_method() { - System.out.println("Hello, world!"); - } - } + public static void main(String[] args) { + my_method(); + + + public static void my_method() { + System.out.println("Hello, world!"); + } + } ``` To fix this piece of code, I simply add a closing curly brace for the main method. To know we are doing the right thing, just look at the lines of code before the error, there may be a missing closing paranthesis or a missing closing curly brace. This would give us what the error is. ```java public class Test { - public static void main(String[] args) - { - my_method(); - } - - public static void my_method() - { - System.out.println("Hello, EVERYONEEEE!"); - } + public static void main(String[] args) + { + my_method(); + } + + public static void my_method() + { + System.out.println("Hello, EVERYONEEEE!"); + } } ``` @@ -249,12 +254,12 @@ public class Test The incompatible types error is raised when we are facing with data type errors. We can overcome this, by converting say a char to an int. We can convert a double to an integer with typecasting. BUt WE CANNOT convert between primitive types and objects. A primitive type is say a: null, undefined, boolean, number, string or char. However objects can be: Arrays, Maps, Sets, Functions, Regular Expression or Date.. ```java -public class Test +public class Test { - public static void main(String[] args) - { - int num = "Hello, world!"; - } + public static void main(String[] args) + { + int num = "Hello, world!"; + } } ``` The above code is an error because we are assigning the string Hello World to the variable num of type int. @@ -263,24 +268,24 @@ Step 1: Change the String value from Hello, world! to 500 ```java public class Test { - public static void main(String[] args) - { - int num = "500"; - } + public static void main(String[] args) + { + int num = "500"; + } } ``` - + Step 2: Use parsing to convert the string to an integer ```java public class Test { - public static void main(String[] args) - { - int num = Integer.parseInt("500"); - } + public static void main(String[] args) + { + int num = Integer.parseInt("500"); + } } ``` - + ### 8- invalid method declaration; return type required @@ -290,16 +295,16 @@ When a method declaration does not contain a return type, this error will occur: ```java public class Test { - public static void main(String[] args) - { - int x = getValue(); - System.out.println(x); - } - - public static getValue() - { - return 10; - } + public static void main(String[] args) + { + int x = getValue(); + System.out.println(x); + } + + public static getValue() + { + return 10; + } } @@ -308,48 +313,48 @@ To fix this, simply insert the appropriate return type in the method signature a ```java -public class Test +public class Test { - public static void main(String[] args) - { - int x = getValue(); - System.out.println(x); - } - - public static int getValue() - { - return 10; - } + public static void main(String[] args) + { + int x = getValue(); + System.out.println(x); + } + + public static int getValue() + { + return 10; + } } ``` ### 9-java.lang.ArrayIndexOutOfBoundsException: -An ArrayIndexOutOfBoundsException is thrown when an attempt is made to access an index in an array that is not valid. This means that say an array has 8 elements and we know that the number of elements in index is 7. We start counting at 0. So, if I enter a value of 8 or greater to access, this will raise an error. +An ArrayIndexOutOfBoundsException is thrown when an attempt is made to access an index in an array that is not valid. This means that say an array has 8 elements and we know that the number of elements in index is 7. We start counting at 0. So, if I enter a value of 8 or greater to access, this will raise an error. ```java public class Test { - public static void main(String[] args) { - int[] arr = {1, 2, 3}; - for (int i = 0; i <= arr.length; i++) { - System.out.println(arr[i]); - } - } - } + public static void main(String[] args) { + int[] arr = {1, 2, 3}; + for (int i = 0; i <= arr.length; i++) { + System.out.println(arr[i]); + } + } +} ``` The code above errored due to the for loop iteration settings. The first element is index 0 which is fine however, the function's output of arr.length of our array named arr of type int is 3. However, we are using the comparison operator of <=. This means less than or equal to. If, we change it to < it will not error. The equal means it will try to access index 3 which is the 4th item in the array which we do not have. ```java public class Test { - public static void main(String[] args) { - int[] arr = {1, 2, 3}; - for (int i = 0; i < arr.length; i++) { - System.out.println(arr[i]); - } - } + public static void main(String[] args) { + int[] arr = {1, 2, 3}; + for (int i = 0; i < arr.length; i++) { + System.out.println(arr[i]); + } + } } ``` -### 10- StringIndexOutOfBoundsException -The exception StringIndexOutOfBoundsException is thrown to the console when an attempt is made to access an index in +### 10- StringIndexOutOfBoundsException +The exception StringIndexOutOfBoundsException is thrown to the console when an attempt is made to access an index in the String that is not valid. The only valid index of the String we can access is from 0 to the (length of the String-1). This means that if the array 8 elements. The biggest number I can access is 7 not 8. If we enter any number greater than 7 for access will throws an outofBoundsException. This is an error in runtime not compile-time. It is accepted by the compiler because it is a logical error ``` java @@ -371,16 +376,16 @@ To fix this I simply change the String a declaration in line 7 from index -1 to Therefore the bottom code is bug free ```java -public class Test +public class Test { - public static void main(String[] args) - { - String str = "Hello, world!"; + public static void main(String[] args) + { + String str = "Hello, world!"; - String a = str.substring(1, 3); - char b = str.charAt((str.length())-1); - String c = str.substring(0, 6); - } + String a = str.substring(1, 3); + char b = str.charAt((str.length())-1); + String c = str.substring(0, 6); + } } ``` @@ -402,178 +407,178 @@ public class Test This errors because I have called the methods with the specified data types in the wrong order. I must call it in the right order ```java -public class Omar -{ - public static void main(String[] args) { - omarMethod(1.0,"YOLO!", 2); - } - - public static void omarMethod(double a, String b, int c) { - System.out.println(a + " " + b + " " + c); - } +public class Omar +{ + public static void main(String[] args) { + omarMethod(1.0,"YOLO!", 2); + } + + public static void omarMethod(double a, String b, int c) { + System.out.println(a + " " + b + " " + c); + } } ``` ### 12- Left out return statement ```java - public class Omar + public class Omar { - public static void main(String[] args) - { - int x = doubleMyNum(5); - System.out.println(x); - } + public static void main(String[] args) + { + int x = doubleMyNum(5); + System.out.println(x); + } - public static int doubleMyNum(int m) - { - int value = 2 * m; - } - } + public static int doubleMyNum(int m) + { + int value = 2 * m; + } +} ``` -The above code errors because I have made the function behave like a void but my 3rd keyword indicates my return type should +The above code errors because I have made the function behave like a void but my 3rd keyword indicates my return type should be of type int. To fix this, after storing the computation in a variable. I use the return keyword to return to the console. The output of the computation performed by the method. ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - int x = doubleMyNum(5); - System.out.println(x); - } + public static void main(String[] args) + { + int x = doubleMyNum(5); + System.out.println(x); + } - public static int doubleMyNum(int m) - { - int value = 2 * m; - return value; - } - } + public static int doubleMyNum(int m) + { + int value = 2 * m; + return value; + } +} ``` ### - Left out return statement in CASE#2 ```java - public class Omar + public class Omar { - public static void main(String[] args) - { - int x = myAwesomeAbsVal(-5); - System.out.println(x); - } - - public static int myAwesomeAbsVal(int m) - { - if(m<0) - { - return -m; - } + public static void main(String[] args) + { + int x = myAwesomeAbsVal(-5); + System.out.println(x); + } - if(m>0) - { - return m; - } - } - } + public static int myAwesomeAbsVal(int m) + { + if(m<0) + { + return -m; + } + + if(m>0) + { + return m; + } + } +} ``` The above lines of code have an error in logic. We should switch the code to this: ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - int x = myAwesomeAbsVal(-5); - System.out.println(x); - } - - public static int myAwesomeAbsVal(int m) - { - if(m<0) - { - return -m; - } + public static void main(String[] args) + { + int x = myAwesomeAbsVal(-5); + System.out.println(x); + } - else - { - return m; - } - } + public static int myAwesomeAbsVal(int m) + { + if(m<0) + { + return -m; + } + + else + { + return m; + } + } } ``` ### 13 - possible loss of precision ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - int theAwesomePi = 3.14159; - System.out.println("The value of pi is: " + theAwesomePi); - } - } + public static void main(String[] args) + { + int theAwesomePi = 3.14159; + System.out.println("The value of pi is: " + theAwesomePi); + } +} ``` There is an error above being raised being we are store double in an integer. An integer can only store 4 4 bytes in main memory. The value we are storing in it is a double which has a memory size of 8 bytes. The way to solve this issue. We will explictly cast the variable theAwesomePi to an int. ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - int theAwesomePi = (int)3.14159; - System.out.println("The value of pi is: " + theAwesomePi); - } - } + public static void main(String[] args) + { + int theAwesomePi = (int)3.14159; + System.out.println("The value of pi is: " + theAwesomePi); + } +} ``` ### 14 - Reached end of file while parsing ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - myWonderfulMethod(); - } - - public static void myWonderfulMethod() - { - System.out.println("How Awesome do you think my Method is?"); - } + public static void main(String[] args) + { + myWonderfulMethod(); + } + + public static void myWonderfulMethod() + { + System.out.println("How Awesome do you think my Method is?"); + } ``` There is an error above being raised being we are not properly closing our class. To solve this issue we add a closing curly brace. After, the closing curly brace of my method. ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - myWonderfulMethod(); - } - - public static void myWonderfulMethod() - { - System.out.println("How Awesome do you think my Method is?"); - } + public static void main(String[] args) + { + myWonderfulMethod(); + } + + public static void myWonderfulMethod() + { + System.out.println("How Awesome do you think my Method is?"); + } } ``` ### 15 - unreachable statement -An "unreachable statement" error takes place when the compiler sees that it is impossible to reacha a certain statement. This is caused by the following code. +An "unreachable statement" error takes place when the compiler sees that it is impossible to reacha a certain statement. This is caused by the following code. ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - int theAwesomeNum = doubleMe(5); - System.out.println(theAwesomeNum); - } - - public static int doubleMe(int a) - { - int doubleMe = 2 * a; - return doubleMe; - System.out.println("Returning " + doubleMe); - } + public static void main(String[] args) + { + int theAwesomeNum = doubleMe(5); + System.out.println(theAwesomeNum); + } + + public static int doubleMe(int a) + { + int doubleMe = 2 * a; + return doubleMe; + System.out.println("Returning " + doubleMe); + } } ``` @@ -581,47 +586,47 @@ The compiler will generate a number of errors. The first one to be listed is tha This is because whenever we create a method and use the keyword return the compiler says you are done with the method therefore, we can exit out of the method and execute the next line of code. To fix this error I simply reverse the order of the print statement and the return statement. ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - int theAwesomeNum = doubleMe(5); - System.out.println(theAwesomeNum); - } + public static void main(String[] args) + { + int theAwesomeNum = doubleMe(5); + System.out.println(theAwesomeNum); + } - public static int doubleMe(int a) - { - int doubleMe = 2 * a; - System.out.println("Returning " + doubleMe); - return doubleMe; - } + public static int doubleMe(int a) + { + int doubleMe = 2 * a; + System.out.println("Returning " + doubleMe); + return doubleMe; + } } ``` -### 16 - Variable might not have been initialized +### 16 - Variable might not have been initialized An variable might not have been initialized error is triggered when we declare a variable and specify its type but never give it an initial value; ```java - public class Omar - { - public static void main(String[] args) { - int myNum = 16; - int myNum2; - System.out.println(myNum + myNum2); - } - } + public class Omar +{ + public static void main(String[] args) { + int myNum = 16; + int myNum2; + System.out.println(myNum + myNum2); + } +} ``` The compiler will generate the error variable myNum2 might not have been initialized because we declared it with the specified data type but never gave it an initial value. To solve this, I simply give it an initial value. ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - int myNum = 16; - int myNum2=3; - System.out.println(myNum + myNum2); - } + public static void main(String[] args) + { + int myNum = 16; + int myNum2=3; + System.out.println(myNum + myNum2); + } } ``` ### 17 - constructor X in class X cannot be applied to given types @@ -631,34 +636,34 @@ super() ### 18 - Cannot make a static reference to the non-static method logLn(object) from the type Omar ```java -public class Omar +public class Omar { - public void logLn(object o){ - System.out.println(o); - } + public void logLn(object o){ + System.out.println(o); + } - public static void main(String[] args) - { - int myNum = 16; - int myNum2=3; - logLn(myNum + myNum2); - } + public static void main(String[] args) + { + int myNum = 16; + int myNum2=3; + logLn(myNum + myNum2); + } } ``` I am getting this error because logLn should me a static method ```java -public class Omar +public class Omar { - public static void logLn(object o){ - System.out.println(o); - } + public static void logLn(object o){ + System.out.println(o); + } - public static void main(String[] args) - { - int myNum = 16; - int myNum2=3; - logLn(myNum + myNum2); - } + public static void main(String[] args) + { + int myNum = 16; + int myNum2=3; + logLn(myNum + myNum2); + } } ``` @@ -699,8 +704,8 @@ public void setLuckyNum(int luckyNum) { this.luckyNum = luckyNum; } */ -@Getter -@Setter +@Getter +@Setter private int luckyNum = 3532; ``` @@ -714,7 +719,7 @@ public class Example ### Equals And Hash Code Annotation ```java @EqualsAndHashCode( - exclude={"id1", "id2"}) + exclude={"id1", "id2"}) public class Example { } ``` \ No newline at end of file From f294d649fd27d8df7115da89ce4292ed0c5f02a7 Mon Sep 17 00:00:00 2001 From: Omar Belkady Date: Wed, 20 Apr 2022 15:12:36 +0000 Subject: [PATCH 10/21] Abstraction is now detailed and well written --- Abstraction/README.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Abstraction/README.md diff --git a/Abstraction/README.md b/Abstraction/README.md new file mode 100644 index 0000000..9919894 --- /dev/null +++ b/Abstraction/README.md @@ -0,0 +1,35 @@ +## Abstraction + +- Hide certain details and show only what's necessary to the User +- Used through Abstract Classes/Interfaces +- Any class that inherits from an abstract class must implement all the abstract methods declared in the abstract class +- An abstract Class Cannot be instantiated + + +### Example + + +```java +public abstract class Animal{ + public abstract void animalSound(); + + public void sleep(){ + System.out.println("Zzz"); + } +} + +public class Dog extends Animal{ + public void animalSound(){ + System.out.println("Woofwoof"); + } +} + +public class Base{ + public static void main(String [] args) + { + Dog olivia = new Dog(); + olivia.animalSound(); + olivia.sleep(); + } +} +``` \ No newline at end of file From 99151d4707b2db40822a6d46c97c1925460238eb Mon Sep 17 00:00:00 2001 From: Omar Belkady Date: Mon, 25 Apr 2022 02:27:20 +0000 Subject: [PATCH 11/21] Topics to Know To Understand Java --- MustKnow/README.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/MustKnow/README.md b/MustKnow/README.md index 35212d3..367ba3d 100644 --- a/MustKnow/README.md +++ b/MustKnow/README.md @@ -13,6 +13,36 @@ - Binary Tree - Binary Search Tree +##### Things You Must Know To Understand Java +- Abstract +- Arrays And ArrayList +- Collections +- Conditionals +- Default +- Enum +- Exception Handling +- Final Keyword +- Generics +- Interfaces +- Loops +- Maps +- OOP(Abstraction, Encapsulation, Inheritance, Polymorphism) +- Passing By Value Vs. Passing By Reference +- Reference Types Vs Primitive Types +- Sets +- Static +- ToString & Equals & Hashcode + + + + + + + + + + + ##### ★★★★Operation You Can Perform On A Data Structure★★★★ From 9d5a094ad7f3eb20d7d7af47e921cc8cfc925499 Mon Sep 17 00:00:00 2001 From: Omar Belkady Date: Sun, 3 Jul 2022 20:56:38 +0000 Subject: [PATCH 12/21] DFS Graph Algorithm Pre order, Post order and Regular Order --- MustKnow/Graphs/README.md | 35 ++++++++++++++++++++ MustKnow/README.md | 67 ++++++++++++++++++++++----------------- 2 files changed, 73 insertions(+), 29 deletions(-) create mode 100644 MustKnow/Graphs/README.md diff --git a/MustKnow/Graphs/README.md b/MustKnow/Graphs/README.md new file mode 100644 index 0000000..21f602f --- /dev/null +++ b/MustKnow/Graphs/README.md @@ -0,0 +1,35 @@ +### Graphs Implementation + + +
+ +##### DFS +```java +import java.util.*; +class Main{ + public final int depthfirsts(int node, int result){ + /*PRE ORDER + * + * result.push(node,value); + * */ + + if(node.left) { + depthfirsts(node.left, result); + } + + + result.push(node,value); + + + if(node.right){ + depthfirsts(node.right); + } + + /*POST ORDER + * + * result.push(node,value); + * */ + return result; + } +} +``` \ No newline at end of file diff --git a/MustKnow/README.md b/MustKnow/README.md index 367ba3d..317df54 100644 --- a/MustKnow/README.md +++ b/MustKnow/README.md @@ -6,12 +6,18 @@ ##### ★★★★★Most Popular Data Structures★★★★★ -- Array -- Linked List -- Stack -- Queue -- Binary Tree -- Binary Search Tree +- Array [Linear and Non-Primitive] + +- Char [Primitive] +- Double [Primitive] +- Float [Primitive] +- Graph [Non-Linear and Non-Primitive] +- Integer [Primitive] +- Linked List [Linear and Non-Primitive] +- Stack [Linear and Non-Primitive] +- String [Primitive] +- Tree [Non-Linear and Non-Primitive] +- Queue [Linear and Non-Primitive] ##### Things You Must Know To Understand Java - Abstract @@ -33,17 +39,9 @@ - Static - ToString & Equals & Hashcode +
- - - - - - - - - -##### ★★★★Operation You Can Perform On A Data Structure★★★★ +##### ★★★★Operations You Can Perform On A Data Structure★★★★ - Delete: Remove an item from the data structure @@ -75,7 +73,7 @@ -1. Stack +1. **Stack** - Linear - LIFO/FILO @@ -98,7 +96,7 @@ Stack myStack= new Stack(); ``` -2. Linked List +2. **Linked List** - Sequential Order - No Random Access @@ -120,7 +118,7 @@ LinkedListnameOfLL = new LinkedList() */ LinkedList mylist=new LinkedList(); ``` -3. Array +3. **Array** - Indexed - When Size increases performance decreases @@ -179,10 +177,10 @@ public class Arr{ } ``` -4. Vector: Grows by 100% of its size everytime I add sth to it... asynchronous aka multiple threads at a time +4. **Vector** : Grows by 100% of its size everytime I add sth to it... asynchronous aka multiple threads at a time -5. Queues +5. **Queues** - People waiting in line in the Movie Theatre - Linear @@ -215,7 +213,7 @@ public class queueimpl{ ``` -5. Hash Table +6. **Hash Table** - Contains an index and its corresponding Hash_Value @@ -258,7 +256,7 @@ public class HashTable{ ``` -6. Trees +7.**Trees** - Hierarchical Structure where data is org in a hierarchy and everything is linked together - Not the same as linked list because LL is linear @@ -459,7 +457,7 @@ B(0) D(0) F(0) -7. Heap +8.**Heap** - Special Tree Based DS - Binary Tree @@ -472,7 +470,7 @@ B(0) D(0) F(0) - Patients that don't have threatening situation wait in line -8. Graphs +9.**Graphs** - Finite set of vertices, nodes and edges. The edges are what connect one vertex with another - Graphs are connected in a network form @@ -481,14 +479,25 @@ B(0) D(0) F(0) - Non-linear - Nodes are the vertices(i.e. endpoints) - Edges are the lines/arcs that connect one node with another node -- Two Types: - - Directed - - Undirected +- Types: + - **Directed**: no particular direction and two-way relation + - e.g. Friends on Facebook + - **Undirected**: Particular Direction and one-way relation + - e.g. who you're following on Twitter + - **Unweighted**: Every edge has no particular weight + - **Weighted**: Each edge has a respective value this is referred to as weight + - e.g. distance between cities +- **Note** A (directed/undirected )graph is independent of being weighted or not +- We can have: + - Direct Weighted Graphs + - Direct Unweighted Graphs + - Undirected Weighted Graphs + - Undirected Unweighted Graphs - Traversing Algo Implementing A Graph: - BFS - DFS - Simple Graph: Each edge connects to two different vertices whereby no two edges connect to the same group of vertices -- Multigraph: An edge can connect to the same pair of vertices +- Multi-graph: An edge can connect to the same pair of vertices - Google Maps Usage of Connecting Roads i.e. vertex therefore, I use an algo to determine the shortest path between vertex A & B From af5e4b881c0b69e6c4d797c93527713ebfe5fccc Mon Sep 17 00:00:00 2001 From: Omar Belkady Date: Tue, 5 Jul 2022 19:56:28 +0000 Subject: [PATCH 13/21] Different Types of Algo --- MustKnow/README.md | 56 +++++++++++++++++++++++++++------------------- 1 file changed, 33 insertions(+), 23 deletions(-) diff --git a/MustKnow/README.md b/MustKnow/README.md index 317df54..62559fc 100644 --- a/MustKnow/README.md +++ b/MustKnow/README.md @@ -457,7 +457,7 @@ B(0) D(0) F(0) -8.**Heap** +8. **Heap** - Special Tree Based DS - Binary Tree @@ -470,7 +470,7 @@ B(0) D(0) F(0) - Patients that don't have threatening situation wait in line -9.**Graphs** +9. **Graphs** - Finite set of vertices, nodes and edges. The edges are what connect one vertex with another - Graphs are connected in a network form @@ -493,29 +493,53 @@ B(0) D(0) F(0) - Direct Unweighted Graphs - Undirected Weighted Graphs - Undirected Unweighted Graphs -- Traversing Algo Implementing A Graph: +## Important Algorithms +- Graph Algorithms: - BFS - DFS + - Dijkstra(Shortest Path) - Simple Graph: Each edge connects to two different vertices whereby no two edges connect to the same group of vertices - Multi-graph: An edge can connect to the same pair of vertices - Google Maps Usage of Connecting Roads i.e. vertex therefore, I use an algo to determine the shortest path between vertex A & B +### Sorting +- Bubble Sort +- Bucket/Insertion Sort +- Counting Sort +- Heap Sort +- Merge Sort +- Quick Sort +- Selection Sort -1. When the sample size increases of an Array what should you do? +
+ +## Search Algorithms + +1. Breath First Search[Graphs] +2. Depth First Search[Graphs] +3. Binary Search[Linear] +4. Linear Search + +**Other** +- Recursive Algorithms +- Hashing Algorithms +- Randomized Algorithms + -- Use A Linked List DS because it increases performance and isn't slow as the sample size increases + +1. When the sample size increases of an Array what should you do? + - Use A Linked List DS because it increases performance and isn't slow as the sample size increases 2. For Loop Runtime: O(n) where n is the size of the input 3. Function with 1 operation: O(1) 4. Say I have a print statement before a for loop and after what's the runtime: - -- Print statement: O(1) -- For Loop: O(n) -- Print statement: O(1) + - Print statement: O(1) + - For Loop: O(n) + - Print statement: O(1) Total: O(1+n+1)= O(n+2) @@ -795,23 +819,9 @@ O(n) - compare using .compareTo() method -### Important Algo - -#### Sorting -1. Merge Sort -2. Quick Sort -3. Bucket/Insertion Sort -4. Heap Sort -5. Selection Sort -6. Counting Sort -#### Searching - -1. Breath First Search[Graphs] -2. Depth First Search[Graphs] -3. Binary Search[Linear] #### Divide & Conquer From 47d212f1a4d8472b8b1e6c963e93404f3c1aa458 Mon Sep 17 00:00:00 2001 From: Omar Belkady Date: Fri, 18 Nov 2022 03:48:23 +0000 Subject: [PATCH 14/21] Selection Sort Implementation 7652626 32 --- MustKnow/README.md | 59 ++++++++++++++++++++++++++++++++++++- MustKnow/Selectionso.class | Bin 0 -> 1223 bytes MustKnow/Selectionso.java | 39 ++++++++++++++++++++++++ 3 files changed, 97 insertions(+), 1 deletion(-) create mode 100644 MustKnow/Selectionso.class create mode 100644 MustKnow/Selectionso.java diff --git a/MustKnow/README.md b/MustKnow/README.md index 62559fc..988f7eb 100644 --- a/MustKnow/README.md +++ b/MustKnow/README.md @@ -504,7 +504,15 @@ B(0) D(0) F(0) ### Sorting - Bubble Sort -- Bucket/Insertion Sort +- Bucket/Insertion Sort + - Runtime: O(n^2) ... ie terrible + - useful when paired with other more complex sorting algo + - i.e. Quicksort, Merge Sort + - good for ordering a small sample size + - Step 1: iterate from the 2nd array to the nth array over the array + - Step 2: compare the element which you are at with its parent/predecessor + - Step 3: if the key is less than its predecessor compare it to the preceding elements + - Step 4: Move the greater element up one spot to give space for the modified element - Counting Sort - Heap Sort - Merge Sort @@ -701,6 +709,9 @@ public class Main{ - O(n) because the val we are searching for maybe stored in the last node aka n that is worst case. + + + #### Insertion Sort Implementation ```java @@ -747,6 +758,52 @@ Space C: O(1) because I am adding a var ``` +#### Selection Sort Implementation + +```java +import java.util.*; + +public class Selectionso { + public static void Selectionso(int myArr[]) + { + for(int i=0;i myArr[j]) + { + position = j; + } + } + //perform a swap + int myTempVar = myArr[position]; + myArr[position] = myArr[i]; + myArr[i] = myTempVar; + } + } + + public static void PrintMyArray(int myArr[]) + { + for(int i=0; iJKH9dKy0#|nLGEMbMBd$Z+}is0p#&eMgTzxAq8PX7}Py} zz_TW|cCw|dJ-zBNM3xN8@bV17)a*tSU5HAM6?8+nkX~-Oo?fRcd!LF1i$0KHXP-NU z<&`~0=k;8SIIk(_g~~8o=QX`xTUGA8FuYxwxgNJXmuge1v#oMp2h|$ZPEJM){SpQg z3}T3({|bDDa6_;Oh|2)88v??jdYt2WF!S|+dXs%JZ-`Aw%c?Zg)76K-vrx|=N8c5T0ryR5V$a-nd&+0d^@@9ed8n{u58 z+lDA`(<~dFp6kLLh5#EUmsc%IcM2wVUEP&%k74>!Z&yi{u*fj>|5Uort^VjhHM;!b z7XqC%BJ@8=s|1aV#&G%**aw<0OwqsC27-u+n?iGu`kG2ZH0Fa#TKY7!eS}4ASqr_& zC&cP42Ga3NI+1yYaANr|$lm|`L4kZap4Kv@w3a9xGKzf_908vrL(fVu$@I(=Vj7|K z1bS#Midpnwo^J30`tg8rmgylRDLaPnFS6}7dKinHA^el}qvE!`JlHwh_#6m<;} U!H}l!Hty0&rr84SlLw>!0MRfMf&c&j literal 0 HcmV?d00001 diff --git a/MustKnow/Selectionso.java b/MustKnow/Selectionso.java new file mode 100644 index 0000000..d9f16b8 --- /dev/null +++ b/MustKnow/Selectionso.java @@ -0,0 +1,39 @@ +import java.util.*; + +public class Selectionso { + public static void Selectionso(int myArr[]) + { + for(int i=0;i myArr[j]) + { + position = j; + } + } + //perform a swap + int myTempVar = myArr[position]; + myArr[position] = myArr[i]; + myArr[i] = myTempVar; + } + } + + public static void PrintMyArray(int myArr[]) + { + for(int i=0; i Date: Fri, 18 Nov 2022 04:56:24 +0100 Subject: [PATCH 15/21] Not Necessary --- MustKnow/Selectionso.class | Bin 1223 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 MustKnow/Selectionso.class diff --git a/MustKnow/Selectionso.class b/MustKnow/Selectionso.class deleted file mode 100644 index 173336513209512dbdce26d8e3e201de238a0a4c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1223 zcmaJ=T~8B16g|_grOP5q`F306qhKl0swkQinrIUurdX2_Oy$L)Y+&hjx7l4t`p$1K zKBI}x`hbQQo{j%R|AEA>JKH9dKy0#|nLGEMbMBd$Z+}is0p#&eMgTzxAq8PX7}Py} zz_TW|cCw|dJ-zBNM3xN8@bV17)a*tSU5HAM6?8+nkX~-Oo?fRcd!LF1i$0KHXP-NU z<&`~0=k;8SIIk(_g~~8o=QX`xTUGA8FuYxwxgNJXmuge1v#oMp2h|$ZPEJM){SpQg z3}T3({|bDDa6_;Oh|2)88v??jdYt2WF!S|+dXs%JZ-`Aw%c?Zg)76K-vrx|=N8c5T0ryR5V$a-nd&+0d^@@9ed8n{u58 z+lDA`(<~dFp6kLLh5#EUmsc%IcM2wVUEP&%k74>!Z&yi{u*fj>|5Uort^VjhHM;!b z7XqC%BJ@8=s|1aV#&G%**aw<0OwqsC27-u+n?iGu`kG2ZH0Fa#TKY7!eS}4ASqr_& zC&cP42Ga3NI+1yYaANr|$lm|`L4kZap4Kv@w3a9xGKzf_908vrL(fVu$@I(=Vj7|K z1bS#Midpnwo^J30`tg8rmgylRDLaPnFS6}7dKinHA^el}qvE!`JlHwh_#6m<;} U!H}l!Hty0&rr84SlLw>!0MRfMf&c&j From 088d4252e0b62b78c6d95d416a090a46dcf3606c Mon Sep 17 00:00:00 2001 From: Omar Belkady Date: Thu, 24 Nov 2022 06:04:48 +0000 Subject: [PATCH 16/21] Merge Sort and Better Selection Sort implementation --- MustKnow/README.md | 148 +++++++++++++++++++++++++++++++++---- MustKnow/Selectionso.class | Bin 1223 -> 0 bytes MustKnow/Selectionso.java | 39 ---------- 3 files changed, 135 insertions(+), 52 deletions(-) delete mode 100644 MustKnow/Selectionso.class delete mode 100644 MustKnow/Selectionso.java diff --git a/MustKnow/README.md b/MustKnow/README.md index 988f7eb..3327f7d 100644 --- a/MustKnow/README.md +++ b/MustKnow/README.md @@ -766,20 +766,29 @@ import java.util.*; public class Selectionso { public static void Selectionso(int myArr[]) { - for(int i=0;i myArr[j]) - { - position = j; + /* + 0. take an unsorted num of elements within an array + 1. find the minimum and place it on its own + 2. find the second min and place it after the min in the other array + 3. repeat till you have one left(i.e. largest) and place it at the end of the array + */ + int arr_size = myArr.length; + for(int x=0;xJKH9dKy0#|nLGEMbMBd$Z+}is0p#&eMgTzxAq8PX7}Py} zz_TW|cCw|dJ-zBNM3xN8@bV17)a*tSU5HAM6?8+nkX~-Oo?fRcd!LF1i$0KHXP-NU z<&`~0=k;8SIIk(_g~~8o=QX`xTUGA8FuYxwxgNJXmuge1v#oMp2h|$ZPEJM){SpQg z3}T3({|bDDa6_;Oh|2)88v??jdYt2WF!S|+dXs%JZ-`Aw%c?Zg)76K-vrx|=N8c5T0ryR5V$a-nd&+0d^@@9ed8n{u58 z+lDA`(<~dFp6kLLh5#EUmsc%IcM2wVUEP&%k74>!Z&yi{u*fj>|5Uort^VjhHM;!b z7XqC%BJ@8=s|1aV#&G%**aw<0OwqsC27-u+n?iGu`kG2ZH0Fa#TKY7!eS}4ASqr_& zC&cP42Ga3NI+1yYaANr|$lm|`L4kZap4Kv@w3a9xGKzf_908vrL(fVu$@I(=Vj7|K z1bS#Midpnwo^J30`tg8rmgylRDLaPnFS6}7dKinHA^el}qvE!`JlHwh_#6m<;} U!H}l!Hty0&rr84SlLw>!0MRfMf&c&j diff --git a/MustKnow/Selectionso.java b/MustKnow/Selectionso.java deleted file mode 100644 index d9f16b8..0000000 --- a/MustKnow/Selectionso.java +++ /dev/null @@ -1,39 +0,0 @@ -import java.util.*; - -public class Selectionso { - public static void Selectionso(int myArr[]) - { - for(int i=0;i myArr[j]) - { - position = j; - } - } - //perform a swap - int myTempVar = myArr[position]; - myArr[position] = myArr[i]; - myArr[i] = myTempVar; - } - } - - public static void PrintMyArray(int myArr[]) - { - for(int i=0; i Date: Sun, 4 Dec 2022 07:59:29 -0800 Subject: [PATCH 17/21] Bubble Sort Implementation --- MustKnow/README.md | 161 ++++++++++++++++++++++++++++++--------------- 1 file changed, 108 insertions(+), 53 deletions(-) diff --git a/MustKnow/README.md b/MustKnow/README.md index 3327f7d..4e38180 100644 --- a/MustKnow/README.md +++ b/MustKnow/README.md @@ -710,6 +710,53 @@ public class Main{ +#### Bubble Sort Implementation + +```java +/* + + 1. Compare the first two elements if the first is + bigger than the second swap + + 2. compare the rest and if the second is less than + the first move the second to the left of the first + + */ + + +public class BubbleSort{ + + public static void bubbleSort(int [] arr){ + int arrsize = arr.length; + for(int s=0;sarr[t+1]){ + int temporary = arr[t]; + arr[t]=arr[t+1]; + arr[t+1]= temporary; + } + } + } + } + + public static void main(String [] args){ + int myarr[] ={3,60,35,2,45,320,5}; + System.out.println("Before Bubble Sort"); + for(int x=0; x + #### Insertion Sort Implementation @@ -757,59 +804,7 @@ Space C: O(1) because I am adding a var */ ``` - -#### Selection Sort Implementation - -```java -import java.util.*; - -public class Selectionso { - public static void Selectionso(int myArr[]) - { - /* - 0. take an unsorted num of elements within an array - 1. find the minimum and place it on its own - 2. find the second min and place it after the min in the other array - 3. repeat till you have one left(i.e. largest) and place it at the end of the array - */ - int arr_size = myArr.length; - for(int x=0;x #### Merge Sort Implementation @@ -925,6 +920,66 @@ public class MergeSort ``` +
+ + +#### Selection Sort Implementation + +```java +import java.util.*; + +public class Selectionso { + public static void Selectionso(int myArr[]) + { + /* + 0. take an unsorted num of elements within an array + 1. find the minimum and place it on its own + 2. find the second min and place it after the min in the other array + 3. repeat till you have one left(i.e. largest) and place it at the end of the array + */ + int arr_size = myArr.length; + for(int x=0;x + + #### Insertions at the End in a LL index Time C From 99c0cb3e2133c4d75b579f60fe91fa05729657db Mon Sep 17 00:00:00 2001 From: Omar Belkady Date: Tue, 13 Dec 2022 20:27:47 +0000 Subject: [PATCH 18/21] GCD aka Greatest common divisor --- MustKnow/GCDeuclid/README.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 MustKnow/GCDeuclid/README.md diff --git a/MustKnow/GCDeuclid/README.md b/MustKnow/GCDeuclid/README.md new file mode 100644 index 0000000..1f940c5 --- /dev/null +++ b/MustKnow/GCDeuclid/README.md @@ -0,0 +1,25 @@ +```java +public class GCDeuclid{ + public static void logLn(Object o){ + System.out.println(o); + } + + public static void main(String [] args){ + logLn(euclidgcd(1800,54)); + } + + public static int euclidgcd(int divid, int divis){ + //2526 56837 35 + /* + * if divisor i.e. divis completely divid i.e. dividend + * remain=0 i.e. therefore divis is the gcd + * */ + int remain = divid%divis; + if(remain==0){ + return divis; + } + + return euclidgcd(divis,remain); + } +} +``` \ No newline at end of file From 90e251396e4687110f9db46c3f37781ffd2501dc Mon Sep 17 00:00:00 2001 From: Omar Belkady <31806568+omarbelkady@users.noreply.github.com> Date: Sat, 11 Mar 2023 11:51:11 -0800 Subject: [PATCH 19/21] Backend Roadmap --- MustKnow/README.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/MustKnow/README.md b/MustKnow/README.md index 4e38180..e9485c1 100644 --- a/MustKnow/README.md +++ b/MustKnow/README.md @@ -19,6 +19,27 @@ - Tree [Non-Linear and Non-Primitive] - Queue [Linear and Non-Primitive] +##### Backend Roadmap +```mermaid +graph TD; + START/FINISH-- Containerization --> Docker; + Docker -- CI/CD Tools --> Gitlab; + Gitlab -- VCS --> GitHub/BitBucket; + GitHub/BitBucket -- Frameworks --> Express/Flask/Laravel/RubyOnRails; + Express/Flask/Laravel/RubyOnRails -- Prog_Lang --> Java/Python/Ruby/C#/NodeJS/Rust/PHP; + Java/Python/Ruby/C#/NodeJS/Rust/PHP -- Archi Pattern --> Microservices/Monolithic/Serverless/SOA; + Microservices/Monolithic/Serverless/SOA -- APIs --> REST/JSON/SOAP; + REST/JSON/SOAP -- Caching--> Client/Server/CDN; + Client/Server/CDN -- Testing --> + Integration/Unit/Functional; + Integration/Unit/Functional -- Database -- SQL --> MYSQL/Postgres; + Integration/Unit/Functional -- Database -- NoSQL --> MongoDB; + MongoDB --> START/FINISH + MYSQL/Postgres --> START/FINISH + +``` + + ##### Things You Must Know To Understand Java - Abstract - Arrays And ArrayList @@ -62,6 +83,8 @@ - Used in the Average Case + + ##### DS Operations - Traverse: Visiting each item in the DS once AND ONLY ONCE From b7b35799fd1f6a075bbd934b89fcdd2e33a04c1d Mon Sep 17 00:00:00 2001 From: Omar Belkady <31806568+omarbelkady@users.noreply.github.com> Date: Thu, 1 Jun 2023 20:23:33 +0100 Subject: [PATCH 20/21] Graph Example 2526 56837 7652626 --- MustKnow/README.md | 60 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/MustKnow/README.md b/MustKnow/README.md index e9485c1..a9b94ff 100644 --- a/MustKnow/README.md +++ b/MustKnow/README.md @@ -525,6 +525,66 @@ B(0) D(0) F(0) - Multi-graph: An edge can connect to the same pair of vertices - Google Maps Usage of Connecting Roads i.e. vertex therefore, I use an algo to determine the shortest path between vertex A & B + +```java +//basic example + +import java.util.*; + +class Graph { + private int V; // Number of vertices + private LinkedList[] adjList; // Array of adjacency lists + + // Constructor + public Graph(int V) { + this.V = V; + adjList = new LinkedList[V]; + + for (int i = 0; i < V; i++) { + adjList[i] = new LinkedList(); + } + } + + // Add an edge to the graph + public void addEdge(int src, int dest) { + adjList[src].add(dest); + adjList[dest].add(src); // Uncomment this line for undirected graph + } + + // Print the graph + public void printGraph() { + for (int i = 0; i < V; i++) { + System.out.print("Vertex " + i + " is connected to: "); + for (int neighbor : adjList[i]) { + System.out.print(neighbor + " "); + } + System.out.println(); + } + } +} + +public class Main { + public static void main(String[] args) { + // Create a graph with 5 vertices + Graph graph = new Graph(5); + + // Add edges + graph.addEdge(0, 1); + graph.addEdge(0, 4); + graph.addEdge(1, 2); + graph.addEdge(1, 3); + graph.addEdge(1, 4); + graph.addEdge(2, 3); + graph.addEdge(3, 4); + + // Print the graph + graph.printGraph(); + } +} + +``` + + ### Sorting - Bubble Sort - Bucket/Insertion Sort From 2405314b79c0a10c73e01b15e3cebb013ad92849 Mon Sep 17 00:00:00 2001 From: Omar Date: Mon, 28 Aug 2023 00:15:57 +0100 Subject: [PATCH 21/21] More Must Know Stuff --- MustKnow/Array Algo/README.md | 88 +++++++++++++++++++++++++++++++++++ MustKnow/Design Pat/README.md | 8 ++++ 2 files changed, 96 insertions(+) create mode 100644 MustKnow/Array Algo/README.md create mode 100644 MustKnow/Design Pat/README.md diff --git a/MustKnow/Array Algo/README.md b/MustKnow/Array Algo/README.md new file mode 100644 index 0000000..fba5e6e --- /dev/null +++ b/MustKnow/Array Algo/README.md @@ -0,0 +1,88 @@ +### Array Algorithms + + +#### Floyd's Cycle Detection Algorithm +```java +class ListNode { + int val; + ListNode next; + + ListNode(int val) { + this.val = val; + this.next = null; + } +} + + public class FloydCycleDetection { + public static boolean hasCycle(ListNode head) { + if (head == null || head.next == null) { + return false; // No cycle if head is null or only one node exists + } + + ListNode slow = head; // Slow pointer moves one step at a time + ListNode fast = head; // Fast pointer moves two steps at a time + + while (fast != null && fast.next != null) { + slow = slow.next; // Move slow pointer one step + fast = fast.next.next; // Move fast pointer two steps + + if (slow == fast) { + return true; // Cycle detected if slow and fast pointers meet + } + } + + return false; // No cycle found + } + + public static void main(String[] args) { + // Create a linked list with a cycle + ListNode head = new ListNode(1); + ListNode node2 = new ListNode(2); + ListNode node3 = new ListNode(3); + ListNode node4 = new ListNode(4); + ListNode node5 = new ListNode(5); + + head.next = node2; + node2.next = node3; + node3.next = node4; + node4.next = node5; + node5.next = node2; // Cycle: node5 points back to node2 + + System.out.println("Does the linked list have a cycle? " + hasCycle(head)); + } + } +``` + +#### Kadane's Algorithm + +```java +public class KadanesAlgorithm { + public static int maxSubArraySum(int[] nums) { + int maxSum = nums[0]; // Initialize maxSum with the first element of the array + int currentSum = nums[0]; // Initialize currentSum with the first element of the array + + for (int i = 1; i < nums.length; i++) { + /** + Calc the currentSum for the current element by taking + the maximum of the current element itself or the sum + of the current element and the previous subarray sum + **/ + currentSum = Math.max(nums[i], currentSum + nums[i]); + + /**Update the maxSum with the maximum of the currentSum and the previous maxSum + * + * + **/ + maxSum = Math.max(maxSum, currentSum); + } + + return maxSum; // Return the maximum subarray sum + } + + public static void main(String[] args) { + int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; + int maxSum = maxSubArraySum(nums); + System.out.println("Maximum subarray sum: " + maxSum); + } +} +``` \ No newline at end of file diff --git a/MustKnow/Design Pat/README.md b/MustKnow/Design Pat/README.md new file mode 100644 index 0000000..d570b02 --- /dev/null +++ b/MustKnow/Design Pat/README.md @@ -0,0 +1,8 @@ +### Design Patterns + + +#### Adapter Design Pattern +- Convert An Interface of A Class into Another Interface that clients expect +- Enables us to make incompatible classes work with one another +- i.e. delegate logic to the Adapter +- ![example](https://www.baeldung.com/wp-content/uploads/2019/02/Adapter.png) \ No newline at end of file