Merge pull request #1322 from Ritik2604/master

Added Important Algos
This commit is contained in:
Sombit Bose
2020-05-25 17:05:37 +05:30
committed by GitHub
8 changed files with 1003 additions and 74 deletions

View File

@ -0,0 +1,487 @@
package DataStructures.Graphs;
/*
Implementation of graph by using hashmap for vertices of class which contains hashmap for vertex and then algos like prims dijktsra ,depth for search and traversal ,breadth for search and traversal ,algo for cycle present or not ,connected or not ,if not connected then connect it
Test case
Graph gp=new Graph();
gp.addVertex("A");
gp.addVertex("B");
gp.addVertex("C");
gp.addVertex("D");
gp.addVertex("E");
gp.addVertex("F");
gp.addVertex("G");
gp.addEdge("A", "B", 2);
gp.addEdge("A", "D", 10);
gp.addEdge("B", "C", 3);
gp.addEdge("C", "D", 1);
gp.addEdge("D", "E", 8);
gp.addEdge("E", "F", 5);
gp.addEdge("E", "G", 6);
gp.addEdge("F", "G", 4);
// gp.display();
// System.out.println(gp.numVertex());
// System.out.println(gp.numEdge());
// System.out.println(gp.containsEdge("A", "C"));
//
// System.out.println(gp.containsEdge("E", "F"));
// gp.removeEdge("D", "E");
// gp.display();
// gp.removeVertex("F");
// gp.addVertex("F");
// gp.display();
// System.out.println(gp.hasPath("A", "F", new HashMap<>()));
// System.out.println(gp.dfs("A", "F"));
// gp.bft();
// gp.dft();
// gp.removeEdge("B","C");
// gp.removeEdge("F","G");
// System.out.println(gp.isConnected());
// System.out.println(gp.isCyclic());
// System.out.println(gp.isTree());
// System.out.println(gp.getConnectedComp());
// gp.prims().display();
System.out.println(gp.Dijktsra("A"));
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import Heaps.GenericHeap;
public class Graph {
private class vertex{
HashMap<String,Integer> nbrs=new HashMap<>();
}
HashMap<String,vertex> vertcs;
public Graph(){
vertcs=new HashMap<>();
}
public int numVertex() {
return this.vertcs.size();
}
public boolean containsVertex(String vname) {
return this.vertcs.containsKey(vname);
}
public void addVertex(String vname) {
vertex vtx=new vertex();
this.vertcs.put(vname,vtx);
}
public void removeVertex(String vname) {
vertex vtx=this.vertcs.get(vname);
ArrayList<String> keys=new ArrayList<>(vtx.nbrs.keySet());
for(String key:keys) {
vertex nbrvtx=this.vertcs.get(key);
nbrvtx.nbrs.remove(vname);
}
this.vertcs.remove(vname);
}
public int numEdge() {
int count=0;
ArrayList<String> keys=new ArrayList<>(this.vertcs.keySet());
for(String key:keys) {
vertex vtx=this.vertcs.get(key);
count+=vtx.nbrs.size();
}
return count/2;
}
public boolean containsEdge(String vname1,String vname2) {
vertex vtx1=this.vertcs.get(vname1);
vertex vtx2=this.vertcs.get(vname2);
if(vtx1==null||vtx2==null||!vtx1.nbrs.containsKey(vname2))
return false;
return true;
}
public void addEdge(String vname1,String vname2,int cost) {
vertex vtx1=this.vertcs.get(vname1);
vertex vtx2=this.vertcs.get(vname2);
if(vtx1==null||vtx2==null||vtx1.nbrs.containsKey(vname2))
return;
vtx1.nbrs.put(vname2,cost);
vtx2.nbrs.put(vname1,cost);
}
public void removeEdge(String vname1,String vname2) {
vertex vtx1=this.vertcs.get(vname1);
vertex vtx2=this.vertcs.get(vname2);
if(vtx1==null||vtx2==null||!vtx1.nbrs.containsKey(vname2))
return;
vtx1.nbrs.remove(vname2);
vtx2.nbrs.remove(vname1);
}
public void display() {
ArrayList<String> keys=new ArrayList<>(this.vertcs.keySet());
for(String key:keys) {
vertex vtx=this.vertcs.get(key);
System.out.println(key+" := "+vtx.nbrs);
}
}
public boolean hasPath(String source ,String dest,HashMap<String,Boolean> processed) {
processed.put(source, true);
if(containsEdge(source,dest)) {
return true;
}
vertex vtx=this.vertcs.get(source);
ArrayList<String> keys=new ArrayList<>(vtx.nbrs.keySet());
for(String key:keys) {
if(!processed.containsKey(key) && hasPath(key,dest,processed))
return true;
}
return false;
}
private class pair{
String vname;
String psf;
}
public boolean bfs(String source,String dest) { // breadth first search
HashMap<String ,Boolean> processed=new HashMap<>();
LinkedList<pair> queue=new LinkedList<>();
pair sp=new pair();
sp.vname=source;
sp.psf=source;
queue.addLast(sp);
while(!queue.isEmpty()) {
pair rp=queue.removeFirst();
if(processed.containsKey(rp.vname))
continue;
processed.put(rp.vname,true);
if(containsEdge(rp.vname,dest)) {
System.out.println(rp.psf+dest);
return true;
}
vertex vtx=this.vertcs.get(rp.vname);
ArrayList<String> nbrs=new ArrayList<>(vtx.nbrs.keySet());
for(String nbr:nbrs) {
if(!processed.containsKey(nbr)) {
pair np=new pair();
np.vname=nbr;
np.psf=rp.psf+nbr;
queue.addLast(np);
}
}
}
return false;
}
public boolean dfs(String source,String dest) { //deapth first search
LinkedList<pair> stack=new LinkedList<>();
HashMap<String,Boolean> processed=new HashMap<>();
pair sp=new pair();
sp.vname=source;
sp.psf=source;
stack.addFirst(sp);
while(!stack.isEmpty()) {
pair rp=stack.removeFirst();
if(processed.containsKey(rp.vname))
continue;
processed.put(rp.vname,true);
if(containsEdge(rp.vname,dest)) {
System.out.println(rp.psf+dest);
return true;
}
vertex vtx=this.vertcs.get(rp.vname);
ArrayList<String > nbrs=new ArrayList<>(vtx.nbrs.keySet());
for(String nbr:nbrs) {
if(!processed.containsKey(nbr)) {
pair np=new pair();
np.vname=nbr;
np.psf=rp.psf+nbr;
stack.addFirst(np);
}
}
}
return false;
}
public void bft() { //breadth first traversal
HashMap<String ,Boolean> processed=new HashMap<>();
LinkedList<pair> queue=new LinkedList<>();
ArrayList<String> keys=new ArrayList<>(this.vertcs.keySet());
for(String key:keys) {
if(processed.containsKey(key))
continue;
pair sp=new pair();
sp.vname=key;
sp.psf=key;
queue.addLast(sp);
while(!queue.isEmpty()) {
pair rp=queue.removeFirst();
if(processed.containsKey(rp.vname))
continue;
processed.put(rp.vname,true);
System.out.println(rp.vname+" via "+rp.psf);
vertex vtx=this.vertcs.get(rp.vname);
ArrayList<String> nbrs=new ArrayList<>(vtx.nbrs.keySet());
for(String nbr:nbrs) {
if(!processed.containsKey(nbr)) {
pair np=new pair();
np.vname=nbr;
np.psf=rp.psf+nbr;
queue.addLast(np);
}
}
}
}
}
public void dft() { //deapt first traversal
HashMap<String ,Boolean> processed=new HashMap<>();
LinkedList<pair> stack=new LinkedList<>();
ArrayList<String> keys=new ArrayList<>(this.vertcs.keySet());
for(String key:keys) {
pair sp=new pair();
sp.vname=key;
sp.psf=key;
stack.addFirst(sp);
while(!stack.isEmpty()) {
pair rp=stack.removeFirst();
if(processed.containsKey(rp.vname))
continue;
processed.put(rp.vname,true);
System.out.println(rp.vname+" via "+rp.psf);
vertex vtx=this.vertcs.get(rp.vname);
ArrayList<String> nbrs=new ArrayList<>(vtx.nbrs.keySet());
for(String nbr:nbrs) {
if(!processed.containsKey(nbr)) {
pair np=new pair();
np.vname=nbr;
np.psf=rp.psf+nbr;
stack.addFirst(np);
}
}
}
}
}
public boolean isCyclic() {
HashMap<String ,Boolean> processed=new HashMap<>();
LinkedList<pair> queue=new LinkedList<>();
ArrayList<String> keys=new ArrayList<>(this.vertcs.keySet());
for(String key:keys) {
if(processed.containsKey(key))
continue;
pair sp=new pair();
sp.vname=key;
sp.psf=key;
queue.addLast(sp);
while(!queue.isEmpty()) {
pair rp=queue.removeFirst();
if(processed.containsKey(rp.vname))
return true;
processed.put(rp.vname,true);
vertex vtx=this.vertcs.get(rp.vname);
ArrayList<String> nbrs=new ArrayList<>(vtx.nbrs.keySet());
for(String nbr:nbrs) {
if(!processed.containsKey(nbr)) {
pair np=new pair();
np.vname=nbr;
np.psf=rp.psf+nbr;
queue.addLast(np);
}
}
}
}
return false;
}
public boolean isConnected() {
int flag=0;
HashMap<String ,Boolean> processed=new HashMap<>();
LinkedList<pair> queue=new LinkedList<>();
ArrayList<String> keys=new ArrayList<>(this.vertcs.keySet());
for(String key:keys) {
if(processed.containsKey(key))
continue;
flag++;
pair sp=new pair();
sp.vname=key;
sp.psf=key;
queue.addLast(sp);
while(!queue.isEmpty()) {
pair rp=queue.removeFirst();
if(processed.containsKey(rp.vname))
continue;
processed.put(rp.vname,true);
vertex vtx=this.vertcs.get(rp.vname);
ArrayList<String> nbrs=new ArrayList<>(vtx.nbrs.keySet());
for(String nbr:nbrs) {
if(!processed.containsKey(nbr)) {
pair np=new pair();
np.vname=nbr;
np.psf=rp.psf+nbr;
queue.addLast(np);
}
}
}
}
if(flag>=2)
return false;
else
return true;
}
public boolean isTree() {
return !isCyclic()&&isConnected();
}
public ArrayList<ArrayList<String>> getConnectedComp() {
ArrayList<ArrayList<String>> ans=new ArrayList<>();
HashMap<String ,Boolean> processed=new HashMap<>();
LinkedList<pair> queue=new LinkedList<>();
ArrayList<String> keys=new ArrayList<>(this.vertcs.keySet());
for(String key:keys) {
if(processed.containsKey(key))
continue;
ArrayList<String> subans=new ArrayList<>();
pair sp=new pair();
sp.vname=key;
sp.psf=key;
queue.addLast(sp);
while(!queue.isEmpty()) {
pair rp=queue.removeFirst();
if(processed.containsKey(rp.vname))
continue;
processed.put(rp.vname,true);
subans.add(rp.vname);
vertex vtx=this.vertcs.get(rp.vname);
ArrayList<String> nbrs=new ArrayList<>(vtx.nbrs.keySet());
for(String nbr:nbrs) {
if(!processed.containsKey(nbr)) {
pair np=new pair();
np.vname=nbr;
np.psf=rp.psf+nbr;
queue.addLast(np);
}
}
}
ans.add(subans);
}
return ans;
}
private class PrimsPair implements Comparable<PrimsPair>{
String vname;
String acqvname;
int cost;
public int compareTo(PrimsPair o) {
return o.cost-this.cost;
}
}
public Graph prims() {
HashMap<String ,PrimsPair> map=new HashMap<>();
GenericHeap<PrimsPair> heap=new GenericHeap<>();
Graph mst=new Graph();
for(String vrtx:this.vertcs.keySet()) {
PrimsPair np=new PrimsPair();
np.acqvname=null;
np.vname=vrtx;
np.cost=Integer.MAX_VALUE;
heap.add(np);
map.put(vrtx, np);
}
while(!heap.isEmpty()) {
PrimsPair rp=heap.remove();
map.remove(rp.vname);
if(rp.acqvname==null) {
mst.addVertex(rp.vname);
}else {
mst.addVertex(rp.vname);
mst.addEdge(rp.vname, rp.acqvname, rp.cost);
}
for(String nbr:this.vertcs.get(rp.vname).nbrs.keySet()) {
if(map.containsKey(nbr)) {
//old cost that is from diff path stored in map
int oc=map.get(nbr).cost;
// cost that present vname need cost to go to nbr
int nc=this.vertcs.get(rp.vname).nbrs.get(nbr);
if(nc<oc) {
PrimsPair gp=map.get(nbr);
gp.acqvname=rp.vname;
gp.cost=nc;
heap.updatePriority(gp);
}
}
}
}
return mst;
}
private class DijktsraPair implements Comparable<DijktsraPair>{
String vname;
String psf;
int cost;
public int compareTo(DijktsraPair o) {
return o.cost-this.cost;
}
}
public HashMap<String,Integer> Dijktsra(String source) {
HashMap<String ,DijktsraPair> map=new HashMap<>();
GenericHeap<DijktsraPair> heap=new GenericHeap<>();
HashMap<String,Integer> ans =new HashMap<>();
for(String vrtx:this.vertcs.keySet()) {
DijktsraPair np=new DijktsraPair();
np.psf="";
np.vname=vrtx;
np.cost=Integer.MAX_VALUE;
if(vrtx==source) {
np.cost=0;
np.psf=source;
}
heap.add(np);
map.put(vrtx, np);
}
while(!heap.isEmpty()) {
DijktsraPair rp=heap.remove();
map.remove(rp.vname);
ans.put(rp.vname,rp.cost);
for(String nbr:this.vertcs.get(rp.vname).nbrs.keySet()) {
if(map.containsKey(nbr)) {
//old cost that is from diff path stored in map
int oc=map.get(nbr).cost;
// cost that present vname need cost to go to nbr
int nc=rp.cost+this.vertcs.get(rp.vname).nbrs.get(nbr);
if(nc<oc) {
DijktsraPair gp=map.get(nbr);
gp.psf=rp.psf+nbr;
gp.cost=nc;
heap.updatePriority(gp);
}
}
}
}
return ans;
}
}

View File

@ -0,0 +1,64 @@
package DataStructures.HashMap.Hashing;
/*
* this is algo which implies common mathematical set theory concept
* called intersection in which result is common values of both the sets
* here metaphor of sets is HashMap
Test Case:
Scanner scn=new Scanner(System.in);
int len =scn.nextInt();
int arr[]=new int[len];
int arr2[]=new int[len];
for(int i=0;i<2*len;i++) {
if(i<len)
arr[i]=scn.nextInt();
if(i>=len) {
arr2[i-len]=scn.nextInt();
}
}
System.out.println(Main(arr,arr2));
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Intersection {
public static ArrayList Main(int arr[],int arr2[]) {
HashMap<Integer,Integer> hmap=new HashMap<>();
HashMap<Integer,Integer> hmap2=new HashMap<>();
for(int i=0;i<arr.length;i++) {
if(hmap.containsKey(arr[i])) {
int val=hmap.get(arr[i]);
hmap.put(arr[i],val+1);
}else
hmap.put(arr[i],1);
}
ArrayList<Integer> res=new ArrayList<>();
for(int i=0;i<arr2.length;i++) {
if(hmap.containsKey(arr2[i])&&hmap.get(arr2[i])>0) {
int val=hmap.get(arr2[i]);
hmap.put(arr2[i],val-1);
res.add(arr2[i]);
}
}
return res;
}
public Intersection() {
}
}

View File

@ -1,63 +0,0 @@
package DataStructures.HashMap.Hashing;
class LinkedList {
private Node Head;
private int size;
public LinkedList() {
Head = null;
size = 0;
}
public void insert(int data) {
Node newnode = new Node(data);
size++;
if(Head == null) {
Head = newnode;
}
else {
newnode.next = Head;
Head = newnode;
}
}
public void delete(int data) {
if(size == 0) {
System.out.println("UnderFlow!");
return;
}
else {
Node curr = Head;
if (curr.data == data) {
Head = curr.next;
size--;
return;
}
else {
while(curr.next.next != null) {
if(curr.next.data == data){
curr.next = curr.next.next;
return;
}
}
System.out.println("Key not Found");
}
}
}
public void display() {
Node temp = Head;
while(temp != null) {
System.out.printf("%d ",temp.data);
temp = temp.next;
}
System.out.println();
}
}

View File

@ -1,11 +0,0 @@
package DataStructures.HashMap.Hashing;
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}

View File

@ -0,0 +1,141 @@
package DataStructures.Lists;
/*
* This class implements a SinglyLinked List.
* A linked list is similar to an array, it hold values.
* However, links in a linked list do not have indexes. With
* a linked list you do not need to predetermine it's size as
* it grows and shrinks as it is edited.
*it has functions called mid that gives node at mid
* in addn to linked list there is algo that
* construct a linked list with alternate sums of linked list
* and added to new one and add mid value
* i.e sum of first and last value of inital list
Test Case:
LinkedList LL1 = new LinkedList();
Scanner scn=new Scanner(System.in);
int numNodes=scn.nextInt();
for(int i=0;i<2*numNodes;i++) {
LL1.addLast(scn.nextInt());
}
LL1.display();
LinkedList LL2=new LinkedList();
LL2.formLL2(LL1);
LL2.display();
LinkedList LL3=new LinkedList();
LL3.formLL3(LL1);
LL3.display();
Node MID=LL1.midValue();
System.out.println(MID.data);
LinkedList updLL1=new LinkedList();
updLL1.formRes(LL1,LL2,LL3,MID);
updLL1.display();
updLL1.Size();
*/
import java.util.*;
import java.lang.*;
import java.io.*;
class LinkedList {
private class Node{
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public Node head = null;
public Node tail = null;
private int size=0;
public void addLast(int data) {
Node newNode = new Node(data);
if(this.head == null) {
this.head = newNode;
this.tail = newNode;
this.size++;
}
else {
this.tail.next = newNode;
this.tail = newNode;
this.size++;
}
}
public void display() {
Node current = this.head;
if(this.head == null) {
return;
}
while(current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public void formLL2(LinkedList LL1) {
Node current=LL1.head;
while(current.next!=null&&current.next.next!=null) {
int sum=current.data+current.next.next.data;
this.addLast(sum);
current=current.next.next;
}
}
public void formLL3(LinkedList LL1) {
Node current=LL1.head.next;
while(current.next!=null&&current.next.next!=null) {
int sum=current.data+current.next.next.data;
this.addLast(sum);
current=current.next.next;
}
}
public Node mid() {
Node slow=this.head;
Node fast=this.head;
while(fast.next!=null && fast.next.next!=null) {
slow=slow.next;
fast=fast.next.next;
}
return slow;
}
public Node midValue() {
int sum=this.head.data+this.tail.data;
Node mid=new Node(sum);
return mid;
}
public void formRes(LinkedList LL1,LinkedList LL2,LinkedList LL3,Node MID) {
Node LL1mid=LL1.mid();
Node currentLL1=LL1.head;
Node currentLL2=LL2.head;
Node currentLL3=LL3.head;
while(currentLL1!=null) {
this.addLast(currentLL1.data);
if(currentLL2!=null) {
this.addLast(currentLL2.data);
currentLL2=currentLL2.next;
}else if(currentLL1.equals(LL1mid)) {
this.addLast(MID.data);
}
else if(currentLL2==null&&currentLL3!=null) {
this.addLast(currentLL3.data);
currentLL3=currentLL3.next;
}
currentLL1=currentLL1.next;
}
}
public void Size() {
System.out.println(this.size);
}
}

View File

@ -0,0 +1,137 @@
package DataStructures.Trees;
/*
* Avl is algo that balance itself while adding new alues to tree
* by rotating branches of binary tree and make itself Binary seaarch tree
* there are four cases which has to tackle
* rotating - left right ,left left,right right,right left
Test Case:
AVLTree tree=new AVLTree();
tree.insert(20);
tree.insert(25);
tree.insert(30);
tree.insert(10);
tree.insert(5);
tree.insert(15);
tree.insert(27);
tree.insert(19);
tree.insert(16);
tree.display();
*/
public class AVLTree {
private class Node{
int data;
int height;
Node left;
Node right;
Node(int data){
this.data=data;
this.height=1;
}
}
private Node root;
public void insert(int data) {
this.root=insert(this.root,data);
}
private Node insert(Node node,int item) {
if(node==null) {
Node add=new Node(item);
return add;
}
if(node.data>item) {
node.left=insert(node.left,item);
}
if(node.data<item) {
node.right=insert(node.right,item);
}
node.height=Math.max(height(node.left),height(node.right))+1;
int bf=bf(node);
//LL case
if(bf>1&&item<node.left.data)
return rightRotate(node);
//RR case
if(bf<-1&&item>node.right.data)
return leftRotate(node);
//RL case
if(bf<-1&&item<node.right.data) {
node.right=rightRotate(node.right);
return leftRotate(node);
}
//LR case
if(bf>1&&item>node.left.data) {
node.left=leftRotate(node.left);
return rightRotate(node);
}
return node;
}
public void display() {
this.display(this.root);
System.out.println(this.root.height);
}
private void display (Node node) {
String str="";
if(node.left!=null)
str+=node.left.data+"=>";
else
str+="END=>";
str+=node.data+"";
if(node.right!=null)
str+="<="+node.right.data;
else
str+="<=END";
System.out.println(str);
if(node.left!=null)
display(node.left);
if(node.right!=null)
display(node.right);
}
private int height(Node node) {
if(node==null) {
return 0;
}
return node.height;
}
private int bf(Node node) {
if(node==null)
return 0;
return height(node.left)-height(node.right);
}
private Node rightRotate(Node c) {
Node b=c.left;
Node T3=b.right;
b.right=c;
c.left=T3;
c.height=Math.max(height(c.left),height(c.right))+1;
b.height=Math.max(height(b.left),height(b.right))+1;
return b;
}
private Node leftRotate(Node c) {
Node b=c.right;
Node T3=b.left;
b.left=c;
c.right=T3;
c.height=Math.max(height(c.left),height(c.right))+1;
b.height=Math.max(height(b.left),height(b.right))+1;
return b;
}
}

View File

@ -0,0 +1,77 @@
package DynamicProgramming;
/*
* this is an important Algo in which
* we have starting and ending of board and we have to reach
* we have to count no. of ways
* that help to reach end point i.e number by rolling dice
* which have 1 to 6 digits
Test Case:
here target is 10
int n=10;
startAlgo();
System.out.println(bpR(0,n));
System.out.println(endAlgo()+"ms");
int[] strg=new int [n+1];
startAlgo();
System.out.println(bpRS(0,n,strg));
System.out.println(endAlgo()+"ms");
startAlgo();
System.out.println(bpIS(0,n,strg));
System.out.println(endAlgo()+"ms");
*/
public class BoardPath {
public static long startTime;
public static long endTime;
public static void startAlgo() {
startTime=System.currentTimeMillis();
}
public static long endAlgo() {
endTime=System.currentTimeMillis();
return endTime-startTime;
}
public static int bpR(int start,int end){
if(start==end) {
return 1;
}
else if(start>end)
return 0;
int count=0;
for(int dice=1;dice<=6;dice++) {
count+=bpR(start+dice,end);
}
return count;
}
public static int bpRS(int curr,int end,int strg[]){
if(curr==end) {
return 1;
}
else if(curr>end)
return 0;
if(strg[curr]!=0)
return strg[curr];
int count=0;
for(int dice=1;dice<=6;dice++) {
count+=bpRS(curr+dice,end,strg);
}
strg[curr]=count;
return count;
}
public static int bpIS(int curr,int end,int[]strg){
strg[end]=1;
for(int i=end-1;i>=0;i--) {
int count=0;
for(int dice=1;dice<=6&&dice+i<strg.length;dice++) {
count+=strg[i+dice];
}
strg[i]=count;
}
return strg[0];
}
}

View File

@ -0,0 +1,97 @@
package DynamicProgramming;
/*
* here is a important algo in this we have to count
* maximum no. of different binary strings which doesnot have
* consectuive 1s
Test Case:
int n=30;
startAlgo();
System.out.println(numStrIS(n));
System.out.println(endAlgo()+"ms");
startAlgo();
CountNumBinaryStr out=new CountNumBinaryStr();
System.out.println(out.numStrR(n).ans);
System.out.println(endAlgo()+"ms");
startAlgo();
System.out.println(countStrings(n,0));
System.out.println(endAlgo()+"ms");
*/
public class CountNumBinaryStr {
public static long startTime;
public static long endTime;
public static void startAlgo() {
startTime=System.currentTimeMillis();
}
public static long endAlgo() {
endTime=System.currentTimeMillis();
return endTime-startTime;
}
public static int numStrIS(int n) {
int[] zeros=new int[n];
int []ones=new int[n];
//seed
zeros[0]=1;
ones[0]=1;
for(int i=1;i<n;i++) {
zeros[i]=zeros[i-1]+ones[i-1];
ones[i]=zeros[i-1];
}
int ans=zeros[n-1]+ones[n-1];
return ans;
}
private class Binary{
int ones;
int zeros;
int ans;
Binary(int ones,int zeros){
this.ones=ones;
this.zeros=zeros;
this.ans=0;
}
Binary(){}
}
public Binary numStrR(int n) {
if(n==1) {
Binary br=new Binary(1,1);
return br;
}
Binary mr=new Binary();
Binary rr=numStrR(n-1);
mr.zeros=rr.zeros+rr.ones;
mr.ones=rr.zeros;
mr.ans=mr.zeros+mr.ones;
return mr;
}
public static int countStrings(int n, int lastDigit)
{
if (n == 0) {
return 0;
}
// if only one digit is left
if (n == 1) {
return (lastDigit == 1) ? 1: 2;
}
// if last digit is 0, we can have both 0 and 1 at current pos
if (lastDigit == 0) {
return countStrings(n - 1, 0) + countStrings(n - 1, 1);
}
// if last digit is 1, we can have only 0 at current position
else {
return countStrings(n - 1, 0);
}
}
}