4 |
5 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Backtracking/nqueens.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def solveNQueens(self, n):
3 | """
4 | :type n: int
5 | :rtype: List[List[str]]
6 | """
7 | # recusive
8 | if n == 0:
9 | return 0
10 | res = []
11 | board = [['.'] * n for t in range(n)]
12 | self.do_solveNQueens(res, board, n)
13 | return res
14 |
15 | def do_solveNQueens(self, res, board, num):
16 | if num == 0:
17 | res.append([''.join(t) for t in board])
18 | return
19 | ls = len(board)
20 | pos = ls - num
21 | check = [True] * ls
22 | for i in range(pos):
23 | for j in range(ls):
24 | if board[i][j] == 'Q':
25 | check[j] = False
26 | step = pos - i
27 | if j + step < ls:
28 | check[j + step] = False
29 | if j - step >= 0:
30 | check[j - step] = False
31 | break
32 | for j in range(ls):
33 | if check[j]:
34 | board[pos][j] = 'Q'
35 | self.do_solveNQueens(res, board, num - 1)
36 | board[pos][j] = '.'
37 |
38 |
39 | if __name__ == '__main__':
40 | # begin
41 | s = Solution()
42 | print s.solveNQueens(4)
--------------------------------------------------------------------------------
/DYNAMIC PROGRAMMING/c or cpp/BinomialCoefficient.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | int nCk(int n, int k)
5 | {
6 | int C[k+1];
7 | memset(C, 0, sizeof(C));
8 | C[0] = 1; // Base case
9 |
10 | for (int i = 1; i <= n; i++)
11 | { // iteratively build the coefficient
12 | for (int j = min(i, k); j > 0; j--) C[j] = C[j] + C[j-1];
13 | }
14 | return C[k];
15 | }
16 |
17 | int main()
18 | {
19 | int n = 5, k = 2;
20 | cout << "Value of C[" << n << "]["
21 | << k << "] is " << nCk(n, k);
22 | }
23 |
--------------------------------------------------------------------------------
/DYNAMIC PROGRAMMING/c or cpp/CatalanNumbers.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | unsigned long int catalanDP(unsigned int n)
5 | {
6 | unsigned long int catalan[n+1];
7 |
8 | catalan[0] = catalan[1] = 1;
9 |
10 | for (int i=2; i<=n; i++)
11 | {
12 | catalan[i] = 0;
13 | for (int j=0; j
2 | #include
3 |
4 | using std::string;
5 |
6 | int edit_distance(const string &str1, const string &str2) {
7 | using namespace std;
8 | int strl1 = str1.size();
9 | int strl2 = str2.size();
10 |
11 | int dMatrix[strl1][strl2];
12 |
13 | for(int i=0;i> str1 >> str2;
43 | std::cout << edit_distance(str1, str2) << std::endl;
44 | return 0;
45 | }
46 |
--------------------------------------------------------------------------------
/DYNAMIC PROGRAMMING/c or cpp/LongestCommonSubsequence.cpp:
--------------------------------------------------------------------------------
1 | // Refer to the complete problem statement here: https://practice.geeksforgeeks.org/problems/longest-common-subsequence/0
2 |
3 | #include
4 | using namespace std;
5 |
6 | int lcs(string s1, string s2){
7 | int n1=s1.size(),n2=s2.size();
8 | int dp[n1+1][n2+1];
9 | for(int i=0;i<=n1;i++){
10 | for(int j=0;j<=n2;j++){
11 | if(i==0 || j==0)
12 | dp[i][j] = 0;
13 | else{
14 | dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
15 | if(s1[i-1]==s2[j-1])
16 | dp[i][j] = max(dp[i][j], 1+dp[i-1][j-1]);
17 | }
18 | }
19 | }
20 | int res = dp[n1][n2];
21 | }
22 |
23 | int main()
24 | {
25 | int T;
26 | cout<<"Enter number of test cases: ";
27 | cin>>T;
28 | cout<>n1>>n2;
33 | cout<>s1>>s2;
37 | cout<
2 |
3 | using namespace std;
4 |
5 | int max(int a, int b){
6 | int m;
7 | m= (a>b)?a:b;
8 | return m;
9 | }
10 | int main()
11 | {
12 | //int N=6;
13 | //int arr[]={1,2,3,4,5,6};
14 | int N;
15 | int m;
16 | //m=4;
17 | cout<<"Enter number of elements: ";
18 | cin>>N;
19 | int arr[N];
20 | cout<<"\nEnter elements of array: ";
21 | for(int i=0;i>arr[i];
23 | }
24 | cout<<"\nEnter subarray size: ";
25 | cin>>m;
26 | int i=0,j=0,sum=0,Max=-1;
27 | while(j
5 | using namespace std;
6 |
7 | int main() {
8 | int m, n;
9 | cout << "Please enter row and column size.\n";
10 | cin >> m >> n ;
11 | int a[m][n];
12 | cout << "Please enter elements.\n";
13 | for(int i = 0; i < m ;i++){
14 | for(int j = 0; j < n; j++)
15 | cin >> a[i][j];
16 | }
17 | // storing sum across 1st row
18 | for(int i = 1; i < n; i++)
19 | a[0][i] += a[0][i - 1];
20 | // stoing sum across 1st column
21 | for(int i = 1; i < m; i++)
22 | a[i][0] += a[i - 1][0];
23 | for(int i = 1; i < m; i++){
24 | for(int j = 1; j < n; j++){
25 | // taking minimum cost by taking min of left, top and top-left element
26 | a[i][j] += ( min(a[i - 1][j], min( a[i][j - 1], a[i - 1][j - 1] ) ) );
27 | }
28 | }
29 | // value at destination
30 | cout << "Minimum cost : " << a[m-1][n-1] << endl;
31 | return 0;
32 | }
33 |
34 | // Time Complexity : O(mn)
35 | // This is because we use nested loops of m and n to iterate over the original matrix
36 | // to calculate minimum cost.
37 |
38 | // Auxililary Space Complexity : O(1)
--------------------------------------------------------------------------------
/DYNAMIC PROGRAMMING/c or cpp/traveling_salesman_using_dynamic_programming.c:
--------------------------------------------------------------------------------
1 | #include
2 | int a[10][10],completed[10],n,cost=0;
3 | void mincost(int city);
4 | int minValue(int c);
5 | int main()
6 | {
7 | int i,j;
8 | printf("Enter the number of villages: ");
9 | scanf("%d",&n);
10 | printf("\nEnter the Cost Matrix (%dX%d):\n",n,n);
11 | for(i=0;i
5 | using namespace std;
6 |
7 | #define N 1000000007 // prime modulo value
8 |
9 | long int exponentiation(long int base,
10 | long int exp)
11 | {
12 | if (exp == 0)
13 | return 1;
14 |
15 | if (exp == 1)
16 | return base % N;
17 |
18 | long int t = exponentiation(base, exp / 2);
19 | t = (t * t) % N;
20 |
21 | // if exponent is even value
22 | if (exp % 2 == 0)
23 | return t;
24 |
25 | // if exponent is odd value
26 | else
27 | return ((base % N) * t) % N;
28 | }
29 |
30 | // Driver Code
31 | int main()
32 | {
33 | long int base;
34 | long int exp;
35 | cin>>base>>exp;
36 |
37 | long int modulo = exponentiation(base, exp);
38 | cout << modulo << endl;
39 | return 0;
40 | }
41 |
42 |
--------------------------------------------------------------------------------
/EXPONENTIAITION BY SQUARING/c or cpp/modularBinaryExponentiation.cpp:
--------------------------------------------------------------------------------
1 | #include "bits/stdc++.h"
2 | #define ll long long
3 | #define lld long double
4 | #define MOD 1000000007
5 | #define inf 1000000000000000000ll
6 | #define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
7 |
8 | ll power(ll x,ll y, ll md=inf) {
9 | ll res = 1;x%=md;
10 | while(y){
11 | if(y&1)
12 | res = (res*x)%md;
13 | x *= x;
14 | if(x>=md)
15 | x %= md;
16 | y >>= 1;
17 | }
18 | return res;
19 | }
20 |
21 | int main(){
22 | assert(power(3,5)==243);
23 | assert(power(2,15)==32768);
24 | }
25 |
--------------------------------------------------------------------------------
/EXPONENTIAITION BY SQUARING/java/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma)
7 |
--------------------------------------------------------------------------------
/EXPONENTIAITION BY SQUARING/py/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma)
7 | - [Yasasvi V Peruvemba](https://github.com/YasasviPeruvemba)
8 |
--------------------------------------------------------------------------------
/EXPONENTIAITION BY SQUARING/py/ModularExponentiation.py:
--------------------------------------------------------------------------------
1 | def power(a, b, mod):
2 | res = 1
3 | while (b > 0):
4 | if b%2: # if it is not divisible by 2
5 | res = ((res%mod)*(a%mod))%mod
6 | b = int(b/2)
7 | a = ((a%mod)*(a%mod))%mod
8 | return res
9 |
10 | assert (power(5,2,1000000007) == 25)
11 | assert (power(3,7,1000000007) == 2187)
12 |
--------------------------------------------------------------------------------
/GRAPHS/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms/35e6685cfca8d43fbef75dbe78e4527b49be6e17/GRAPHS/.DS_Store
--------------------------------------------------------------------------------
/GRAPHS/c or cpp/Bellman Ford.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | using namespace std ;
4 |
5 | struct Edge {
6 | int src, dest, weight;
7 | };
8 |
9 | struct Graph {
10 | int V, E;
11 | struct Edge* edge;
12 | };
13 |
14 | struct Graph* createGraph(int V, int E)
15 | {
16 | struct Graph* graph = new Graph;
17 | graph->V = V;
18 | graph->E = E;
19 | graph->edge = new Edge[E];
20 | return graph;
21 | }
22 |
23 | void printArr(int dist[], int n)
24 | {
25 | printf("Vertex Distance from Source\n");
26 | for (int i = 0; i < n; ++i)
27 | printf("%d \t\t %d\n", i, dist[i]);
28 | }
29 |
30 | void BellmanFord(struct Graph* graph, int src)
31 | {
32 | int V = graph->V;
33 | int E = graph->E;
34 | int dist[V];
35 |
36 | for (int i = 0; i < V; i++)
37 | dist[i] = INT_MAX;
38 | dist[src] = 0;
39 |
40 | for (int i = 1; i <= V - 1; i++) {
41 | for (int j = 0; j < E; j++) {
42 | int u = graph->edge[j].src;
43 | int v = graph->edge[j].dest;
44 | int weight = graph->edge[j].weight;
45 | if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
46 | dist[v] = dist[u] + weight;
47 | }
48 | }
49 |
50 | for (int i = 0; i < E; i++) {
51 | int u = graph->edge[i].src;
52 | int v = graph->edge[i].dest;
53 | int weight = graph->edge[i].weight;
54 | if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {
55 | printf("Graph contains negative weight cycle");
56 | return;
57 | }
58 | }
59 |
60 | printArr(dist, V);
61 |
62 | return;
63 | }
64 |
65 | int main()
66 | {
67 | int V ;
68 | cout<<"Enter no. of vertices : " ;
69 | cin>>V ;
70 |
71 | int E ;
72 | cout<<"Enter no. of edges : " ;
73 | cin>>E ;
74 |
75 | struct Graph* graph = createGraph(V, E);
76 |
77 | for(int i=0;i>graph->edge[i].src>>graph->edge[i].dest>>graph->edge[i].weight ;
80 | }
81 |
82 | BellmanFord(graph, 0);
83 |
84 | return 0;
85 | }
86 |
--------------------------------------------------------------------------------
/GRAPHS/c or cpp/BreadthFirstSearch.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | class Queue{
5 | public :
6 | int size,Queue[100],i = 0,nice,j;
7 | int front = -1;
8 | int rear = -1;
9 |
10 | void readQueue(int n)
11 | {
12 | size = n;
13 | }
14 |
15 | void enqueue(int element)
16 | {
17 | Queue[i] = element;
18 | i++;
19 | rear++;
20 | }
21 |
22 | int Dequeue(){
23 | if(front < rear){
24 | front++;
25 | return Queue[front];
26 | }
27 | }
28 |
29 | void display(){
30 | cout<<"\n";
31 | if(front == rear){
32 | cout<<"Queue is empty";
33 | }
34 | else{
35 | for(j = front + 1 ; j <= rear ; j++){
36 | cout<>G[i][j];
62 | }
63 | }
64 | }
65 |
66 | void BFS(int f , int n , Queue Q){
67 | int path[50],current,i,j=0;
68 | int visited[n] ={0};
69 | visited[f] = 1;
70 | Q.enqueue(f);
71 | path[j] = f;
72 | j++;
73 |
74 | while(!Q.isEmpty()){
75 | current = Q.Dequeue();
76 | for(i = 0 ; i < n ; i++){
77 | if(G[current][i] == 1 && visited[i] == 0){
78 | visited[i] = 1;
79 | Q.enqueue(i);
80 | path[j] = i;
81 | j++;
82 | }
83 | }
84 | }
85 | cout<<"\n";
86 | cout<<"The BSF path is ->";
87 | for(i = 0 ; i < j ; i++){
88 | cout<<"-->"<>n;
101 | G.readGraph(n);
102 | cout<<"\n";
103 | cout<<"Enter the node you want to start search from";
104 | cin>>node;
105 | G.BFS(node , n ,Q);
106 | }
107 |
108 | /*
109 | Enter no of vertices6
110 | 0 1 0 0 1 0
111 | 1 0 1 1 1 0
112 | 0 1 0 1 0 1
113 | 0 1 1 0 1 1
114 | 1 1 0 1 0 1
115 | 0 0 1 1 1 0
116 |
117 | Enter the node you want to start search from :- 0
118 |
119 | The BSF path is ->-->0-->1-->4-->2-->3-->5
120 | */
121 |
--------------------------------------------------------------------------------
/GRAPHS/c or cpp/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma)
7 | - [Varun Irani](https://github.com/VarunIrani)
8 | - [Mayur Narkhede](https://github.com/PrinceMayur007)
9 | - [Atharva Kulkarni](https://github.com/AK9175)
10 |
--------------------------------------------------------------------------------
/GRAPHS/c or cpp/Graph.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms/35e6685cfca8d43fbef75dbe78e4527b49be6e17/GRAPHS/c or cpp/Graph.cpp
--------------------------------------------------------------------------------
/GRAPHS/c or cpp/PrimsAlgo.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | int main()
3 | {
4 | int n,i,j,m=2,cost=0;
5 | printf("Enter no of vertices you need");
6 | scanf("%d",&n);
7 | printf("\n");
8 | printf("Enter 9999 if no edge exist");
9 | printf("\n");
10 | int G[n][n];
11 | for(i = 0 ; i < n ; i++)
12 | {
13 | for(j = 0 ; j < n ; j++)
14 | {
15 | scanf("%d",&G[i][j]);
16 | }
17 | }
18 |
19 | int u,v,min=999;
20 | for(i = 0 ; i < n ; i++)
21 | {
22 | for(j = i ; j < n ; j++)
23 | {
24 | if(G[i][j] < min)
25 | {
26 | min = G[i][j];
27 | u = i;
28 | v = j;
29 | }
30 | }
31 | }
32 |
33 | cost = cost + G[u][v];
34 |
35 | int visited[n] = {0};
36 | int value[100];
37 | value[0] = u;
38 | value[1] = v;
39 | visited[u] = 1;
40 | visited[v] = 1;
41 | printf("\n");
42 |
43 | for(int z = 1 ; z <= n-2 ; z++)
44 | {
45 | min = 999;
46 | for(i = 0 ; i < n ; i++)
47 | {
48 | for(j = 0 ; j < n ; j++)
49 | {
50 | if(visited[i] != 1 && visited[j] == 1)
51 | {
52 | if(G[i][j] < min)
53 | {
54 | min = G[i][j];
55 | u = j;
56 | v = i;
57 | }
58 | }
59 | }
60 | }
61 | visited[u] = 1;
62 | visited[v] = 1;
63 | value[m] = u;
64 | m++;
65 | value[m] = v;
66 | m++;
67 | cost = cost + G[u][v];
68 | }
69 |
70 | printf("Prims way is : -");
71 | printf("\n");
72 | printf("\n");
73 | int t=1;
74 | for(i = 0 ; i < m ; i++)
75 | {
76 | printf("%d --> ",value[i]);
77 | if(t >= 2)
78 | {
79 | printf("\n");
80 | t = 0;
81 | }
82 | t++;
83 | }
84 |
85 | printf("\n");
86 |
87 | printf("Minimum cost of the spnning tree is :- %d",cost);
88 |
89 | }
90 |
--------------------------------------------------------------------------------
/GRAPHS/c or cpp/WordLadder.cpp:
--------------------------------------------------------------------------------
1 | // https://leetcode.com/problems/word-ladder/
2 |
3 | bool dist(string a, string b){
4 | int count=0;
5 | for(int i=0;i& wordList) {
14 | if(find(wordList.begin(),wordList.end(),endWord)==wordList.end())
15 | return 0;
16 | if(beginWord==endWord) return 1;
17 |
18 | if(dist(beginWord,endWord)) return 2;
19 |
20 | int n=wordList.size();
21 | vector visit(n,false);
22 | queue > q;
23 |
24 | q.push(make_pair(1,beginWord));
25 | while(!q.empty()){
26 |
27 | pair pos=q.front();
28 | q.pop();
29 | int level=pos.first;
30 | if(dist(pos.second,endWord)) return pos.first+1;
31 | level++;
32 | for(int i=0;i
2 | #include
3 | voidmain()
4 | {
5 | int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
6 | int n, value;
7 | int temp, hash;
8 | clrscr();
9 | printf("\nEnter the value of n(table size):");scanf("%d", &n);
10 | do
11 | {
12 | printf("\nEnter the hash value");
13 | scanf("%d", &value);
14 | hash = value % n;
15 | if(a[hash] == 0)
16 | {
17 | a[hash] = value;
18 | printf("\na[%d]the value %d is stored", hash, value);
19 | }
20 | else
21 | {
22 | for(hash++; hash < n; hash++)
23 | {
24 | if(a[hash] == 0)
25 | {
26 | printf("Space is allocated give other value");a[hash] = value;
27 | printf("\n a[%d]the value %d is stored", hash, value);
28 | gotomenu;
29 | }
30 | }
31 | for(hash = 0; hash < n; hash++)
32 | {
33 | if(a[hash] == 0)
34 | {
35 | printf("Space is allocated give other value");a[hash] = value;
36 | printf("\n a[%d]the value %d is stored", hash, value);
37 | gotomenu;
38 | }
39 | }
40 | printf("\n\nERROR\n");
41 | printf("\nEnter '0' and press 'Enter key' twice to exit");
42 | }
43 | menu:
44 | printf("\n Do u want enter more");
45 | scanf("%d", &temp);
46 | }while(temp == 1);
47 | getch();
48 | }
--------------------------------------------------------------------------------
/HASHING/java/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma)
7 |
--------------------------------------------------------------------------------
/HASHING/py/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma)
7 | - [Vivek Ray](https://github.com/vivekray903)
8 |
9 |
--------------------------------------------------------------------------------
/HASHING/py/MD5Hashing.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # Python code to generate MD5 hashing and check their similarity based on Hash
3 |
4 | import hashlib # Supports hashing functions
5 |
6 | message1= str(input("Enter message 1 ="))
7 | message2= str(input("Enter message 2 ="))
8 |
9 | encoding1 = message1.encode()
10 | encoding2 = message2.encode()
11 |
12 | hash1 = (hashlib.md5(encoding1)).hexdigest()
13 | hash2 = (hashlib.md5(encoding2)).hexdigest()
14 |
15 | # Printing the hash in hexadecimal format
16 | print("The byte equivalent of hash for message 1 is : ", hash1)
17 |
18 | # Printing the hash in hexadecimal format
19 | print("The byte equivalent of hash for message 2 is : ", hash2)
20 |
21 | if hash1 == hash2 :
22 | print("The message are similar.")
23 | else:
24 | print("The message are different.")
25 |
--------------------------------------------------------------------------------
/HEAP/c or cpp/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma)
7 |
--------------------------------------------------------------------------------
/HEAP/c or cpp/heap.cpp:
--------------------------------------------------------------------------------
1 | // C++ program for implementation
2 | // of Iterative Heap Sort
3 | #include
4 | using namespace std;
5 |
6 | // function build Max Heap where value
7 | // of each child is always smaller
8 | // than value of their parent
9 | void buildMaxHeap(int arr[], int n)
10 | {
11 | for (int i = 1; i < n; i++)
12 | {
13 | // if child is bigger than parent
14 | if (arr[i] > arr[(i - 1) / 2])
15 | {
16 | int j = i;
17 |
18 | // swap child and parent until
19 | // parent is smaller
20 | while (arr[j] > arr[(j - 1) / 2])
21 | {
22 | swap(arr[j], arr[(j - 1) / 2]);
23 | j = (j - 1) / 2;
24 | }
25 | }
26 | }
27 | }
28 |
29 | void heapSort(int arr[], int n)
30 | {
31 | buildMaxHeap(arr, n);
32 |
33 | for (int i = n - 1; i > 0; i--)
34 | {
35 | // swap value of first indexed
36 | // with last indexed
37 | swap(arr[0], arr[i]);
38 |
39 | // maintaining heap property
40 | // after each swapping
41 | int j = 0, index;
42 |
43 | do
44 | {
45 | index = (2 * j + 1);
46 |
47 | // if left child is smaller than
48 | // right child point index variable
49 | // to right child
50 | if (arr[index] < arr[index + 1] &&
51 | index < (i - 1))
52 | index++;
53 |
54 | // if parent is smaller than child
55 | // then swapping parent with child
56 | // having higher value
57 | if (arr[j] < arr[index] && index < i)
58 | swap(arr[j], arr[index]);
59 |
60 | j = index;
61 |
62 | } while (index < i);
63 | }
64 | }
65 |
66 | // Driver Code to test above
67 | int main()
68 | {
69 | int arr[] = {10, 20, 15, 17, 9, 21};
70 | int n = sizeof(arr) / sizeof(arr[0]);
71 |
72 | printf("Given array: ");
73 | for (int i = 0; i < n; i++)
74 | printf("%d ", arr[i]);
75 |
76 | printf("\n\n");
77 |
78 | heapSort(arr, n);
79 |
80 | // print array after sorting
81 | printf("Sorted array: ");
82 | for (int i = 0; i < n; i++)
83 | printf("%d ", arr[i]);
84 |
85 | return 0;
86 | }
--------------------------------------------------------------------------------
/HEAP/java/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma)
7 |
--------------------------------------------------------------------------------
/HEAP/py/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma)
7 | - [Abhishek kumar](https://github.com/avik001)
8 |
--------------------------------------------------------------------------------
/HEAP/py/heap.py:
--------------------------------------------------------------------------------
1 | class BinaryHeap(object):
2 | def __init__(self):
3 | self.heap = [0]
4 | self.currentSize = 0
5 |
6 | def __repr__(self):
7 | heap = self.heap[1:]
8 | return ' '.join(str(i) for i in heap)
9 |
10 | # for shifting the node up
11 | def shiftUp(self, index):
12 | while (index // 2) > 0:
13 | if self.heap[index] < self.heap[index // 2]: # (currentSize // 2) is the parent
14 | temp = self.heap[index // 2]
15 | self.heap[index // 2] = self.heap[index]
16 | self.heap[index] = temp
17 | index = index // 2
18 |
19 | # to insert a node in the heap
20 | def insert(self, key):
21 | self.heap.append(key)
22 | self.currentSize += 1
23 | self.shiftUp(self.currentSize)
24 |
25 | # for shifting down a node
26 | def shiftDown(self, index):
27 | while(index * 2) <= self.currentSize:
28 | minimumChild = self.minChild(index)
29 | if self.heap[index] > self.heap[minimumChild]:
30 | temp = self.heap[index]
31 | self.heap[index] = self.heap[minimumChild]
32 | self.heap[minimumChild] = temp
33 | index = minimumChild
34 |
35 | # for finding the child with minimum value
36 | def minChild(self,i):
37 | if i * 2 + 1 > self.currentSize:
38 | return i * 2
39 | else:
40 | if self.heap[i * 2] < self.heap[i * 2 + 1]:
41 | return i * 2
42 | else:
43 | return i * 2 + 1
44 |
45 | # for deleting a node from the heap and maintaining the heap property
46 | def delete(self):
47 | deletedNode = self.heap[1]
48 | self.heap[1] = self.heap[self.currentSize]
49 | self.currentSize -= 1
50 | self.heap.pop()
51 | self.shiftDown(1)
52 | return deletedNode
53 |
54 | # for building heap
55 | def buildHeap(self, alist):
56 | i = len(alist) // 2
57 | self.currentSize = len(alist)
58 | self.heap = [0] + alist[:]
59 | while (i > 0):
60 | self.shiftDown(i)
61 | i = i - 1
62 |
63 | bh = BinaryHeap()
64 | bh.buildHeap([9,5,6,2,3])
65 |
66 | print('Deleted:', bh.delete())
67 | print('Deleted:', bh.delete())
68 | print('Deleted:', bh.delete())
69 | bh.insert(3)
70 | print('Deleted:', bh.delete())
71 | print(bh)
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Abstract Classes/App.java:
--------------------------------------------------------------------------------
1 | public class App {
2 |
3 | public static void main(String[] args) {
4 | Camera cam1 = new Camera();
5 | cam1.setId(5);
6 |
7 | Car car1 = new Car();
8 | car1.setId(4);
9 |
10 | car1.run();
11 |
12 | //Machine machine1 = new Machine();
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Abstract Classes/Camera.java:
--------------------------------------------------------------------------------
1 | public class Camera extends Machine {
2 |
3 | @Override
4 | public void start() {
5 | System.out.println("Starting camera.");
6 | }
7 |
8 | @Override
9 | public void doStuff() {
10 | System.out.println("Taking a photo");
11 |
12 | }
13 |
14 | @Override
15 | public void shutdown() {
16 | System.out.println("Shutting down the camera.");
17 |
18 | }
19 |
20 | }
21 |
22 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Abstract Classes/Car.java:
--------------------------------------------------------------------------------
1 | public class Car extends Machine {
2 |
3 | @Override
4 | public void start() {
5 | System.out.println("Starting ignition...");
6 |
7 | }
8 |
9 | @Override
10 | public void doStuff() {
11 | System.out.println("Driving...");
12 | }
13 |
14 | @Override
15 | public void shutdown() {
16 | System.out.println("Switch off ignition.");
17 |
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Abstract Classes/Machine.java:
--------------------------------------------------------------------------------
1 | public abstract class Machine {
2 | private int id;
3 |
4 | public int getId() {
5 | return id;
6 | }
7 |
8 | public void setId(int id) {
9 | this.id = id;
10 | }
11 |
12 | public abstract void start();
13 | public abstract void doStuff();
14 | public abstract void shutdown();
15 |
16 | public void run() {
17 | start();
18 | doStuff();
19 | shutdown();
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/AnonymousClasses.java:
--------------------------------------------------------------------------------
1 | class Machine {
2 | public void start() {
3 | System.out.println("Starting machine ...");
4 | }
5 | }
6 |
7 | interface Plant {
8 | public void grow();
9 | }
10 |
11 | public class AnonymousClasses {
12 |
13 | public static void main(String[] args) {
14 |
15 | // This is equivalent to creating a class that "extends"
16 | // Machine and overrides the start method.
17 | Machine machine1 = new Machine() {
18 | @Override public void start() {
19 | System.out.println("Camera snapping ....");
20 | }
21 | };
22 |
23 | machine1.start();
24 |
25 | // This is equivalent to creating a class that "implements"
26 | // the Plant interface
27 | Plant plant1 = new Plant() {
28 | @Override
29 | public void grow() {
30 | System.out.println("Plant growing");
31 |
32 | }
33 | };
34 |
35 | plant1.grow();
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/ArraysOfStrings.java:
--------------------------------------------------------------------------------
1 | public class ArraysOfStrings {
2 |
3 |
4 | public static void main(String[] args) {
5 |
6 | // Declare array of (references to) strings.
7 | String[] words = new String[3];
8 |
9 | // Set the array elements (point the references
10 | // at strings)
11 | words[0] = "Hello";
12 | words[1] = "to";
13 | words[2] = "you";
14 |
15 | // Access an array element and print it.
16 | System.out.println(words[2]);
17 |
18 | // Simultaneously declare and initialize an array of strings
19 | String[] fruits = {"apple", "banana", "pear", "kiwi"};
20 |
21 | // Iterate through an array
22 | for(String fruit: fruits) {
23 | System.out.println(fruit);
24 | }
25 |
26 | // "Default" value for an integer
27 | int value = 0;
28 |
29 | // Default value for a reference is "null"
30 | String text = null;
31 |
32 | System.out.println(text);
33 |
34 | // Declare an array of strings
35 | String[] texts = new String[2];
36 |
37 | // The references to strings in the array
38 | // are initialized to null.
39 | System.out.println(texts[0]);
40 |
41 | // ... But of course we can set them to actual strings.
42 | texts[0] = "one";
43 | }
44 |
45 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/ArraysProgram.java:
--------------------------------------------------------------------------------
1 | public class ArraysProgram {
2 | public static void main(String[] args) {
3 |
4 | int value = 7;
5 |
6 | int[] values;
7 | values = new int[3];
8 |
9 | System.out.println(values[0]);
10 |
11 | values[0] = 10;
12 | values[1] = 20;
13 | values[2] = 30;
14 |
15 | System.out.println(values[0]);
16 | System.out.println(values[1]);
17 | System.out.println(values[2]);
18 |
19 | for(int i=0; i < values.length; i++) {
20 | System.out.println(values[i]);
21 | }
22 |
23 | int[] numbers = {5, 6, 7};
24 |
25 | for(int i=0; i < numbers.length; i++) {
26 | System.out.println(numbers[i]);
27 | }
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/CastingNumericals.java:
--------------------------------------------------------------------------------
1 | public class CastingNumericals {
2 |
3 | /**
4 | * @param args
5 | */
6 | public static void main(String[] args) {
7 |
8 | byte byteValue = 20;
9 | short shortValue = 55;
10 | int intValue = 888;
11 | long longValue = 23355;
12 |
13 | float floatValue = 8834.8f;
14 | float floatValue2 = (float)99.3;
15 | double doubleValue = 32.4;
16 |
17 | System.out.println(Byte.MAX_VALUE);
18 |
19 | intValue = (int)longValue;
20 |
21 | System.out.println(intValue);
22 |
23 | doubleValue = intValue;
24 | System.out.println(doubleValue);
25 |
26 | intValue = (int)floatValue;
27 | System.out.println(intValue);
28 |
29 |
30 | // The following won't work as we expect it to!!
31 | // 128 is too big for a byte.
32 | byteValue = (byte)128;
33 | System.out.println(byteValue);
34 |
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/ClassesAndObjects.java:
--------------------------------------------------------------------------------
1 |
2 | class Person {
3 |
4 | // Instance variables (data or "state")
5 | String name;
6 | int age;
7 |
8 |
9 | // Classes can contain
10 |
11 | // 1. Data
12 | // 2. Subroutines (methods)
13 | }
14 |
15 |
16 | public class ClassesAndObjects{
17 |
18 | public static void main(String[] args) {
19 |
20 |
21 | // Create a Person object using the Person class
22 | Person person1 = new Person();
23 | person1.name = "Joe Bloggs";
24 | person1.age = 37;
25 |
26 | // Create a second Person object
27 | Person person2 = new Person();
28 | person2.name = "Sarah Smith";
29 | person2.age = 20;
30 |
31 | System.out.println(person1.name);
32 |
33 | }
34 |
35 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Constructors.java:
--------------------------------------------------------------------------------
1 | class Machine {
2 | private String name;
3 | private int code;
4 |
5 | public Machine() {
6 | this("Arnie", 0);
7 |
8 | System.out.println("Constructor running!");
9 | }
10 |
11 | public Machine(String name) {
12 | this(name, 0);
13 |
14 | System.out.println("Second constructor running");
15 | // No longer need following line, since we're using the other constructor above.
16 | //this.name = name;
17 | }
18 |
19 | public Machine(String name, int code) {
20 |
21 | System.out.println("Third constructor running");
22 | this.name = name;
23 | this.code = code;
24 | }
25 | }
26 |
27 | public class Constructors {
28 | public static void main(String[] args) {
29 | Machine machine1 = new Machine();
30 |
31 | Machine machine2 = new Machine("Bertie");
32 |
33 | Machine machine3 = new Machine("Chalky", 7);
34 | }
35 |
36 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/DoWhileLoop.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 |
4 | public class DoWhileLoop {
5 |
6 | public static void main(String[] args) {
7 |
8 |
9 | Scanner scanner = new Scanner(System.in);
10 |
11 |
12 | System.out.println("Enter a number: ");
13 | int value = scanner.nextInt();
14 |
15 | while(value != 5) {
16 | System.out.println("Enter a number: ");
17 | value = scanner.nextInt();
18 | }
19 |
20 |
21 | int value = 0;
22 | do {
23 | System.out.println("Enter a number: ");
24 | value = scanner.nextInt();
25 | }
26 | while(value != 5);
27 |
28 | System.out.println("Got 5!");
29 | }
30 |
31 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Encapsulation.java:
--------------------------------------------------------------------------------
1 | class Plant {
2 |
3 | // Usually only static final members are public
4 | public static final int ID = 7;
5 |
6 | // Instance variables should be declared private,
7 | // or at least protected.
8 | private String name;
9 |
10 | // Only methods intended for use outside the class
11 | // should be public. These methods should be documented
12 | // carefully if you distribute your code.
13 | public String getData() {
14 | String data = "some stuff" + calculateGrowthForecast();
15 |
16 | return data;
17 | }
18 |
19 | // Methods only used the the class itself should
20 | // be private or protected.
21 | private int calculateGrowthForecast() {
22 | return 9;
23 | }
24 |
25 |
26 | public String getName() {
27 | return name;
28 | }
29 |
30 | public void setName(String name) {
31 | this.name = name;
32 | }
33 |
34 |
35 | }
36 |
37 |
38 | public class Encapsulation {
39 |
40 | public static void main(String[] args) {
41 |
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Enum/Animal.java:
--------------------------------------------------------------------------------
1 | public enum Animal {
2 | CAT("Fergus"), DOG("Fido"), MOUSE("Jerry");
3 |
4 | private String name;
5 |
6 | Animal(String name) {
7 | this.name = name;
8 | }
9 |
10 | public String getName() {
11 | return name;
12 | }
13 |
14 | public String toString() {
15 | return "This animal is called: " + name;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Enum/App.java:
--------------------------------------------------------------------------------
1 | public class App {
2 |
3 | public static void main(String[] args) {
4 |
5 | Animal animal = Animal.DOG;
6 |
7 | switch(animal) {
8 | case CAT:
9 | System.out.println("Cat");
10 | break;
11 | case DOG:
12 | System.out.println("Dog");
13 | break;
14 | case MOUSE:
15 | break;
16 | default:
17 | break;
18 |
19 | }
20 |
21 | System.out.println(Animal.DOG);
22 | System.out.println("Enum name as a string: " + Animal.DOG.name());
23 |
24 | System.out.println(Animal.DOG.getClass());
25 |
26 | System.out.println(Animal.DOG instanceof Enum);
27 |
28 | System.out.println(Animal.MOUSE.getName());
29 |
30 | Animal animal2 = Animal.valueOf("CAT");
31 |
32 | System.out.println(animal2);
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/ForLoop.java:
--------------------------------------------------------------------------------
1 | public class ForLoop {
2 | public static void main(String[] args) {
3 |
4 | for(int i=0; i < 5; i++) {
5 | System.out.printf("The value of i is: %dn", i);
6 | }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/GenericsAndWildcards.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 |
3 | class Machine {
4 |
5 | @Override
6 | public String toString() {
7 | return "I am a machine";
8 | }
9 |
10 | public void start() {
11 | System.out.println("Machine starting.");
12 | }
13 |
14 | }
15 |
16 | class Camera extends Machine {
17 | @Override
18 | public String toString() {
19 | return "I am a camera";
20 | }
21 |
22 | public void snap() {
23 | System.out.println("snap!");
24 | }
25 | }
26 |
27 | public class App {
28 |
29 | public static void main(String[] args) {
30 |
31 | ArrayList list1 = new ArrayList();
32 |
33 | list1.add(new Machine());
34 | list1.add(new Machine());
35 |
36 | ArrayList list2 = new ArrayList();
37 |
38 | list2.add(new Camera());
39 | list2.add(new Camera());
40 |
41 | showList(list2);
42 | showList2(list1);
43 | showList3(list1);
44 | }
45 |
46 | public static void showList(ArrayList extends Machine> list) {
47 | for (Machine value : list) {
48 | System.out.println(value);
49 | value.start();
50 | }
51 |
52 | }
53 |
54 | public static void showList2(ArrayList super Camera> list) {
55 | for (Object value : list) {
56 | System.out.println(value);
57 | }
58 | }
59 |
60 | public static void showList3(ArrayList> list) {
61 | for (Object value : list) {
62 | System.out.println(value);
63 | }
64 | }
65 |
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/GetterAndReturnValues.java:
--------------------------------------------------------------------------------
1 | class Person {
2 | String name;
3 | int age;
4 |
5 | void speak() {
6 | System.out.println("My name is: " + name);
7 | }
8 |
9 | int calculateYearsToRetirement() {
10 | int yearsLeft = 65 - age;
11 |
12 | return yearsLeft;
13 | }
14 |
15 | int getAge() {
16 | return age;
17 | }
18 |
19 | String getName() {
20 | return name;
21 | }
22 | }
23 |
24 |
25 | public class GetterAndReturnValues {
26 |
27 | public static void main(String[] args) {
28 | Person person1 = new Person();
29 |
30 | person1.name = "Joe";
31 | person1.age = 25;
32 |
33 | // person1.speak();
34 |
35 | int years = person1.calculateYearsToRetirement();
36 |
37 | System.out.println("Years till retirements " + years);
38 |
39 | int age = person1.getAge();
40 | String name = person1.getName();
41 |
42 | System.out.println("Name is: " + name);
43 | System.out.println("Age is: " + age);
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/GettingUserInput.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class GettingUserInput {
4 | public static void main(String[] args) {
5 |
6 | // Creating scanner object
7 | Scanner input = new Scanner(System.in);
8 |
9 | // Output the prompt
10 | System.out.println("Enter a floating point value: ");
11 |
12 | // enter something.
13 | double value = input.nextDouble();
14 |
15 | //they entered.
16 | System.out.println("You entered: " + value);
17 | }
18 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/HelloWorldprogram.java:
--------------------------------------------------------------------------------
1 | public class HelloWorldprogram
2 | {
3 |
4 | public static void main(String[] args) {
5 | System.out.println("Hello World!");
6 | }
7 |
8 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/IfCondition.java:
--------------------------------------------------------------------------------
1 | public class IfCondition
2 | {
3 | public static void main(String[] args) {
4 |
5 | // Some useful conditions:
6 | System.out.println(5 == 5);
7 | System.out.println(10 != 11);
8 | System.out.println(3 < 6);
9 | System.out.println(10 > 100);
10 |
11 | // Using loops with "break":
12 | int loop = 0;
13 |
14 | while(true) {
15 | System.out.println("Looping: " + loop);
16 |
17 | if(loop == 3) {
18 | break;
19 | }
20 |
21 | loop++;
22 |
23 | System.out.println("Running");
24 | }
25 | }
26 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Inheritance/Car.java:
--------------------------------------------------------------------------------
1 | public class Car extends Machine {
2 |
3 |
4 | @Override
5 | public void start() {
6 | System.out.println("Car started");
7 | }
8 |
9 | public void wipeWindShield() {
10 | System.out.println("Wiping windshield");
11 | }
12 |
13 | public void showInfo() {
14 | System.out.println("Car name: " + name);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Inheritance/IStartable.java:
--------------------------------------------------------------------------------
1 | public interface IStartable {
2 | public void start();
3 | public void stop();
4 | }
5 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Inheritance/Inheritance.java:
--------------------------------------------------------------------------------
1 | public class Inheritance {
2 |
3 | public static void main(String[] args) {
4 | Machine mach1 = new Machine();
5 |
6 | mach1.start();
7 | mach1.stop();
8 |
9 | Car car1 = new Car();
10 |
11 | car1.start();
12 | car1.wipeWindShield();
13 | car1.showInfo();
14 | car1.stop();
15 |
16 |
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Inheritance/Machine.java:
--------------------------------------------------------------------------------
1 | public class Machine {
2 |
3 | protected String name = "Machine Type 1";
4 |
5 | public void start() {
6 | System.out.println("Machine started.");
7 | }
8 |
9 | public void stop() {
10 | System.out.println("Machine stopped.");
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/InnerClasses(Nested)/App.java:
--------------------------------------------------------------------------------
1 | public class App {
2 |
3 |
4 | public static void main(String[] args) {
5 |
6 | Robot robot = new Robot(7);
7 | robot.start();
8 |
9 | // The syntax below will only work if Brain is
10 | // declared public. It is quite unusual to do this.
11 | // Robot.Brain brain = robot.new Brain();
12 | // brain.think();
13 |
14 | // This is very typical Java syntax, using
15 | // a static inner class.
16 | Robot.Battery battery = new Robot.Battery();
17 | battery.charge();
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/InnerClasses(Nested)/Robot.java:
--------------------------------------------------------------------------------
1 | public class Robot {
2 |
3 | private int id;
4 |
5 | // Non-static nested classes have access to the enclosing
6 | // class's instance data. E.g. implement Iterable
7 | // http://www.caveofprogramming.com/java/using-iterable-java-collections-framework-video-tutorial-part-11/
8 | // Use them to group functionality.
9 | private class Brain {
10 | public void think() {
11 | System.out.println("Robot " + id + " is thinking.");
12 | }
13 | }
14 |
15 | // static inner classes do not have access to instance data.
16 | // They are really just like "normal" classes, except that they are grouped
17 | // within an outer class. Use them for grouping classes together.
18 | public static class Battery {
19 | public void charge() {
20 | System.out.println("Battery charging...");
21 | }
22 | }
23 |
24 | public Robot(int id) {
25 | this.id = id;
26 | }
27 |
28 | public void start() {
29 | System.out.println("Starting robot " + id);
30 |
31 | // Use Brain. We don't have an instance of brain
32 | // until we create one. Instances of brain are
33 | // always associated with instances of Robot (the
34 | // enclosing class).
35 | Brain brain = new Brain();
36 | brain.think();
37 |
38 | final String name = "Robert";
39 |
40 | // Sometimes it's useful to create local classes
41 | // within methods. You can use them only within the method.
42 | class Temp {
43 | public void doSomething() {
44 | System.out.println("ID is: " + id);
45 | System.out.println("My name is " + name);
46 | }
47 | }
48 |
49 | Temp temp = new Temp();
50 | temp.doSomething();
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Interfaces/App.java:
--------------------------------------------------------------------------------
1 | public class App {
2 |
3 | public static void main(String[] args) {
4 |
5 | Machine mach1 = new Machine();
6 | mach1.start();
7 |
8 | Person person1 = new Person("Bob");
9 | person1.greet();
10 |
11 | Info info1 = new Machine();
12 | info1.showInfo();
13 |
14 | Info info2 = person1;
15 | info2.showInfo();
16 |
17 | System.out.println();
18 |
19 | outputInfo(mach1);
20 | outputInfo(person1);
21 | }
22 |
23 | private static void outputInfo(Info info) {
24 | info.showInfo();
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Interfaces/Info.java:
--------------------------------------------------------------------------------
1 |
2 | public interface Info {
3 | public void showInfo();
4 | }
5 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Interfaces/Machine.java:
--------------------------------------------------------------------------------
1 | public class Machine implements Info {
2 |
3 | private int id = 7;
4 |
5 | public void start() {
6 | System.out.println("Machine started.");
7 | }
8 |
9 | public void showInfo() {
10 | System.out.println("Machine ID is: " + id);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Interfaces/Person.java:
--------------------------------------------------------------------------------
1 | public class Person implements Info {
2 |
3 | private String name;
4 |
5 | public Person(String name) {
6 | this.name = name;
7 | }
8 |
9 | public void greet() {
10 | System.out.println("Hello there.");
11 | }
12 |
13 | @Override
14 | public void showInfo() {
15 | System.out.println("Person name is: " + name);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/MethodParameters.java:
--------------------------------------------------------------------------------
1 | class Robot {
2 | public void speak(String text) {
3 | System.out.println(text);
4 | }
5 |
6 | public void jump(int height) {
7 | System.out.println("Jumping: " + height);
8 | }
9 |
10 | public void move(String direction, double distance) {
11 | System.out.println("Moving " + distance + " in direction " + direction);
12 | }
13 | }
14 |
15 | public class MethodParameters {
16 |
17 | public static void main(String[] args) {
18 | Robot sam = new Robot();
19 |
20 | sam.speak("Hi I'm Sam");
21 | sam.jump(7);
22 |
23 | sam.move("West", 12.2);
24 |
25 | String greeting = "Hello there";
26 | sam.speak(greeting);
27 |
28 | int value = 14;
29 | sam.jump(value);
30 |
31 | }
32 |
33 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/MethodsInClasses.java:
--------------------------------------------------------------------------------
1 | class Person {
2 |
3 | // Instance variables (data or "state")
4 | String name;
5 | int age;
6 |
7 | // Classes can contain
8 |
9 | // 1. Data
10 | // 2. Subroutines (methods)
11 |
12 | void speak() {
13 | for(int i=0; i<3; i++) {
14 | System.out.println("My name is: " + name + " and I am " + age + " years old ");
15 | }
16 | }
17 |
18 | void sayHello() {
19 | System.out.println("Hello there!");
20 | }
21 | }
22 |
23 | public class MethodsInClasses {
24 |
25 | public static void main(String[] args) {
26 |
27 | // Create a Person object using the Person class
28 | Person person1 = new Person();
29 | person1.name = "Joe Bloggs";
30 | person1.age = 37;
31 | person1.speak();
32 | person1.sayHello();
33 |
34 | // Create a second Person object
35 | Person person2 = new Person();
36 | person2.name = "Sarah Smith";
37 | person2.age = 20;
38 | person2.speak();
39 | person1.sayHello();
40 |
41 | System.out.println(person1.name);
42 |
43 | }
44 |
45 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/MultiDimensionalArrays.java:
--------------------------------------------------------------------------------
1 | public class MultiDimensionalArrays {
2 |
3 | public static void main(String[] args) {
4 |
5 |
6 | int[] values = {3, 5, 2343};
7 |
8 |
9 | System.out.println(values[2]);
10 |
11 |
12 | int[][] grid = {
13 | {3, 5, 2343},
14 | {2, 4},
15 | {1, 2, 3, 4}
16 | };
17 |
18 |
19 | System.out.println(grid[1][1]);
20 | System.out.println(grid[0][2]);
21 |
22 |
23 | String[][] texts = new String[2][3];
24 |
25 | texts[0][1] = "Hello there";
26 |
27 | System.out.println(texts[0][1]);
28 |
29 |
30 | for(int row=0; row < grid.length; row++) {
31 | for(int col=0; col < grid[row].length; col++) {
32 | System.out.print(grid[row][col] + "\t");
33 | }
34 |
35 | System.out.println();
36 | }
37 |
38 |
39 | String[][] words = new String[2][];
40 |
41 |
42 | System.out.println(words[0]);
43 |
44 |
45 | words[0] = new String[3];
46 |
47 |
48 | words[0][1] = "hi there";
49 |
50 | System.out.println(words[0][1]);
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/MultipleExceptions/App.java:
--------------------------------------------------------------------------------
1 | import java.io.FileNotFoundException;
2 | import java.io.IOException;
3 | import java.text.ParseException;
4 |
5 | public class App {
6 |
7 | public static void main(String[] args) {
8 | Test test = new Test();
9 |
10 | // Multiple catch blocks
11 | try {
12 | test.run();
13 | } catch (IOException e) {
14 | // TODO Auto-generated catch block
15 | e.printStackTrace();
16 | } catch (ParseException e) {
17 | System.out.println("Couldn't parse command file.");
18 | }
19 |
20 | // Try multi-catch (Java 7+ only)
21 | try {
22 | test.run();
23 | } catch (IOException | ParseException e) {
24 | // TODO Auto-generated catch block
25 | e.printStackTrace();
26 | }
27 |
28 | // Using polymorphism to catch the parent of all exceptions
29 | try {
30 | test.run();
31 | } catch (Exception e) {
32 | // TODO Auto-generated catch block
33 | e.printStackTrace();
34 | }
35 |
36 | // Important to catch exceptions in the right order!
37 | // IOException cannot come first, because it's the parent
38 | // of FileNotFoundException, so would catch both exceptions
39 | // in this case.
40 | try {
41 | test.input();
42 | } catch (FileNotFoundException e) {
43 | // TODO Auto-generated catch block
44 | e.printStackTrace();
45 | } catch (IOException e) {
46 | // TODO Auto-generated catch block
47 | e.printStackTrace();
48 | }
49 |
50 |
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/MultipleExceptions/Test.java:
--------------------------------------------------------------------------------
1 | import java.io.FileNotFoundException;
2 | import java.io.IOException;
3 | import java.text.ParseException;
4 |
5 |
6 | public class Test {
7 | public void run() throws IOException, ParseException {
8 |
9 |
10 | //throw new IOException();
11 |
12 | throw new ParseException("Error in command list.", 2);
13 |
14 |
15 | }
16 |
17 | public void input() throws IOException, FileNotFoundException {
18 |
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Packages/Algae.java:
--------------------------------------------------------------------------------
1 | package ocean.plants;
2 |
3 | public class Algae {
4 |
5 | }
6 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Packages/App.java:
--------------------------------------------------------------------------------
1 | import ocean.Fish;
2 | import ocean.plants.Seaweed;
3 |
4 | public class App {
5 |
6 |
7 | public static void main(String[] args) {
8 | Fish fish = new Fish();
9 | Seaweed weed = new Seaweed();
10 | }
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Packages/Fish.java:
--------------------------------------------------------------------------------
1 | package ocean;
2 |
3 | public class Fish {
4 |
5 | }
6 |
7 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Packages/Seaweed.java:
--------------------------------------------------------------------------------
1 | package ocean.plants;
2 |
3 | public class Seaweed {
4 |
5 | }
6 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/PassingByValue/App.java:
--------------------------------------------------------------------------------
1 | public class App {
2 |
3 |
4 | public static void main(String[] args) {
5 | App app = new App();
6 |
7 | //===========================================
8 |
9 | int value = 7;
10 | System.out.println("1. Value is: " + value);
11 |
12 | app.show(value);
13 |
14 | System.out.println("4. Value is: " + value);
15 |
16 | //===========================================
17 | System.out.println();
18 |
19 | Person person = new Person("Bob");
20 | System.out.println("1. Person is: " + person);
21 |
22 | app.show(person);
23 |
24 | System.out.println("4. Person is: " + person);
25 | }
26 |
27 | public void show(int value) {
28 | System.out.println("2. Value is: " + value);
29 |
30 | value = 8;
31 |
32 | System.out.println("3. Value is: " + value);
33 | }
34 |
35 | public void show(Person person) {
36 | System.out.println("2. Person is: " + person);
37 |
38 |
39 |
40 | person = new Person("Mike");
41 | person.setName("Sue");
42 |
43 | System.out.println("3. Person is: " + person);
44 |
45 | }
46 |
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/PassingByValue/Person.java:
--------------------------------------------------------------------------------
1 | public class Person {
2 | private String name;
3 |
4 | public Person(String name) {
5 | this.name = name;
6 | }
7 |
8 | public String getName() {
9 | return name;
10 | }
11 |
12 | public void setName(String name) {
13 | this.name = name;
14 | }
15 |
16 | @Override
17 | public String toString() {
18 | return "Person [name=" + name + "]";
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Polymorphism/App.java:
--------------------------------------------------------------------------------
1 | public class App {
2 |
3 | public static void main(String[] args) {
4 |
5 |
6 | Plant plant1 = new Plant();
7 |
8 | // Tree is a kind of Plant (it extends Plant)
9 | Tree tree = new Tree();
10 |
11 | // Polymorphism guarantees that we can use a child class
12 | // wherever a parent class is expected.
13 | Plant plant2 = tree;
14 |
15 | // plant2 references a Tree, so the Tree grow() method is called.
16 | plant2.grow();
17 |
18 | // The type of the reference decided what methods you can actually call;
19 | // we need a Tree-type reference to call tree-specific methods.
20 | tree.shedLeaves();
21 |
22 | // ... so this won't work.
23 | //plant2.shedLeaves();
24 |
25 | // Another example of polymorphism.
26 | doGrow(tree);
27 | }
28 |
29 | public static void doGrow(Plant plant) {
30 | plant.grow();
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Polymorphism/Plant.java:
--------------------------------------------------------------------------------
1 | public class Plant {
2 | public void grow() {
3 | System.out.println("Plant growing");
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Polymorphism/Tree.java:
--------------------------------------------------------------------------------
1 | public class Tree extends Plant {
2 |
3 | @Override
4 | public void grow() {
5 | System.out.println("Tree growing");
6 | }
7 |
8 | public void shedLeaves() {
9 | System.out.println("Leaves shedding.");
10 | }
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Public,Private,Protected/App.java:
--------------------------------------------------------------------------------
1 | import world.Plant;
2 |
3 | /*
4 | * private --- only within same class
5 | * public --- from anywhere
6 | * protected -- same class, subclass, and same package
7 | * no modifier -- same package only
8 | */
9 |
10 | public class App {
11 |
12 | public static void main(String[] args) {
13 | Plant plant = new Plant();
14 |
15 | System.out.println(plant.name);
16 |
17 | System.out.println(plant.ID);
18 |
19 | // Won't work --- type is private
20 | //System.out.println(plant.type);
21 |
22 | // size is protected; App is not in the same package as Plant.
23 | // Won't work
24 | // System.out.println(plant.size);
25 |
26 | // Won't work; App and Plant in different packages, height has package-level visibility.
27 | //System.out.println(plant.height);
28 |
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Public,Private,Protected/Field.java:
--------------------------------------------------------------------------------
1 | package world;
2 |
3 | public class Field {
4 | private Plant plant = new Plant();
5 |
6 | public Field() {
7 |
8 | // size is protected; Field is in the same package as Plant.
9 | System.out.println(plant.size);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Public,Private,Protected/Grass.java:
--------------------------------------------------------------------------------
1 | import world.Plant;
2 |
3 |
4 | public class Grass extends Plant {
5 | public Grass() {
6 |
7 | // Won't work --- Grass not in same package as plant, even though it's a subclass
8 | // System.out.println(this.height);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Public,Private,Protected/Oak.java:
--------------------------------------------------------------------------------
1 | package world;
2 |
3 | public class Oak extends Plant {
4 |
5 | public Oak() {
6 |
7 | // Won't work -- type is private
8 | // type = "tree";
9 |
10 | // This works --- size is protected, Oak is a subclass of plant.
11 | this.size = "large";
12 |
13 | // No access specifier; works because Oak and Plant in same package
14 | this.height = 10;
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Public,Private,Protected/Plant.java:
--------------------------------------------------------------------------------
1 | package world;
2 |
3 | class Something {
4 |
5 | }
6 |
7 | public class Plant {
8 | // Bad practice
9 | public String name;
10 |
11 | // Accepetable practice --- it's final.
12 | public final static int ID = 8;
13 |
14 | private String type;
15 |
16 | protected String size;
17 |
18 | int height;
19 |
20 | public Plant() {
21 | this.name = "Freddy";
22 | this.type = "plant";
23 | this.size = "medium";
24 | this.height = 8;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/ReadingFiles.java:
--------------------------------------------------------------------------------
1 | import java.io.File;
2 | import java.io.FileNotFoundException;
3 | import java.util.Scanner;
4 |
5 |
6 | public class ReadingFiles {
7 |
8 | public static void main(String[] args) throws FileNotFoundException {
9 | //String fileName = "C:/Users/John/Desktop/example.txt";
10 | String fileName = "example.txt";
11 |
12 | File textFile = new File(fileName);
13 |
14 | Scanner in = new Scanner(textFile);
15 |
16 | int value = in.nextInt();
17 | System.out.println("Read value: " + value);
18 |
19 | in.nextLine();
20 |
21 | int count = 2;
22 | while(in.hasNextLine()) {
23 | String line = in.nextLine();
24 |
25 | System.out.println(count + ": " + line);
26 | count++;
27 | }
28 |
29 | in.close();
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/ReadingFileswithFileReader.java:
--------------------------------------------------------------------------------
1 |
2 | import java.io.BufferedReader;
3 | import java.io.File;
4 | import java.io.FileNotFoundException;
5 | import java.io.FileReader;
6 | import java.io.IOException;
7 |
8 |
9 | public class ReadingFileswithFileReader{
10 |
11 | public static void main(String[] args) {
12 |
13 | File file = new File("test.txt");
14 |
15 | BufferedReader br = null;
16 |
17 | try {
18 | FileReader fr = new FileReader(file);
19 | br = new BufferedReader(fr);
20 |
21 | String line;
22 |
23 | while( (line = br.readLine()) != null ) {
24 | System.out.println(line);
25 | }
26 |
27 | } catch (FileNotFoundException e) {
28 | System.out.println("File not found: " + file.toString());
29 | } catch (IOException e) {
30 | System.out.println("Unable to read file: " + file.toString());
31 | }
32 | finally {
33 | try {
34 | br.close();
35 | } catch (IOException e) {
36 | System.out.println("Unable to close file: " + file.toString());
37 | }
38 | catch(NullPointerException ex) {
39 | // File was probably never opened!
40 | }
41 | }
42 |
43 |
44 |
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Recursion.java:
--------------------------------------------------------------------------------
1 | public class Recursion {
2 |
3 |
4 | public static void main(String[] args) {
5 |
6 | // E.g. 4! = 4*3*2*1 (factorial 4)
7 |
8 | System.out.println(factorial(5));
9 | }
10 |
11 | private static int factorial(int value) {
12 | //System.out.println(value);
13 |
14 | if(value == 1) {
15 | return 1;
16 | }
17 |
18 | return factorial(value - 1) * value;
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/RuntimeExceptions.java:
--------------------------------------------------------------------------------
1 | public class RuntimeExceptions {
2 |
3 | public static void main(String[] args) {
4 |
5 | // Null pointer exception ....
6 | String text = null;
7 |
8 | System.out.println(text.length());
9 |
10 | // Arithmetic exception ... (divide by zero)
11 | int value = 7/0;
12 |
13 | // You can actually handle RuntimeExceptions if you want to;
14 | // for example, here we handle an ArrayIndexOutOfBoundsException
15 | String[] texts = { "one", "two", "three" };
16 |
17 | try {
18 | System.out.println(texts[3]);
19 | } catch (ArrayIndexOutOfBoundsException e) {
20 | System.out.println(e.toString());
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Serialization/Person.java:
--------------------------------------------------------------------------------
1 | import java.io.Serializable;
2 |
3 | public class Person implements Serializable {
4 |
5 | private static final long serialVersionUID = 4801633306273802062L;
6 |
7 | private int id;
8 | private String name;
9 |
10 | public Person(int id, String name) {
11 | this.id = id;
12 | this.name = name;
13 | }
14 |
15 | @Override
16 | public String toString() {
17 | return "Person [id=" + id + ", name=" + name + "]";
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Serialization/ReadObjects.java:
--------------------------------------------------------------------------------
1 | import java.io.FileInputStream;
2 | import java.io.FileNotFoundException;
3 | import java.io.IOException;
4 | import java.io.ObjectInputStream;
5 |
6 |
7 |
8 | public class ReadObjects {
9 |
10 |
11 | public static void main(String[] args) {
12 | System.out.println("Reading objects...");
13 |
14 | try(FileInputStream fi = new FileInputStream("people.bin")) {
15 |
16 | ObjectInputStream os = new ObjectInputStream(fi);
17 |
18 | Person person1 = (Person)os.readObject();
19 | Person person2 = (Person)os.readObject();
20 |
21 | os.close();
22 |
23 | System.out.println(person1);
24 | System.out.println(person2);
25 |
26 | } catch (FileNotFoundException e) {
27 | // TODO Auto-generated catch block
28 | e.printStackTrace();
29 | } catch (IOException e) {
30 | // TODO Auto-generated catch block
31 | e.printStackTrace();
32 | } catch (ClassNotFoundException e) {
33 | // TODO Auto-generated catch block
34 | e.printStackTrace();
35 | }
36 |
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/Serialization/WriteObjects.java:
--------------------------------------------------------------------------------
1 | import java.io.FileNotFoundException;
2 | import java.io.FileOutputStream;
3 | import java.io.IOException;
4 | import java.io.ObjectOutputStream;
5 |
6 |
7 |
8 | public class WriteObjects {
9 |
10 | public static void main(String[] args) {
11 | System.out.println("Writing objects...");
12 |
13 | Person mike = new Person(543, "Mike");
14 | Person sue = new Person(123, "Sue");
15 |
16 | System.out.println(mike);
17 | System.out.println(sue);
18 |
19 | try(FileOutputStream fs = new FileOutputStream("people.bin")) {
20 |
21 | ObjectOutputStream os = new ObjectOutputStream(fs);
22 |
23 | os.writeObject(mike);
24 | os.writeObject(sue);
25 |
26 | os.close();
27 |
28 | } catch (FileNotFoundException e) {
29 | // TODO Auto-generated catch block
30 | e.printStackTrace();
31 | } catch (IOException e) {
32 | // TODO Auto-generated catch block
33 | e.printStackTrace();
34 | }
35 |
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/SetterAndThis.java:
--------------------------------------------------------------------------------
1 | class Frog {
2 | private String name;
3 | private int age;
4 |
5 | public void setName(String name) {
6 | this.name = name;
7 | }
8 |
9 | public void setAge(int age) {
10 | this.age = age;
11 | }
12 |
13 | public String getName() {
14 | return name;
15 | }
16 |
17 | public int getAge() {
18 | return age;
19 | }
20 |
21 | public void setInfo(String name, int age) {
22 | setName(name);
23 | setAge(age);
24 | }
25 | }
26 |
27 | public class SetterAndThis {
28 |
29 | public static void main(String[] args) {
30 |
31 | Frog frog1 = new Frog();
32 |
33 | //frog1.name = "Bertie";
34 | //frog1.age = 1;
35 |
36 | frog1.setName("Bertie");
37 | frog1.setAge(1);
38 |
39 | System.out.println(frog1.getName());
40 | }
41 |
42 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/StaticAndFinal.java:
--------------------------------------------------------------------------------
1 | class Thing {
2 | public final static int LUCKY_NUMBER = 7;
3 |
4 | public String name;
5 | public static String description;
6 |
7 | public static int count = 0;
8 |
9 | public int id;
10 |
11 | public Thing() {
12 |
13 | id = count;
14 |
15 | count++;
16 | }
17 |
18 | public void showName() {
19 | System.out.println("Object id: " + id + ", " + description + ": " + name);
20 | }
21 |
22 | public static void showInfo() {
23 | System.out.println(description);
24 | // Won't work: System.out.println(name);
25 | }
26 | }
27 |
28 |
29 | public class StaticAndFinal {
30 |
31 | public static void main(String[] args) {
32 |
33 | Thing.description = "I am a thing";
34 |
35 | Thing.showInfo();
36 |
37 | System.out.println("Before creating objects, count is: " + Thing.count);
38 |
39 | Thing thing1 = new Thing();
40 | Thing thing2 = new Thing();
41 |
42 | System.out.println("After creating objects, count is: " + Thing.count);
43 |
44 | thing1.name = "Bob";
45 | thing2.name = "Sue";
46 |
47 | thing1.showName();
48 | thing2.showName();
49 |
50 | System.out.println(Math.PI);
51 |
52 | System.out.println(Thing.LUCKY_NUMBER);
53 | }
54 |
55 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/SwitchCase.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class SwitchCase{
4 |
5 | public static void main(String[] args) {
6 |
7 | Scanner input = new Scanner(System.in);
8 |
9 | System.out.println("Please enter a command: ");
10 | String text = input.nextLine();
11 |
12 | switch (text) {
13 | case "start":
14 | System.out.println("Machine started!");
15 | break;
16 |
17 | case "stop":
18 | System.out.println("Machine stopped.");
19 | break;
20 |
21 | default:
22 | System.out.println("Command not recognized");
23 | }
24 | }
25 |
26 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/ToStringMethods.java:
--------------------------------------------------------------------------------
1 | class Frog {
2 |
3 | private int id;
4 | private String name;
5 |
6 | public Frog(int id, String name) {
7 | this.id = id;
8 | this.name = name;
9 | }
10 |
11 | public String toString() {
12 |
13 | return String.format("%-4d: %s", id, name);
14 |
15 | /*
16 | StringBuilder sb = new StringBuilder();
17 | sb.append(id).append(": ").append(name);
18 |
19 | return sb.toString();
20 | */
21 | }
22 | }
23 |
24 | public class ToStringMethods {
25 |
26 | public static void main(String[] args) {
27 | Frog frog1 = new Frog(7, "Freddy");
28 | Frog frog2 = new Frog(5, "Roger");
29 |
30 | System.out.println(frog1);
31 | System.out.println(frog2);
32 | }
33 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/TryWithResources/App.java:
--------------------------------------------------------------------------------
1 | class Temp implements AutoCloseable {
2 |
3 | @Override
4 | public void close() throws Exception {
5 | System.out.println("Closing!");
6 | throw new Exception("oh no!");
7 | }
8 |
9 | }
10 |
11 |
12 | public class App {
13 |
14 | public static void main(String[] args) {
15 |
16 | try(Temp temp = new Temp()) {
17 |
18 | } catch (Exception e) {
19 | // TODO Auto-generated catch block
20 | e.printStackTrace();
21 | }
22 |
23 |
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/TryWithResources/App2.java:
--------------------------------------------------------------------------------
1 | import java.io.BufferedReader;
2 | import java.io.File;
3 | import java.io.FileNotFoundException;
4 | import java.io.FileReader;
5 | import java.io.IOException;
6 |
7 | public class App2 {
8 |
9 | public static void main(String[] args) {
10 | File file = new File("test.txt");
11 |
12 | try (BufferedReader br = new BufferedReader(new FileReader(file))) {
13 | String line;
14 |
15 | while ((line = br.readLine()) != null) {
16 | System.out.println(line);
17 | }
18 | } catch (FileNotFoundException e) {
19 | System.out.println("Can't find file " + file.toString());
20 | } catch (IOException e) {
21 | System.out.println("Unable to read file " + file.toString());
22 | }
23 |
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/UpcastingAndDowncasting.java:
--------------------------------------------------------------------------------
1 | class Machine {
2 | public void start() {
3 | System.out.println("Machine started.");
4 | }
5 | }
6 |
7 | class Camera extends Machine {
8 | public void start() {
9 | System.out.println("Camera started.");
10 | }
11 |
12 | public void snap() {
13 | System.out.println("Photo taken.");
14 | }
15 | }
16 |
17 |
18 | public class UpcastingAndDowncasting {
19 | public static void main(String[] args) {
20 |
21 | Machine machine1 = new Machine();
22 | Camera camera1 = new Camera();
23 |
24 | machine1.start();
25 | camera1.start();
26 | camera1.snap();
27 |
28 | // Upcasting
29 | Machine machine2 = camera1;
30 | machine2.start();
31 | // error: machine2.snap();
32 |
33 | // Downcasting
34 | Machine machine3 = new Camera();
35 | Camera camera2 = (Camera)machine3;
36 | camera2.start();
37 | camera2.snap();
38 |
39 | // Doesn't work --- runtime error.
40 | Machine machine4 = new Machine();
41 | // Camera camera3 = (Camera)machine4;
42 | // camera3.start();
43 | // camera3.snap();
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/UsingGenerics.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.HashMap;
3 |
4 | class Animal {
5 |
6 | }
7 |
8 |
9 | public class UsingGenerics {
10 |
11 | public static void main(String[] args) {
12 |
13 | /////////////////// Before Java 5 ////////////////////////
14 | ArrayList list = new ArrayList();
15 |
16 | list.add("apple");
17 | list.add("banana");
18 | list.add("orange");
19 |
20 | String fruit = (String)list.get(1);
21 |
22 | System.out.println(fruit);
23 |
24 | /////////////// Modern style //////////////////////////////
25 |
26 | ArrayList strings = new ArrayList();
27 |
28 | strings.add("cat");
29 | strings.add("dog");
30 | strings.add("alligator");
31 |
32 | String animal = strings.get(1);
33 |
34 | System.out.println(animal);
35 |
36 |
37 | ///////////// There can be more than one type argument ////////////////////
38 |
39 | HashMap map = new HashMap();
40 |
41 |
42 | //////////// Java 7 style /////////////////////////////////
43 |
44 | ArrayList someList = new ArrayList<>();
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/UsingStrings.java:
--------------------------------------------------------------------------------
1 | public class UsingStrings {
2 | public static void main(String[] args) {
3 |
4 | int myInt = 7;
5 |
6 | String text = "Hello";
7 |
8 | String blank = " ";
9 |
10 | String name = "Bob";
11 |
12 | String greeting = text + blank + name;
13 |
14 | System.out.println(greeting);
15 |
16 | System.out.println("Hello" + " " + "Bob");
17 |
18 | System.out.println("My integer is: " + myInt);
19 |
20 | double myDouble = 7.8;
21 |
22 | System.out.println("My number is: " + myDouble + ".");
23 | }
24 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/UsingVariables.java:
--------------------------------------------------------------------------------
1 | public class UsingVariables {
2 |
3 | public static void main(String[] args) {
4 | int myNumber = 88;
5 | short myShort = 847;
6 | long myLong = 9797;
7 |
8 | double myDouble = 7.3243;
9 | float myFloat = 324.3f;
10 |
11 | char myChar = 'y';
12 | boolean myBoolean = false;
13 |
14 | byte myByte = 127;
15 |
16 |
17 | System.out.println(myNumber);
18 | System.out.println(myShort);
19 | System.out.println(myLong);
20 | System.out.println(myDouble);
21 | System.out.println(myFloat);
22 | System.out.println(myChar);
23 | System.out.println(myBoolean);
24 | System.out.println(myByte);
25 | }
26 |
27 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/WhileLoop.java:
--------------------------------------------------------------------------------
1 | public class WhileLoop {
2 | public static void main(String[] args) {
3 |
4 | int value = 0;
5 |
6 | while(value < 10)
7 | {
8 | System.out.println("Hello " + value);
9 |
10 | value = value + 1;
11 | }
12 | }
13 | }
--------------------------------------------------------------------------------
/Java Basics/Basics_of_java/WritingTextFiles.java:
--------------------------------------------------------------------------------
1 | import java.io.BufferedWriter;
2 | import java.io.File;
3 | import java.io.FileWriter;
4 | import java.io.IOException;
5 |
6 |
7 | public class WritingTextFiles {
8 |
9 |
10 | public static void main(String[] args) {
11 | File file = new File("test.txt");
12 |
13 | try (BufferedWriter br = new BufferedWriter(new FileWriter(file))) {
14 | br.write("This is line one");
15 | br.newLine();
16 | br.write("This is line two");
17 | br.newLine();
18 | br.write("Last line.");
19 | } catch (IOException e) {
20 | System.out.println("Unable to read file " + file.toString());
21 | }
22 |
23 |
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/Java Basics/README.md.txt:
--------------------------------------------------------------------------------
1 | This folder contains all the basics of java programming for the beginners.
2 | All the basics of java with code in the given folder.
--------------------------------------------------------------------------------
/LINKED LIST/c or cpp/CircularLinkedList.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | class Node{
5 | public:
6 | int data;
7 | Node* next;
8 | };
9 |
10 | //Traversing through the circular linked list
11 | void circular_ll_traversal(Node* head){
12 | Node* p = head;
13 | do{
14 | cout<data<<" ";
15 | p=p->next;
16 | }while(p!=head);
17 | }
18 | //Inserting at first
19 | Node* insertAtFirst(Node* head, int data){
20 | Node* zero = new Node();
21 | zero->data=data;
22 |
23 | Node* p=head;
24 | while(p->next!=head){
25 | p=p->next;
26 | }
27 | p->next = zero;
28 | zero->next = head;
29 | head= zero;
30 | return head;
31 |
32 | }
33 | //Inserting at the last
34 | Node* insertAtLast(Node* head,int data){
35 | Node* sixth = new Node();
36 | sixth->data=data;
37 |
38 | Node* p = head;
39 | while(p->next!=head){
40 | p=p->next;
41 | }
42 | p->next=sixth;
43 | sixth->next=head;
44 | return head;
45 |
46 | }
47 | //Inserting at a specific index
48 | Node* InsertAtIndex(Node* head,int data,int index){
49 | Node* between = new Node();
50 | between->data=data;
51 | int i=0;
52 | Node* p=head;
53 | while(i!=index-1){
54 | p=p->next;
55 | i++;
56 | }
57 | between->next = p->next;
58 | p->next = between;
59 | return head;
60 |
61 | }
62 |
63 |
64 | int main(){
65 | Node* head=new Node();
66 | Node* second =new Node();
67 | Node* third =new Node();
68 | Node* fourth =new Node();
69 | Node* fifth =new Node();
70 |
71 | head->data=23;
72 | head->next=second;
73 |
74 | second->data=12;
75 | second->next=third;
76 |
77 | third->data=34;
78 | third->next=fourth;
79 |
80 | fourth->data=56;
81 | fourth->next=fifth;
82 |
83 | fifth->data=90;
84 | fifth->next=head;
85 |
86 | cout<<"Circular linked list before Insertion\n";
87 | circular_ll_traversal(head);
88 | cout<<"\n";
89 |
90 | //head=insertAtFirst(head, 45);
91 | //cout<<"\n";
92 | //circular_ll_traversal(head);
93 |
94 | //head = insertAtLast(head,53);
95 | head = InsertAtIndex(head,44,3);
96 |
97 | cout<<"Circular linked list after Insertion\n";
98 | circular_ll_traversal(head);
99 | cout<<"\n";
100 |
101 | return 0;
102 |
103 | }
104 |
--------------------------------------------------------------------------------
/LINKED LIST/c or cpp/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma)
7 | - [Taniya Kulkarni](https://github.com/taniyask)
8 | - [Akshita Sharma](https://github.com/Akshitasharma01)
9 | - [Mayur Narkhede](https://github.com/PrinceMayur007)
10 | - [Ashutosh Pandey](https://github.com/DataCrusade1999)
11 | - [Ananthakrishnan Nair RS](https://github.com/akrish4)
12 |
--------------------------------------------------------------------------------
/LINKED LIST/c or cpp/Doubly_linked_list.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 | struct Node {
4 | int data;
5 | struct Node *prev;
6 | struct Node *next;
7 | };
8 | struct Node* head = NULL;
9 | void insert(int newdata) {
10 | struct Node* newnode = (struct Node*) malloc(sizeof(struct Node));
11 | newnode->data = newdata;
12 | newnode->prev = NULL;
13 | newnode->next = head;
14 | if(head != NULL)
15 | head->prev = newnode ;
16 | head = newnode;
17 | }
18 | void display() {
19 | struct Node* ptr;
20 | ptr = head;
21 | while(ptr != NULL) {
22 | cout<< ptr->data <<" ";
23 | ptr = ptr->next;
24 | }
25 | }
26 | int main() {
27 | insert(3);
28 | insert(1);
29 | insert(7);
30 | insert(2);
31 | insert(9);
32 | cout<<"The doubly linked list is: ";
33 | display();
34 | return 0;
35 | }
--------------------------------------------------------------------------------
/LINKED LIST/c or cpp/Intersection.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include "dll.h"
4 | //Author: Taniya Kulkarni
5 |
6 | struct node *list3 = NULL;
7 |
8 | void intersection (struct node *head1, struct node *head2)
9 | {
10 | isempty(head1);
11 | isempty(head2);
12 | if( head1 != NULL && head2 != NULL)
13 | {
14 | struct node *temp1 = head1;
15 | while (temp1 != NULL)
16 | {
17 | struct node *temp2 = head2;
18 | while (temp2 != NULL)
19 | {
20 | if(temp2->num == temp1->num)
21 | {
22 | insert_end (temp1->num, &list3);
23 | }
24 | temp2 = temp2->next;
25 | }
26 | temp1 = temp1->next;
27 | }
28 | duplicates (&list3);
29 | }
30 | }
31 |
32 | void main()
33 | {
34 | int choice1, choice2;
35 | struct node *head1 = NULL;
36 | struct node *head2 = NULL;
37 | printf ("\nLIST 1:");
38 | printf("\n --------------------------\n");
39 | do
40 | {
41 | int item;
42 | printf("\n ENTER NUMBER INTO LIST 1: ");
43 | scanf("%d", &item);
44 | insert_end (item, &head1);
45 | printf("\n DO YOU WISH TO ENTER ANOTHER NUMBER INTO THE LIST? (Any number/0): ");
46 | scanf("%d", &choice1);
47 | }while(choice1);
48 | printf ("\nLIST 2:");
49 | printf("\n --------------------------\n");
50 | do
51 | {
52 | int item;
53 | printf("\n ENTER NUMBER INTO LIST 2: ");
54 | scanf("%d", &item);
55 | insert_end (item, &head2);
56 | printf("\n DO YOU WISH TO ENTER ANOTHER NUMBER INTO THE LIST? (Any number/0): ");
57 | scanf("%d", &choice2);
58 | }while(choice2);
59 | printf("\n----------------------------");
60 | printf("\nLIST 1: \n");
61 | display(head1);
62 | printf("\n----------------------------");
63 | printf("\n----------------------------");
64 | printf("\nLIST 2: \n");
65 | display(head2);
66 | printf("\n----------------------------");
67 | printf("\n----------------------------");
68 | printf("\n LIST 3: \n");
69 | intersection(head1, head2);
70 | display(list3);
71 | printf("\n----------------------------\n");
72 | }
--------------------------------------------------------------------------------
/LINKED LIST/c or cpp/LinkListUsingSTL.CPP:
--------------------------------------------------------------------------------
1 | //Implementation of SLL
2 | #include
3 | #include
4 | struct list
5 | {
6 | int data;
7 | struct list *next;
8 | };
9 |
10 | typedef struct list ll;
11 |
12 | class sll
13 | {
14 | public:
15 | ll *create(ll *);
16 | void display(ll *);
17 | ll *insert(ll *);
18 | ll *Delete(ll *);
19 | };
20 |
21 | void main()
22 | {
23 | sll l;
24 | ll *node;
25 | clrscr();
26 | node = l.create(node);
27 | cout<<"\n List is : ";
28 | l.display(node);
29 | cout<<"\n *****************";
30 | cout<<"\n\n Node Insertion ";
31 | cout<<"\n *****************\n";
32 | node = l.insert(node);
33 | cout<<"\n List after insertion : ";
34 | l.display(node);
35 | //insertL(node);
36 | //insertM(node);
37 | cout<<"\n ****************";
38 | cout<<"\n\n Node Deletion ";
39 | cout<<"\n *****************\n";
40 | node = l.Delete(node);
41 | cout<<"\n List after deletion : ";
42 | l.display(node);
43 | getch();
44 | }
45 |
46 | ll *sll::create(ll *node)
47 | {
48 | char ch;
49 | ll *start;
50 | start = node;
51 | do{
52 | cout<<"\n Enter the node : ";
53 | cin>>node->data;
54 | node->next = new ll;
55 | node = node->next;
56 | node->next = NULL;
57 | //fflush(stdin);
58 | cout<<"\n Do you want to another node (y/n) ";
59 | cin>>ch;
60 | }while(ch != 'n');
61 | return start;
62 | }
63 | void sll::display(ll *node)
64 | {
65 | while(node->next)
66 | {
67 | cout<<" "<data;
68 | node = node->next;
69 | }
70 | }
71 | ll *sll::insert(ll *node)
72 | {
73 | ll *F, *h;
74 | int pos, i = 1;
75 | F = new ll;
76 | h = node;
77 | if(node)
78 | {
79 | cout<<"\n Enter position, where node to be inserted: ";
80 | cin>>pos;
81 |
82 | cout<<"\n Enter the node :";
83 | cin>>F->data;
84 |
85 | if(pos == 1)
86 | {
87 | F->next = h;
88 | h = F;
89 | }
90 | else
91 | {
92 | while(inext;
95 | i++;
96 | }
97 | F->next = node->next;
98 | node->next = F;
99 | }
100 | }
101 | return h;
102 | }
103 |
104 | ll *sll::Delete(ll *node)
105 | {
106 | ll *start, *d;
107 | int pos, i = 1;
108 | start = node;
109 | cout<<"\n Enter the position, from where node to be deleted : ";
110 | cin>>pos;
111 | while(inext;
114 | i++;
115 | }
116 | d = node->next;
117 | node->next = d->next;
118 | delete(d);
119 | return start;
120 | }
121 |
122 |
123 |
124 |
--------------------------------------------------------------------------------
/LINKED LIST/c or cpp/Palindrome_Linked_list.cpp:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | using namespace std;
4 |
5 | class Node {
6 | public:
7 | int data;
8 |
9 | Node(int d){
10 | data = d;
11 | }
12 | Node *ptr;
13 | };
14 |
15 | bool isPalindrome(Node* head){
16 | // This pointer will allow the first traversal
17 | // of the linked list
18 | Node* next= head;
19 | // Declare a stack
20 | stack s;
21 |
22 | // Traverse the linked list and add its elements
23 | // to the stack
24 | while(next != NULL){
25 | s.push(next->data);
26 | next = next->ptr;
27 | }
28 |
29 | // Iterate the linked list again and
30 | // check by each element with the stack
31 | while(head != NULL ){
32 | int i=s.top();
33 |
34 | if(head -> data != i){
35 | return false;
36 | }
37 | // Move to the next element in stack and the list
38 | s.pop();
39 | head=head->ptr;
40 | }
41 |
42 | return true;
43 | }
44 |
45 |
46 | //Main function
47 | int main(){
48 |
49 | Node one = Node(1);
50 | Node two = Node(3);
51 | Node three = Node(5);
52 | Node four = Node(3);
53 | Node five = Node(1);
54 |
55 | // Initialize the pointers of the Linked List
56 | five.ptr = NULL;
57 | one.ptr = &two;
58 | two.ptr = &three;
59 | three.ptr = &four;
60 | four.ptr = &five;
61 | Node* temp = &one;
62 |
63 |
64 | // Call function with head of the linked list
65 | int result = isPalindrome(&one);
66 | if(result == 1)
67 | cout<<"Linked list is a palindrome\n";
68 | else
69 | cout<<"Linked list is NOT a palindrome\n";
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/LINKED LIST/c or cpp/Remove_Duplicates.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include "dll.h"
4 | //Author: Taniya Kulkarni
5 |
6 |
7 |
8 | void main()
9 | {
10 | int choice;
11 | struct node *head = NULL;
12 | do{
13 | int item;
14 | printf("\n ENTER NUMBER INTO LIST: ");
15 | scanf("%d", &item);
16 | insert_end (item, &head);
17 | printf("\n DO YOU WISH TO ENTER ANOTHER NUMBER INTO THE LIST? (Any number/0): ");
18 | scanf("%d", &choice);
19 | }while(choice);
20 | printf("\n----------------------------");
21 | printf("\nOLD LIST (WITH DUPLICATES): \n");
22 | display(head);
23 | printf("\n----------------------------");
24 | printf("\nNEW LIST (WITHOUT DUPLICATES): \n");
25 | duplicates(&head);
26 | display(head);
27 | printf("\n");
28 | }
--------------------------------------------------------------------------------
/LINKED LIST/c or cpp/Unions.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include "dll.h"
4 | //Author: Taniya Kulkarni
5 |
6 | struct node *list3=NULL;
7 |
8 | void union_list(struct node *head1, struct node *head2)
9 | {
10 | isempty(head1);
11 | isempty(head2);
12 | if(head1 != NULL && head2 != NULL)
13 | {
14 | struct node *temp1 = head1;
15 | struct node *temp2 = head2;
16 | while(temp1 != NULL)
17 | {
18 | insert_end(temp1->num, &list3);
19 | temp1 = temp1->next;
20 | }
21 | while(temp2 != NULL)
22 | {
23 | insert_end(temp2->num, &list3);
24 | temp2 = temp2->next;
25 | }
26 | }
27 | duplicates(&list3);
28 |
29 | }
30 |
31 | void main()
32 | {
33 | int choice1, choice2;
34 | struct node *head1 = NULL;
35 | struct node *head2 = NULL;
36 | printf ("\nLIST 1:");
37 | printf("\n --------------------------\n");
38 | do{
39 | int item;
40 | printf("\n ENTER NUMBER INTO LIST 1: ");
41 | scanf("%d", &item);
42 | insert_end (item, &head1);
43 | printf("\n DO YOU WISH TO ENTER ANOTHER NUMBER INTO THE LIST? (Any number/0): ");
44 | scanf("%d", &choice1);
45 | }while(choice1);
46 | printf ("\nLIST 2:");
47 | printf("\n --------------------------\n");
48 | do{
49 | int item;
50 | printf("\n ENTER NUMBER INTO LIST 2: ");
51 | scanf("%d", &item);
52 | insert_end (item, &head2);
53 | printf("\n DO YOU WISH TO ENTER ANOTHER NUMBER INTO THE LIST? (Any number/0): ");
54 | scanf("%d", &choice2);
55 | }while(choice2);
56 | printf("\n----------------------------");
57 | printf("\nLIST 1: \n");
58 | display(head1);
59 | printf("\n----------------------------");
60 | printf("\n----------------------------");
61 | printf("\nLIST 2: \n");
62 | display(head2);
63 | printf("\n----------------------------");
64 | printf("\n----------------------------");
65 | printf("\n LIST 3: \n");
66 | union_list(head1, head2);
67 | display(list3);
68 | printf("\n----------------------------\n");
69 | }
--------------------------------------------------------------------------------
/LINKED LIST/c or cpp/dll.h:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | //Author: Taniya Kulkarni
4 |
5 | //Node for Doubly linked list.
6 | struct node
7 | {
8 | int num;
9 | struct node *prev, *next;
10 | };
11 | struct node *new, *ptr;
12 | int size=0;
13 |
14 | //Function to check if list is empty
15 | void isempty(struct node *head)
16 | {
17 | if (head==NULL)
18 | {
19 | printf("\n LIST IS EMPTY!\n");
20 | return;
21 | }
22 | return;
23 | }
24 |
25 |
26 |
27 | //Function to insert node at the end
28 | void insert_end (int item, struct node **head_ref)
29 | {
30 | struct node *temp;
31 | new=(struct node *) malloc (sizeof(struct node));
32 | new->num = item;
33 | new->next = NULL;
34 | if (*head_ref == NULL)
35 | {
36 | *head_ref = new;
37 | size++;
38 | return;
39 | }
40 |
41 | else
42 | {
43 | temp = *head_ref;
44 | while (temp -> next != NULL)
45 | {
46 | temp = temp->next;
47 | }
48 | temp->next = new;
49 | new->prev = temp;
50 | }
51 | size++;
52 | }
53 |
54 |
55 |
56 |
57 |
58 | void display (struct node *head)
59 | {
60 |
61 | if (head != NULL)
62 | {
63 | struct node *temp;
64 | temp=head;
65 | while(temp->next != NULL)
66 | {
67 | printf (" %d -> ", temp->num);
68 | temp= temp->next;
69 | }
70 | printf("%d ", temp->num);
71 | }
72 | }
73 |
74 |
75 | //Function to check for duplicates
76 | void duplicates(struct node **head_ref)
77 | {
78 | struct node *temp, *copy;
79 | isempty(*head_ref);
80 | if(*head_ref != NULL)
81 | {
82 | temp = *head_ref;
83 | while (temp != NULL && temp->next != NULL)
84 | {
85 | ptr = temp;
86 | while(ptr -> next != NULL)
87 | {
88 | if(temp->num == ptr->next->num) //If duplicate found, then delete the copy.
89 | {
90 | copy = ptr->next;
91 | ptr->next = ptr->next->next;
92 | free(copy);
93 | }
94 | else
95 | {
96 | ptr= ptr->next;
97 | }
98 | }
99 | temp = temp->next;
100 | }
101 |
102 | }
103 | }
--------------------------------------------------------------------------------
/LINKED LIST/c or cpp/sorting linked list.c:
--------------------------------------------------------------------------------
1 | // Problem :- Program to check whether Linked List is sorted or not.
2 |
3 | #include
4 | #include
5 |
6 | struct Node
7 | {
8 | int data;
9 | struct Node *next;
10 | }*first=NULL;
11 |
12 | void create (int A[], int n)
13 | {
14 | int i;
15 | struct Node *t, *last;
16 | first=(struct Node *)malloc(sizeof(struct Node));
17 | first->data=A[0];
18 | first->next=NULL;
19 | last=first;
20 | for(i=1; idata=A[i];
24 | t->next=NULL;
25 | last->next=t;
26 | last=t;
27 | }
28 | }
29 |
30 | int isSorted(struct Node *p)
31 | {
32 | int x = -32768;
33 | while(p!=NULL)
34 | {
35 | if(p->data < x)
36 | return 0;
37 | x = p->data;
38 | p = p->next;
39 | }
40 | return 1;
41 | }
42 |
43 | int main()
44 | {
45 | int A[]={10, 2, 30, 40, 50};
46 | create(A, 5);
47 | if(isSorted(first))
48 | {
49 | printf("Linked List is Sorted\n");
50 | }
51 | else
52 | {
53 | printf("Linked List is Not Sorted\n");
54 | }
55 | return 0;
56 | }
57 |
58 |
59 | /*
60 |
61 | Output :-
62 |
63 | Linked List is Not Sorted
64 |
65 | */
66 |
--------------------------------------------------------------------------------
/LINKED LIST/java/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma)
7 | - [Abhishek Kumar Vikrant](https://github.com/AbhiVikrant)
8 | - [Pari Zunake](https://github.com/psz8)
9 |
--------------------------------------------------------------------------------
/LINKED LIST/java/Sorting/MergeSort.md:
--------------------------------------------------------------------------------
1 | ## Best Sorting Algorithms for Linked List
2 | ----------
3 | *Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible.*
4 |
5 |
6 |
7 |
8 |
9 | ### Steps Required for Sorting the LinkedList using Merge Sort
10 |
11 | ```language
12 | MergeSort(headRef)
13 | 1) If the head is NULL or there is only one element in the Linked List
14 | then return.
15 | 2) Else divide the linked list into two halves.
16 | FrontBackSplit(head, &a, &b); /* a and b are two halves */
17 | 3) Sort the two halves a and b.
18 | MergeSort(a);
19 | MergeSort(b);
20 | 4) Merge the sorted a and b (using SortedMerge() discussed here)
21 | and update the head pointer using headRef.
22 | *headRef = SortedMerge(a, b);
23 | ```
24 |
25 | ### Descriptions
26 | *Let head be the first node of the linked list to be sorted and headRef be the pointer to head. Note that we need a reference to head in MergeSort() as the below implementation changes next links to sort the linked lists (not data at the nodes), so head node has to be changed if the data at the original head is not the smallest value in the linked list.*
27 |
28 | ### Reference
29 | [GeeksForGeeks](https://www.geeksforgeeks.org/merge-sort-for-linked-list/#:~:text=Merge%20sort%20is%20often%20preferred,be%20the%20pointer%20to%20head.)
30 |
31 |
32 |
33 | Thanks Coding !
34 | Thanks for Open Source Contribution!
35 |
--------------------------------------------------------------------------------
/LINKED LIST/java/Sorting/Sort-Linked-List-768x384.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms/35e6685cfca8d43fbef75dbe78e4527b49be6e17/LINKED LIST/java/Sorting/Sort-Linked-List-768x384.png
--------------------------------------------------------------------------------
/LINKED LIST/java/linkedlist.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class Test {
4 |
5 | public static void main(String args[])
6 | {
7 | // Creating object of the
8 | // class linked list
9 | LinkedList ll
10 | = new LinkedList();
11 |
12 | // Adding elements to the linked list
13 | ll.add("A");
14 | ll.add("B");
15 | ll.addLast("C");
16 | ll.addFirst("D");
17 | ll.add(2, "E");
18 |
19 | System.out.println(ll);
20 |
21 | ll.remove("B");
22 | ll.remove(3);
23 | ll.removeFirst();
24 | ll.removeLast();
25 |
26 | System.out.println(ll);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/LINKED LIST/py/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma)
7 | - [Karan Wagh](https://github.com/FlashTech-dev)
8 | - [Vivek Ray](https://github.com/vivekray903)
9 | - [Gaurav Kulkarni](https://github.com/gkulk007)
10 |
11 |
12 |
--------------------------------------------------------------------------------
/LINKED LIST/py/is_palindrome.py:
--------------------------------------------------------------------------------
1 | def is_palindrome(head):
2 | if not head:
3 | return True
4 | # split the list to two parts
5 | fast, slow = head.next, head
6 | while fast and fast.next:
7 | fast = fast.next.next
8 | slow = slow.next
9 | second = slow.next
10 | slow.next = None # Don't forget here! But forget still works!
11 | # reverse the second part
12 | node = None
13 | while second:
14 | nxt = second.next
15 | second.next = node
16 | node = second
17 | second = nxt
18 | # compare two parts
19 | # second part has the same or one less node
20 | while node:
21 | if node.val != head.val:
22 | return False
23 | node = node.next
24 | head = head.next
25 | return True
26 |
27 |
28 | def is_palindrome_stack(head):
29 | if not head or not head.next:
30 | return True
31 |
32 | # 1. Get the midpoint (slow)
33 | slow = fast = cur = head
34 | while fast and fast.next:
35 | fast, slow = fast.next.next, slow.next
36 |
37 | # 2. Push the second half into the stack
38 | stack = [slow.val]
39 | while slow.next:
40 | slow = slow.next
41 | stack.append(slow.val)
42 |
43 | # 3. Comparison
44 | while stack:
45 | if stack.pop() != cur.val:
46 | return False
47 | cur = cur.next
48 |
49 | return True
50 |
51 |
52 | def is_palindrome_dict(head):
53 | if not head or not head.next:
54 | return True
55 | d = {}
56 | pos = 0
57 | while head:
58 | if head.val in d.keys():
59 | d[head.val].append(pos)
60 | else:
61 | d[head.val] = [pos]
62 | head = head.next
63 | pos += 1
64 | checksum = pos - 1
65 | middle = 0
66 | for v in d.values():
67 | if len(v) % 2 != 0:
68 | middle += 1
69 | else:
70 | step = 0
71 | for i in range(0, len(v)):
72 | if v[i] + v[len(v) - 1 - step] != checksum:
73 | return False
74 | step += 1
75 | if middle > 1:
76 | return False
77 | return True
78 |
79 | # Implemented by Gaurav Kulkarni
80 |
--------------------------------------------------------------------------------
/OBJECT ORIENTED PROGRAMMING/c or cpp/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma )
7 | - [Bhavesh Joshi](https://github.com/Wittty-Panda )
8 | - [Atharv Karanjkar](https://github.com/atharvkaranjkar)
--------------------------------------------------------------------------------
/OBJECT ORIENTED PROGRAMMING/c or cpp/Herarchical_inheritance/Herarchical_inheritance.cbp:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/OBJECT ORIENTED PROGRAMMING/c or cpp/Herarchical_inheritance/Herarchical_inheritance.layout:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/OBJECT ORIENTED PROGRAMMING/c or cpp/Herarchical_inheritance/bin/Debug/Herarchical_inheritance.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms/35e6685cfca8d43fbef75dbe78e4527b49be6e17/OBJECT ORIENTED PROGRAMMING/c or cpp/Herarchical_inheritance/bin/Debug/Herarchical_inheritance.exe
--------------------------------------------------------------------------------
/OBJECT ORIENTED PROGRAMMING/c or cpp/Herarchical_inheritance/main.cpp:
--------------------------------------------------------------------------------
1 | // C++ program to implement Hierarchical Inheritance
2 | #include
3 | using namespace std;
4 | // base class
5 | class Vehicle
6 | {
7 | public:
8 | Vehicle()
9 | {
10 | cout << "This is a Vehicle" << endl;
11 | }
12 | };
13 | // first sub class
14 | class Car: public Vehicle
15 | {
16 |
17 | };
18 | // second sub class
19 | class Bus: public Vehicle
20 | {
21 | };
22 | // main function
23 | int main()
24 | { // creating object of sub class will
25 | // invoke the constructor of base class
26 | Car obj1;
27 | Bus obj2;
28 | return 0;
29 | }
30 |
--------------------------------------------------------------------------------
/OBJECT ORIENTED PROGRAMMING/c or cpp/Herarchical_inheritance/obj/Debug/main.o:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms/35e6685cfca8d43fbef75dbe78e4527b49be6e17/OBJECT ORIENTED PROGRAMMING/c or cpp/Herarchical_inheritance/obj/Debug/main.o
--------------------------------------------------------------------------------
/OBJECT ORIENTED PROGRAMMING/c or cpp/Hybrid_Inheritance/Hybrid_Inheritance.cbp:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/OBJECT ORIENTED PROGRAMMING/c or cpp/Hybrid_Inheritance/Hybrid_Inheritance.depend:
--------------------------------------------------------------------------------
1 | # depslib dependency file v1.0
2 | 1602068805 source:e:\programming\teaching\hybrid_inheritance\main.cpp
3 |
4 |
5 |
--------------------------------------------------------------------------------
/OBJECT ORIENTED PROGRAMMING/c or cpp/Hybrid_Inheritance/Hybrid_Inheritance.layout:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/OBJECT ORIENTED PROGRAMMING/c or cpp/Hybrid_Inheritance/bin/Debug/Hybrid_Inheritance.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms/35e6685cfca8d43fbef75dbe78e4527b49be6e17/OBJECT ORIENTED PROGRAMMING/c or cpp/Hybrid_Inheritance/bin/Debug/Hybrid_Inheritance.exe
--------------------------------------------------------------------------------
/OBJECT ORIENTED PROGRAMMING/c or cpp/Hybrid_Inheritance/main.cpp:
--------------------------------------------------------------------------------
1 | // C++ program for Hybrid Inheritance
2 | #include
3 | using namespace std;
4 |
5 | // base class
6 | class Vehicle
7 | {
8 | public:
9 | Vehicle()
10 | {
11 | cout << "This is a Vehicle" << endl;
12 | }
13 | };
14 | //base class
15 | class Fare
16 | {
17 | public:
18 | Fare()
19 | {
20 | cout<
4 |
5 | using namespace std;
6 |
7 | class N;
8 |
9 | class M{
10 | int num;
11 | public:
12 | M(){
13 | cout<<"Enter value (M)";
14 | cin>>num;
15 | };
16 | void displaydata();
17 | ~M(){
18 |
19 | }
20 | friend void comp(M x, N y);
21 | };
22 |
23 | class N{
24 | int num;
25 | friend void comp(M x, N y);
26 | public:
27 | N(){
28 | cout<<"Enter value (N)";
29 | cin>>num;
30 | };
31 | void displaydata();
32 | ~N(){
33 |
34 | }
35 | //friend void comp(M x, N y);
36 | };
37 | void comp(M x, N y){
38 | if (x.num>y.num){
39 | cout<<"\n Greater number is : "<
3 | using namespace std;
4 |
5 | class A //single base class
6 | {
7 | public:
8 | int x, y;
9 | void getdata()
10 | {
11 | cout << "\nEnter value of x and y:\n"; cin >> x >> y;
12 | }
13 | };
14 | class B : public A //B is derived from class base
15 | {
16 | public:
17 | void product()
18 | {
19 | cout << "\nProduct= " << x * y;
20 | }
21 | };
22 | class C : public A //C is also derived from class base
23 | {
24 | public:
25 | void sum()
26 | {
27 | cout << "\nSum= " << x + y;
28 | }
29 | };
30 | int main()
31 | {
32 | B obj1; //object of derived class B
33 | C obj2; //object of derived class C
34 | obj1.getdata();
35 | obj1.product();
36 | obj2.getdata();
37 | obj2.sum();
38 | return 0;
39 | } //end of program
--------------------------------------------------------------------------------
/PATTERNS/halfpyramid.c:
--------------------------------------------------------------------------------
1 | #include
2 | int main()
3 | {
4 | int i;
5 | int j;
6 | int n=7;
7 | int x=n, y=n;
8 | for(i=1; i<=n; i++)
9 | {
10 | for(j=1; j=x && j<=y)
13 | {
14 | printf(" * ");
15 | }
16 | else
17 | {
18 | printf("");
19 | }
20 |
21 | }
22 |
23 | x--;
24 | y++;
25 | printf("\n");
26 | }
27 | return 0;
28 | }
29 |
30 | #OUTPUT:
31 |
32 | *
33 | * *
34 | * * *
35 | * * * *
36 | * * * * *
37 | * * * * * *
38 |
--------------------------------------------------------------------------------
/PATTERNS/pascalTriangle.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | using namespace std;
4 |
5 | int factorial(int num)
6 | {
7 | int factorial = 1;
8 | for (int i = 2; i <= num; i++)
9 | {
10 | factorial *= i;
11 | }
12 | return factorial;
13 | }
14 | int main()
15 | {
16 | int n;
17 | cin >> n;
18 | for (int i = 0; i < n; i++)
19 | {
20 | for (int j = 0; j <= i; j++)
21 | {
22 | cout << factorial(i) / (factorial(j) * factorial(i - j)) << " ";
23 | }
24 | cout << endl;
25 | }
26 | return 0;
27 | }
28 |
--------------------------------------------------------------------------------
/PATTERNS/pattern.c:
--------------------------------------------------------------------------------
1 | /*
2 | 1
3 | 2*2
4 | 3*3*3
5 | 4*4*4*4
6 | 4*4*4*4
7 | 3*3*3
8 | 2*2
9 | 1
10 | */
11 | #include
12 |
13 | int main()
14 | {
15 | int i, j;
16 | for (i = 1; i <= 4; i++)
17 | {
18 | for (j = 1; j <= i; j++)
19 | {
20 | if (j < i)
21 | printf("%d*", i);
22 | else
23 | printf("%d", i);
24 | }
25 | printf(" \n");
26 | }
27 | for (i = 4; i >= 1; i--)
28 | {
29 | for (j = 1; j <= i; j++)
30 | {
31 | if (j < i)
32 | printf("%d*", i);
33 | else
34 | printf("%d", i);
35 | }
36 | printf(" \n");
37 | }
38 | return 0;
39 | }
--------------------------------------------------------------------------------
/PRIMALITY TESTING ALGORITHMS/c or cpp/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma)
7 |
--------------------------------------------------------------------------------
/PRIMALITY TESTING ALGORITHMS/c or cpp/sieve.cpp:
--------------------------------------------------------------------------------
1 | //Program to find the prime numbers in O(nloglogn)
2 | #include
3 | using namespace std;
4 |
5 | void SieveOfEratosthenes(int n)
6 | {
7 | bool prime[n+1];
8 | memset(prime, true, sizeof(prime));
9 |
10 | for (int p=2; p*p<=n; p++)
11 | {
12 | if (prime[p] == true)
13 | {
14 | for (int i=p*p; i<=n; i += p)
15 | prime[i] = false;
16 | }
17 | }
18 |
19 | for (int p=2; p<=n; p++)
20 | if (prime[p])
21 | cout << p << " ";
22 | }
23 |
24 | // Driver Program
25 | int main()
26 | {
27 | int n = 1000;
28 | cout << "Here are the prime numbers smaller "
29 | << " than or equal to " << n << endl;
30 | SieveOfEratosthenes(n);
31 | return 0;
32 | }
33 |
--------------------------------------------------------------------------------
/PRIMALITY TESTING ALGORITHMS/java/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma)
7 |
--------------------------------------------------------------------------------
/PRIMALITY TESTING ALGORITHMS/py/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 |
3 | If you have contributed to this repository, kindly add your username here
4 |
5 | - [Dhruvil Shah](https://github.com/d-s-2803)
6 | - [Gaurav Verma](https://github.com/thegauravverma)
7 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Data-Structures-and-Algorithms
2 |
3 |
Contribute your C,CPP,JAVA and PYTHON Codes
4 |
5 |
6 |
7 |
How to contribute?
8 |
9 |
10 | 1. [Fork](https://github.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms) this repository.
11 | 2. Clone the forked repository to your computer.
12 |
13 | `https://github.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms.git`
14 |
15 | 3. Add your choice of code in any of the folder that has been created.
16 | 4. You are also welcomed to add innovative codes of your choice.
17 | 5. Your program should be interactive and please do add comments if possible.
18 | 6. Add your name in the contributors.md file just for the record.
19 | 7. Create a Pull Request
20 |