Skip to content

Commit 0f34f79

Browse files
author
Bhrigu Kansra
authored
Merge branch 'master' into master
2 parents 2b8f3aa + a0554ce commit 0f34f79

File tree

18 files changed

+789
-90
lines changed

18 files changed

+789
-90
lines changed

Algorithms/HuffmanEncoder.java

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import java.util.ArrayList;
2+
import java.util.HashMap;
3+
import java.util.PriorityQueue;
4+
5+
public class HuffmanEncoder {
6+
private HashMap<Character, String> encoder = new HashMap<>();
7+
private HashMap<String, Character> decoder = new HashMap<>();
8+
9+
private class Node implements Comparable<Node> {
10+
char data;
11+
int freq;
12+
Node left;
13+
Node right;
14+
15+
@Override
16+
public int compareTo(Node o) {
17+
return this.freq - o.freq;
18+
}
19+
}
20+
21+
public HuffmanEncoder(String feeder) {
22+
// Step 1 -> Feeder to fmap
23+
HashMap<Character, Integer> fmap = new HashMap<>();
24+
25+
for (int i = 0; i < feeder.length(); i++) {
26+
char ch = feeder.charAt(i);
27+
fmap.put(ch, fmap.containsKey(ch) ? fmap.get(ch) + 1 : 1);
28+
}
29+
30+
// Step 2 -> fmap to Priority Queue
31+
ArrayList<Character> keys = new ArrayList<>(fmap.keySet());
32+
PriorityQueue<Node> pq = new PriorityQueue<>();
33+
for (Character key : keys) {
34+
Node node = new Node();
35+
node.freq = fmap.get(key);
36+
node.data = key;
37+
pq.add(node);
38+
}
39+
40+
// Step 3 -> while PQ.size > 1, remove 2 from PQ, merge them and add in
41+
// PQ
42+
while (pq.size() > 1) {
43+
Node one = pq.remove();
44+
Node two = pq.remove();
45+
Node merged = new Node();
46+
merged.freq = one.freq + two.freq;
47+
merged.left = one;
48+
merged.right = two;
49+
pq.add(merged);
50+
}
51+
52+
Node lastNodeInPQ = pq.remove();
53+
traverse(lastNodeInPQ, "");
54+
System.out.println(encoder);
55+
}
56+
57+
private void traverse(Node node, String psf) {
58+
if (node.left == null && node.right == null) {
59+
encoder.put(node.data, psf);
60+
decoder.put(psf, node.data);
61+
return;
62+
}
63+
traverse(node.left, psf + "0");
64+
traverse(node.right, psf + "1");
65+
}
66+
67+
public String encode(String str) {
68+
String coded = "";
69+
for (int i = 0; i < str.length(); i++) {
70+
coded += encoder.get(str.charAt(i));
71+
}
72+
73+
return coded;
74+
}
75+
76+
public String decode(String str) {
77+
String ch = "";
78+
String decoded = "";
79+
80+
for (int i = 0; i < str.length(); i++) {
81+
ch += str.substring(i, i + 1);
82+
if (decoder.containsKey(ch)) {
83+
decoded += decoder.get(ch);
84+
ch = "";
85+
}
86+
}
87+
88+
return decoded;
89+
}
90+
91+
}

Graph/BFS.java

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import java.util.ArrayDeque;
2+
import java.util.ArrayList;
3+
import java.util.Arrays;
4+
5+
public class BFS {
6+
7+
public static void main(String[] args) {
8+
Graph G = new Graph(8);
9+
G.addEdge(0, 1);
10+
G.addEdge(2, 3);
11+
G.addEdge(0, 4);
12+
G.addEdge(5, 6);
13+
G.addEdge(2, 5);
14+
G.addEdge(2, 6);
15+
G.addEdge(1, 5);
16+
G.addEdge(6, 7);
17+
G.addEdge(3, 6);
18+
G.addEdge(3, 7);
19+
BFS b = new BFS();
20+
b.bfs(G, 1);
21+
}
22+
23+
public void bfs(Graph G,int s) {
24+
int[] color = new int[G.V()]; //0-White,1-Gray,2-Black
25+
int[] d = new int[G.V()]; //distance from source
26+
int[] p = new int[G.V()]; // parent
27+
Arrays.fill(d, -1);
28+
Arrays.fill(p, -1);
29+
ArrayDeque<Integer> q = new ArrayDeque<>();
30+
31+
color[s]=1;
32+
d[s]=0;
33+
p[s]=-1; //parent of source in BFS tree is NIL
34+
q.add(s);
35+
while(!q.isEmpty()) {
36+
int u = q.poll();
37+
for(int v:G.adj[u]) {
38+
if(color[v]==0) { //if color is white
39+
color[v]=1; //make it Grey
40+
d[v]=d[u]+1; // update distance from source
41+
p[v]=u; // update parent
42+
q.add(v);
43+
}
44+
}
45+
color[u]=2; //change color to black when all adjacent of u are discovered
46+
}
47+
System.out.println(Arrays.toString(color));
48+
System.out.println(Arrays.toString(d));
49+
System.out.println(Arrays.toString(p));
50+
}
51+
52+
static class Graph {
53+
private final int V;
54+
private int E;
55+
private ArrayList<Integer>[] adj;
56+
57+
public Graph(int V) {
58+
this.V = V;
59+
adj = new ArrayList[V];
60+
for (int v = 0; v < V; v++) {
61+
adj[v] = new ArrayList<Integer>();
62+
}
63+
}
64+
65+
public int V() {
66+
return V;
67+
}
68+
69+
public int E() {
70+
return E;
71+
}
72+
73+
public void addEdge(int v, int w) {
74+
adj[v].add(w);
75+
adj[w].add(v);
76+
E++;
77+
}
78+
79+
public Iterable<Integer> adj(int v) {
80+
return adj[v];
81+
}
82+
}
83+
}

Graph/BFS.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""pseudo-code"""
2+
3+
"""
4+
BFS(graph G, start vertex s):
5+
// all nodes initially unexplored
6+
mark s as explored
7+
let Q = queue data structure, initialized with s
8+
while Q is non-empty:
9+
remove the first node of Q, call it v
10+
for each edge(v, w): // for w in graph[v]
11+
if w unexplored:
12+
mark w as explored
13+
add w to Q (at the end)
14+
15+
"""
16+
17+
import collections
18+
19+
20+
def bfs(graph, start):
21+
explored, queue = set(), [start] # collections.deque([start])
22+
explored.add(start)
23+
while queue:
24+
v = queue.pop(0) # queue.popleft()
25+
for w in graph[v]:
26+
if w not in explored:
27+
explored.add(w)
28+
queue.append(w)
29+
return explored
30+
31+
32+
G = {'A': ['B', 'C'],
33+
'B': ['A', 'D', 'E'],
34+
'C': ['A', 'F'],
35+
'D': ['B'],
36+
'E': ['B', 'F'],
37+
'F': ['C', 'E']}
38+
39+
print(bfs(G, 'A'))

Graph/DFS.java

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import java.util.*;
2+
3+
public class DFS {
4+
//////////simple DFS//////////////////
5+
private static boolean[] marked;
6+
private static int count;
7+
8+
public static void dfsUtil(Graph G, int s) {
9+
marked = new boolean[G.V()];
10+
dfs(G, s);
11+
}
12+
13+
private static void dfs(Graph G, int v) {
14+
marked[v] = true;
15+
count++;
16+
for (int w : G.adj(v)) {
17+
if (!marked[w]) {
18+
dfs(G, w);
19+
}
20+
}
21+
}
22+
23+
public static boolean isMarked(int w) {
24+
return marked[w];
25+
}
26+
27+
public static int count() {
28+
return count;
29+
}
30+
////////////////////////////////////////
31+
static class Graph {
32+
private final int V; // vertices
33+
private int E; // edges
34+
ArrayList<Integer>[] adj; // adjacency list
35+
36+
public Graph(int V) {
37+
this.V = V;
38+
adj = new ArrayList[V];
39+
for (int v = 0; v < V; v++) {
40+
adj[v] = new ArrayList<Integer>();
41+
}
42+
}
43+
44+
public int V() {
45+
return V;
46+
}
47+
48+
public int E() {
49+
return E;
50+
}
51+
52+
public void addEdge(int v, int w) {
53+
adj[v].add(w);
54+
adj[w].add(v);
55+
E++;
56+
}
57+
58+
public Iterable<Integer> adj(int v) {
59+
return adj[v];
60+
}
61+
}
62+
63+
public static void main(String[] args) {
64+
int v=3; //no of vertex
65+
Graph G = new Graph(v);
66+
G.addEdge(0, 1);
67+
G.addEdge(1, 2);
68+
G.addEdge(2, 0);
69+
int source=1;
70+
dfsUtil(G, source);
71+
System.out.println(isMarked(2)); //tell reachable from source or not
72+
System.out.println(count); //number of vertices reachable from source
73+
}
74+
}

Graph/DFS.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""pseudo-code"""
2+
3+
"""
4+
DFS(graph G, start vertex s):
5+
// all nodes initially unexplored
6+
mark s as explored
7+
for every edge (s, v):
8+
if v unexplored:
9+
DFS(G, v)
10+
"""
11+
12+
13+
def dfs(graph, start):
14+
"""The DFS function simply calls itself recursively for every unvisited child of its argument. We can emulate that
15+
behaviour precisely using a stack of iterators. Instead of recursively calling with a node, we'll push an iterator
16+
to the node's children onto the iterator stack. When the iterator at the top of the stack terminates, we'll pop
17+
it off the stack."""
18+
explored, stack = set(), [start]
19+
explored.add(start)
20+
while stack:
21+
v = stack.pop() # the only difference from BFS is to pop last element here instead of first one
22+
for w in graph[v]:
23+
if w not in explored:
24+
explored.add(w)
25+
stack.append(w)
26+
return explored
27+
28+
29+
G = {'A': ['B', 'C'],
30+
'B': ['A', 'D', 'E'],
31+
'C': ['A', 'F'],
32+
'D': ['B'],
33+
'E': ['B', 'F'],
34+
'F': ['C', 'E']}
35+
36+
print(dfs(G, 'A'))

Graph/filename.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

0 commit comments

Comments
 (0)