public HashSet<HashSet<Integer>> getAllSubset(HashSet<Integer> set) {
int[] superSet = getHashToIntArray(set);
double max = Math.pow(2, superSet.length);
HashSet<HashSet<Integer>> result = new HashSet<HashSet<Integer>>();
for(int i=1; i<=max; i++) {
int n=i;
HashSet<Integer> subset = new HashSet<Integer>();
for(int j=0; j<superSet.length; j++) {
if(n%2==1)
subset.add(superSet[j]);
n=n/2;
}
result.add(subset);
}
return result;
}
private int[] getHashToIntArray(HashSet<Integer> set) {
int[] result = new int[set.size()];
int i=0;
for(Integer n: set) {
result[i]=n;
i++;
}
return result;
}
Sunday, December 27, 2015
Friday, December 25, 2015
Convert Numeric to Binary
With Recursion:
public StringBuffer convertToBinary(int n) {
if (n<2) return new StringBuffer().append(n);
return new StringBuffer().insert(0, n%2).insert(0, convertToBinary(n/2));
}
Without Recursion:
public String convertToBinary(int n) {
StringBuffer result = new StringBuffer();
while(n>0) {
result.insert(0, n%2);
n=n/2;
}
return result.toString();
}
public StringBuffer convertToBinary(int n) {
if (n<2) return new StringBuffer().append(n);
return new StringBuffer().insert(0, n%2).insert(0, convertToBinary(n/2));
}
Without Recursion:
public String convertToBinary(int n) {
StringBuffer result = new StringBuffer();
while(n>0) {
result.insert(0, n%2);
n=n/2;
}
return result.toString();
}
Saturday, December 19, 2015
Reversing Parts of a LinkedList
Initial LinkedList: 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
Input: count = 3
Output: 3, 2, 1, 6, 5, 4, 9, 8, 7, 0,
Input: count = 4
Output: 4, 3, 2, 1, 8, 7, 6, 5, 0, 9,
Input: count = 7
Output: 7, 6, 5, 4, 3, 2, 1, 0, 9, 8,
public void compute(int count) {
LinkedList L = this;
int i=0;
StringBuffer sb = new StringBuffer();
Stack<Integer> S = new Stack<Integer>();
while(L!=null) {
if(i<count) {
S.push(L.data);
L=L.next;
i++;
} else {
while(!S.isEmpty())
sb.append(S.pop()).append(", ");
i=0;
}
}
while(!S.isEmpty())
sb.append(S.pop()).append(", ");
System.out.println(sb.toString());
}
Input: count = 3
Output: 3, 2, 1, 6, 5, 4, 9, 8, 7, 0,
Input: count = 4
Output: 4, 3, 2, 1, 8, 7, 6, 5, 0, 9,
Input: count = 7
Output: 7, 6, 5, 4, 3, 2, 1, 0, 9, 8,
public void compute(int count) {
LinkedList L = this;
int i=0;
StringBuffer sb = new StringBuffer();
Stack<Integer> S = new Stack<Integer>();
while(L!=null) {
if(i<count) {
S.push(L.data);
L=L.next;
i++;
} else {
while(!S.isEmpty())
sb.append(S.pop()).append(", ");
i=0;
}
}
while(!S.isEmpty())
sb.append(S.pop()).append(", ");
System.out.println(sb.toString());
}
Inserting an Array of Elements in a Linked List
public void insert(int... data) {
LinkedList L = this;
while(L.next!=null) {
L=L.next;
}
int size=data.length;
for(int i=0; i<size; i++) {
L.next=new LinkedList(data[i]);
L=L.next;
}
}
LinkedList L = this;
while(L.next!=null) {
L=L.next;
}
int size=data.length;
for(int i=0; i<size; i++) {
L.next=new LinkedList(data[i]);
L=L.next;
}
}
Tuesday, December 15, 2015
Get All SubArray of a given Array
public ArrayList<ArrayList<Integer>> getAllSubArray(int[] a) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
for(int subarray_size=1; subarray_size<a.length; subarray_size++) {
ArrayList<Integer> newList = new ArrayList<Integer>();
for(int i=0; i<a.length; i++) {
if((subarray_size+i)>a.length-1)
break;
newList.add(a[i+subarray_size]);
result.add(new ArrayList<>(newList));
}
}
return result;
}
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
for(int subarray_size=1; subarray_size<a.length; subarray_size++) {
ArrayList<Integer> newList = new ArrayList<Integer>();
for(int i=0; i<a.length; i++) {
if((subarray_size+i)>a.length-1)
break;
newList.add(a[i+subarray_size]);
result.add(new ArrayList<>(newList));
}
}
return result;
}
Find if a Tree is a Mirror copy of another Tree
public boolean isMirrorTrees(BinaryTree T1, BinaryTree T2) {
if(T1==null && T2==null)
return true;
if(T1.data!=T2.data)
return false;
if((T1==null && T2!=null) || (T2==null && T1!=null))
return false;
if(isMirrorTrees(T1.left, T2.right)
&& isMirrorTrees(T2.left, T1.right))
return true;
return false;
}
if(T1==null && T2==null)
return true;
if(T1.data!=T2.data)
return false;
if((T1==null && T2!=null) || (T2==null && T1!=null))
return false;
if(isMirrorTrees(T1.left, T2.right)
&& isMirrorTrees(T2.left, T1.right))
return true;
return false;
}
Create a Mirror Copy of a Binary Tree
public BinaryTree MirorCopyOfTree(BinaryTree T) {
BinaryTree newTree = new BinaryTree(T.data);
if(T.left!=null)
newTree.right=MirorCopyOfTree(T.left);
if(T.right!=null)
newTree.left=MirorCopyOfTree(T.right);
return newTree;
}
BinaryTree newTree = new BinaryTree(T.data);
if(T.left!=null)
newTree.right=MirorCopyOfTree(T.left);
if(T.right!=null)
newTree.left=MirorCopyOfTree(T.right);
return newTree;
}
Labels:
Algorithm,
Binary Tree,
Java,
Jeevan,
Jeevan Rex,
Jeevanus
Monday, December 14, 2015
get Root to given Node path in a Binary Tree
public void rootToNode(int data) {
getRootToNodePath(this, data, new StringBuffer(), false);
}
private void getRootToNodePath(BinarySearchTree T, int data, StringBuffer sb, boolean isFound) {
if(T!=null && !isFound) {
sb.append(T.data).append(", ");
if(T.data==data) {
System.out.println(sb.toString());
isFound = true;
return;
} else {
getRootToNodePath(T.left, data, new StringBuffer(sb), isFound);
getRootToNodePath(T.right, data, new StringBuffer(sb), isFound);
}
}
}
getRootToNodePath(this, data, new StringBuffer(), false);
}
private void getRootToNodePath(BinarySearchTree T, int data, StringBuffer sb, boolean isFound) {
if(T!=null && !isFound) {
sb.append(T.data).append(", ");
if(T.data==data) {
System.out.println(sb.toString());
isFound = true;
return;
} else {
getRootToNodePath(T.left, data, new StringBuffer(sb), isFound);
getRootToNodePath(T.right, data, new StringBuffer(sb), isFound);
}
}
}
Check if two Binary Tree are same
public boolean isTreesSame(BinaryTree T1, BinaryTree T2) {
if(T1==null && T2==null)
return true;
if(T1==null || T2==null)
return false;
if(T1.data==T2.data
&& isTreesSame(T1.left, T2.left)
&& isTreesSame(T1.right, T2.right))
return true;
return false;
}
if(T1==null && T2==null)
return true;
if(T1==null || T2==null)
return false;
if(T1.data==T2.data
&& isTreesSame(T1.left, T2.left)
&& isTreesSame(T1.right, T2.right))
return true;
return false;
}
Sunday, December 13, 2015
Delete Node from Binary Search Tree
// Binary Search Tree full program is available here: link
private BinarySearchTree ParentNode; //Parent Node of the node to delete
private boolean LeftOrRightFlag; //Deleting node is Left from parent means true, else Right means false
public void DeleteNode(int data) {
DeleteNode(this, data);
}
private void DeleteNode(BinarySearchTree T, int data) {
if(T==null) return;
if(data==T.data) { //delete root note
T.data=getMin(T.right).data;
DeleteNode(T.right, T.data);
} else {
BinarySearchTree Current = findNode(T, data);
if(Current.left==null && Current.right==null)
if(LeftOrRightFlag)
ParentNode.left=null;
else
ParentNode.right=null;
else if(Current.left==null)
if(LeftOrRightFlag)
ParentNode.left=Current.right;
else
ParentNode.right=Current.right;
else if(Current.right==null)
if(LeftOrRightFlag)
ParentNode.left=Current.left;
else
ParentNode.right=Current.left;
else {//Current node has both children
Current.data=getMin(Current.right).data;
DeleteNode(T.right, Current.data);
}
}
}
private BinarySearchTree getMin(BinarySearchTree T) {
while(T.left!=null)
T=T.left;
return T;
}
public BinarySearchTree findNode(BinarySearchTree T,int data) { //except root
if(data==T.data)
return T;
else if(data<T.data) {
ParentNode=T;
LeftOrRightFlag=true;
return findNode(T.left, data);
} else {
ParentNode=T;
LeftOrRightFlag=false;
return findNode(T.right, data);
}
}
private BinarySearchTree ParentNode; //Parent Node of the node to delete
private boolean LeftOrRightFlag; //Deleting node is Left from parent means true, else Right means false
public void DeleteNode(int data) {
DeleteNode(this, data);
}
private void DeleteNode(BinarySearchTree T, int data) {
if(T==null) return;
if(data==T.data) { //delete root note
T.data=getMin(T.right).data;
DeleteNode(T.right, T.data);
} else {
BinarySearchTree Current = findNode(T, data);
if(Current.left==null && Current.right==null)
if(LeftOrRightFlag)
ParentNode.left=null;
else
ParentNode.right=null;
else if(Current.left==null)
if(LeftOrRightFlag)
ParentNode.left=Current.right;
else
ParentNode.right=Current.right;
else if(Current.right==null)
if(LeftOrRightFlag)
ParentNode.left=Current.left;
else
ParentNode.right=Current.left;
else {//Current node has both children
Current.data=getMin(Current.right).data;
DeleteNode(T.right, Current.data);
}
}
}
private BinarySearchTree getMin(BinarySearchTree T) {
while(T.left!=null)
T=T.left;
return T;
}
public BinarySearchTree findNode(BinarySearchTree T,int data) { //except root
if(data==T.data)
return T;
else if(data<T.data) {
ParentNode=T;
LeftOrRightFlag=true;
return findNode(T.left, data);
} else {
ParentNode=T;
LeftOrRightFlag=false;
return findNode(T.right, data);
}
}
Saturday, December 12, 2015
get InOrder sucessor of a given node in a BST
private Stack<BinarySearchTree> S;
public int inOrderSuccessor(int data) {
S = new Stack<BinarySearchTree>();
BinarySearchTree Current = getNode(this, data);
if(Current.right!=null) {
return getMin(Current.right).data;
} else {
BinarySearchTree parent = S.pop();
if(parent.left==Current)
return parent.data;
else
return S.pop().data;
}
}
private BinarySearchTree getMin(BinarySearchTree T) {
while(T.left!=null)
T=T.left;
return T;
}
private BinarySearchTree getNode(BinarySearchTree T, int data) {
if(T==null) return null;
else if(data==T.data) {
return T;
}
else if(data<T.data) {
S.add(T);
return getNode(T.left, data);
}
else {
S.add(T);
return getNode(T.right, data);
}
}
public int inOrderSuccessor(int data) {
S = new Stack<BinarySearchTree>();
BinarySearchTree Current = getNode(this, data);
if(Current.right!=null) {
return getMin(Current.right).data;
} else {
BinarySearchTree parent = S.pop();
if(parent.left==Current)
return parent.data;
else
return S.pop().data;
}
}
private BinarySearchTree getMin(BinarySearchTree T) {
while(T.left!=null)
T=T.left;
return T;
}
private BinarySearchTree getNode(BinarySearchTree T, int data) {
if(T==null) return null;
else if(data==T.data) {
return T;
}
else if(data<T.data) {
S.add(T);
return getNode(T.left, data);
}
else {
S.add(T);
return getNode(T.right, data);
}
}
is Binary Tree a Binary Search Tree
public boolean isBinarySearchTree() {
return isBinaryTree(this, (-10^23), 10^23);
}
private boolean isBinarySearchTree(BinaryTree T, int min, int max) {
if(T==null) return true;
if(T.data>min && T.data<max
&& isBinaryTree(T.left, min, T.data)
&& isBinaryTree(T.right, T.data, max))
return true;
return false;
}
return isBinaryTree(this, (-10^23), 10^23);
}
private boolean isBinarySearchTree(BinaryTree T, int min, int max) {
if(T==null) return true;
if(T.data>min && T.data<max
&& isBinaryTree(T.left, min, T.data)
&& isBinaryTree(T.right, T.data, max))
return true;
return false;
}
Wednesday, December 9, 2015
Insert Sorted Array into a Binary Search Tree with minimum height
public class BinarySearchTree {
BinarySearchTree left, right;
int data;
public BinarySearchTree(int... SortedArrayOfdata) {
int mid=SortedArrayOfdata.length/2;
this.left=null;
this.right=null;
this.data=SortedArrayOfdata[mid];
insertSortedArray(SortedArrayOfdata, 0, mid-1);
insertSortedArray(SortedArrayOfdata, mid+1, SortedArrayOfdata.length-1);
}
private void insertSortedArray(int[] a, int startIndex, int endIndex) {
if(startIndex<=endIndex) {
int mid=(startIndex+endIndex)/2;
insert(a[mid]); //Insert method is available here: link
insertSortedArray(a, startIndex, mid-1);
insertSortedArray(a, mid+1, endIndex);
}
}
}
Example Input:
BinarySearchTree BST = new BinarySearchTree(0,1,2,3,4,5,6,7,8,9,10,11,12,13);
BinarySearchTree left, right;
int data;
public BinarySearchTree(int... SortedArrayOfdata) {
int mid=SortedArrayOfdata.length/2;
this.left=null;
this.right=null;
this.data=SortedArrayOfdata[mid];
insertSortedArray(SortedArrayOfdata, 0, mid-1);
insertSortedArray(SortedArrayOfdata, mid+1, SortedArrayOfdata.length-1);
}
private void insertSortedArray(int[] a, int startIndex, int endIndex) {
if(startIndex<=endIndex) {
int mid=(startIndex+endIndex)/2;
insert(a[mid]); //Insert method is available here: link
insertSortedArray(a, startIndex, mid-1);
insertSortedArray(a, mid+1, endIndex);
}
}
}
Example Input:
BinarySearchTree BST = new BinarySearchTree(0,1,2,3,4,5,6,7,8,9,10,11,12,13);
Tuesday, December 8, 2015
Quick Sort
import java.util.Random;
public class QuickSort {
int[] a;
public QuickSort(int[] a) {
this.a = a;
}
public int[] QSort() {
QSort(this.a, 0, this.a.length-1);
return a;
}
private void QSort(int[] a, int startIndex, int endIndex) {
if(startIndex<endIndex) {
int PartionIndex = RandomizedPartition(startIndex, endIndex);
QSort(a, startIndex, PartionIndex-1);
QSort(a, PartionIndex+1, endIndex);
}
}
private int RandomizedPartition(int startIndex, int endIndex) {
/* Worst Case of QuickSort is O(n^2)
The possibility for WorstCase in QuickSort is very low
RandomizedPartition will help reducing the probability of the occurrence of worst case*/
int PivotIndex=new Random().nextInt(endIndex-startIndex)+startIndex;
swap(PivotIndex, endIndex);
return Partition(startIndex, endIndex);
}
private int Partition(int startIndex, int endIndex) {
int Pivot=a[endIndex];
int PivotIndex=startIndex;
for(int i=startIndex; i<endIndex; i++) {
if(a[i]<=Pivot) {
swap(i, PivotIndex);
PivotIndex++;
}
}
swap(PivotIndex, endIndex);
return PivotIndex;
}
private void swap(int IndexA, int IndexB) {
int temp=a[IndexA];
a[IndexA]=a[IndexB];
a[IndexB]=temp;
}
}
public class QuickSort {
int[] a;
public QuickSort(int[] a) {
this.a = a;
}
public int[] QSort() {
QSort(this.a, 0, this.a.length-1);
return a;
}
private void QSort(int[] a, int startIndex, int endIndex) {
if(startIndex<endIndex) {
int PartionIndex = RandomizedPartition(startIndex, endIndex);
QSort(a, startIndex, PartionIndex-1);
QSort(a, PartionIndex+1, endIndex);
}
}
private int RandomizedPartition(int startIndex, int endIndex) {
/* Worst Case of QuickSort is O(n^2)
The possibility for WorstCase in QuickSort is very low
RandomizedPartition will help reducing the probability of the occurrence of worst case*/
int PivotIndex=new Random().nextInt(endIndex-startIndex)+startIndex;
swap(PivotIndex, endIndex);
return Partition(startIndex, endIndex);
}
private int Partition(int startIndex, int endIndex) {
int Pivot=a[endIndex];
int PivotIndex=startIndex;
for(int i=startIndex; i<endIndex; i++) {
if(a[i]<=Pivot) {
swap(i, PivotIndex);
PivotIndex++;
}
}
swap(PivotIndex, endIndex);
return PivotIndex;
}
private void swap(int IndexA, int IndexB) {
int temp=a[IndexA];
a[IndexA]=a[IndexB];
a[IndexB]=temp;
}
}
Selection Sort
public int[] SelectionSort(int[] a) {
for(int i=0; i<a.length; i++) {
int min=i;
for(int j=i+1; j<a.length; j++) {
if(a[j]<=a[min])
min=j;
}
int temp=a[i];
a[i]=a[min];
a[min]=temp;
}
return a;
}
for(int i=0; i<a.length; i++) {
int min=i;
for(int j=i+1; j<a.length; j++) {
if(a[j]<=a[min])
min=j;
}
int temp=a[i];
a[i]=a[min];
a[min]=temp;
}
return a;
}
Sunday, December 6, 2015
Insertion Sort
public int[] InsertionSort(int[] input) {
for(int i=1; i<input.length; i++) {
int val=input[i];
int hole=i;
while(hole>0 && val<input[hole-1]) {
input[hole]=input[hole-1];
hole--;
}
input[hole]=val;
}
return input;
}
for(int i=1; i<input.length; i++) {
int val=input[i];
int hole=i;
while(hole>0 && val<input[hole-1]) {
input[hole]=input[hole-1];
hole--;
}
input[hole]=val;
}
return input;
}
Swap Two Integers without Temporary Variable
public static void DoSwaping(int a, int b) {
a=a+b;
b=a-b;
a=a-b;
System.out.println("a: "+a+"\nb: "+b);
}
public static void main(String[] args) {
DoSwaping(5, 9); // Example Input
}
a=a+b;
b=a-b;
a=a-b;
System.out.println("a: "+a+"\nb: "+b);
}
public static void main(String[] args) {
DoSwaping(5, 9); // Example Input
}
Bubble Sort
public int[] BubbleSort(int[] input) {
int size=input.length;
for(int i=0; i<size; i++) {
boolean flag = true;
int s=size-i-1;
for(int j=0; j<s; j++) {
if(input[j]>=input[j+1]) {
flag=false;
input[j] = input[j]+input[j+1];
input[j+1] = input[j]-input[j+1];
input[j] = input[j]-input[j+1];
}
}
if(flag) break;
}
return input;
}
int size=input.length;
for(int i=0; i<size; i++) {
boolean flag = true;
int s=size-i-1;
for(int j=0; j<s; j++) {
if(input[j]>=input[j+1]) {
flag=false;
input[j] = input[j]+input[j+1];
input[j+1] = input[j]-input[j+1];
input[j] = input[j]-input[j+1];
}
}
if(flag) break;
}
return input;
}
Merge Sort
public int[] MergeSort(int[] a) {
int mid = a.length/2;
if(mid<1) return a;
int[] left = new int[mid];
int i=0;
for(; i<left.length; i++)
left[i]=a[i];
left = MergeSort(left);
int[] right = new int[(a.length%2==1)?(mid+1):mid];
for(int j=0; j<right.length; j++) {
right[j]=a[i];
i++;
}
right = MergeSort(right);
return Merge(left, right);
}
private int[] Merge(int[] left, int[] right) {
int i, j, k; i=j=k=0;
int[] merged = new int[left.length+right.length];
while(i<left.length && j<right.length) {
if(left[i]<=right[j]) {
merged[k]=left[i];
i++;
} else if(left[i]>right[j]) {
merged[k]=right[j];
j++;
}
k++;
}
while(i<left.length) {
merged[k]=left[i];
i++; k++;
}
while(j<right.length) {
merged[k]=right[j];
j++; k++;
}
return merged;
}
int mid = a.length/2;
if(mid<1) return a;
int[] left = new int[mid];
int i=0;
for(; i<left.length; i++)
left[i]=a[i];
left = MergeSort(left);
int[] right = new int[(a.length%2==1)?(mid+1):mid];
for(int j=0; j<right.length; j++) {
right[j]=a[i];
i++;
}
right = MergeSort(right);
return Merge(left, right);
}
private int[] Merge(int[] left, int[] right) {
int i, j, k; i=j=k=0;
int[] merged = new int[left.length+right.length];
while(i<left.length && j<right.length) {
if(left[i]<=right[j]) {
merged[k]=left[i];
i++;
} else if(left[i]>right[j]) {
merged[k]=right[j];
j++;
}
k++;
}
while(i<left.length) {
merged[k]=left[i];
i++; k++;
}
while(j<right.length) {
merged[k]=right[j];
j++; k++;
}
return merged;
}
Labels:
Algorithm,
Java,
Jeevan,
Jeevan Rex,
Jeevanus,
Merge Sort,
Sorting
Saturday, December 5, 2015
Chess Knight Move in Board
public class ChessBoard {
int[][] Board;
public ChessBoard() {
Board = new int[8][8];
for(int i=0; i<8; i++)
for(int j=0; j<8; j++)
Board[i][j]='E';//Empty
}
public void KnightMove(int x, int y) {
if(x>-1 && x<8 && y>-1 && y<8)
Board[x][y]='K';//Knight
else {
System.out.println("Error: Not valid Points");
return;
}
int a=x+2;int b=y+1;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
System.out.println(a+" "+b);
a=x+2;b=y-1;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
a=x-2;b=y+1;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
a=x-2;b=y-1;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
a=x+1;b=y+2;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
a=x-1;b=y+2;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
a=x+1;b=y-2;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
a=x-1;b=y-2;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
printBoard();
}
public void printBoard() {
for(int i=0; i<8; i++) {
StringBuffer sb = new StringBuffer();
for(int j=0; j<8; j++)
sb.append((char)Board[i][j]).append(", ");
System.out.println(sb.toString());
}
}
}
int[][] Board;
public ChessBoard() {
Board = new int[8][8];
for(int i=0; i<8; i++)
for(int j=0; j<8; j++)
Board[i][j]='E';//Empty
}
public void KnightMove(int x, int y) {
if(x>-1 && x<8 && y>-1 && y<8)
Board[x][y]='K';//Knight
else {
System.out.println("Error: Not valid Points");
return;
}
int a=x+2;int b=y+1;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
System.out.println(a+" "+b);
a=x+2;b=y-1;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
a=x-2;b=y+1;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
a=x-2;b=y-1;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
a=x+1;b=y+2;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
a=x-1;b=y+2;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
a=x+1;b=y-2;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
a=x-1;b=y-2;
if(a>-1 && a<8 && b>-1 && b<8)
Board[a][b]='T';//Threten
printBoard();
}
public void printBoard() {
for(int i=0; i<8; i++) {
StringBuffer sb = new StringBuffer();
for(int j=0; j<8; j++)
sb.append((char)Board[i][j]).append(", ");
System.out.println(sb.toString());
}
}
}
Thursday, December 3, 2015
Make all diagonal to 0 when encountered a 0
Given a 2D array, write a method MakeDiagonalZeroWhenEncounteredZero() to convert all diagonal to zero when encountered a zero.
import java.util.ArrayList;
public class ChessBoard {
public int[][] Board;
public ChessBoard(int fill) { //Pass 1 for fill
this.Board = new int[8][8];
for(int i=0; i<8; i++)
for(int j=0; j<8; j++)
this.Board[i][j]=fill;
}
public void FillZero(int x, int y) {
if(x<8 && x>-1 && y<8 && y>-1)
Board[x][y]=0;
else
System.out.println("Error: Possition Not Valid");
}
public void MakeDiagonalZeroWhenEncounteredZero() {
ArrayList<Coordinates> zeros = getZeroCordinates();
for(Coordinates c: zeros) {
int x=c.getX();
int y=c.getY();
while(x<7 && y<7) {
x++; y++;
Board[x][y]=0;
}
x=c.getX(); y=c.getY();
while(x>0 && y>0) {
x--; y--;
Board[x][y]=0;
}
x=c.getX(); y=c.getY();
while(x<7 && y>0) {
x++; y--;
Board[x][y]=0;
}
x=c.getX(); y=c.getY();
while(x>0 && y<7) {
x--; y++;
Board[x][y]=0;
}
}
}
private ArrayList<Coordinates> getZeroCordinates() {
ArrayList<Coordinates> zeros = new ArrayList<Coordinates>();
for(int i=0; i<8; i++)
for(int j=0; j<8; j++) {
if(Board[i][j]==0)
zeros.add(new Coordinates(i,j));
}
return zeros;
}
public void PrintBoard() {
for(int i=0; i<8; i++) {
StringBuffer sb = new StringBuffer();
for(int j=0; j<8; j++) {
sb.append(Board[i][j]).append(", ");
}
System.out.println(sb.toString());
}
}
}
class Coordinates {
private int x, y;
public Coordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
Main Method:
ChessBoard cb = new ChessBoard(1);
cb.FillZero(4, 5);
cb.FillZero(7, 2);
System.out.println("Input: ");
cb.PrintBoard();
cb.MakeDiagonalZeroWhenEncounteredZero();
System.out.println("Output: ");
cb.PrintBoard();
Input:
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 0, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 0, 1, 1, 1, 1, 1,
Output:
1, 0, 1, 1, 1, 1, 1, 1,
1, 1, 0, 1, 1, 1, 1, 1,
1, 1, 1, 0, 1, 1, 1, 0,
1, 1, 1, 1, 0, 1, 0, 1,
1, 1, 1, 1, 1, 0, 1, 1,
0, 1, 1, 1, 0, 1, 0, 1,
1, 0, 1, 0, 1, 1, 1, 0,
1, 1, 0, 1, 1, 1, 1, 1,
import java.util.ArrayList;
public class ChessBoard {
public int[][] Board;
public ChessBoard(int fill) { //Pass 1 for fill
this.Board = new int[8][8];
for(int i=0; i<8; i++)
for(int j=0; j<8; j++)
this.Board[i][j]=fill;
}
public void FillZero(int x, int y) {
if(x<8 && x>-1 && y<8 && y>-1)
Board[x][y]=0;
else
System.out.println("Error: Possition Not Valid");
}
public void MakeDiagonalZeroWhenEncounteredZero() {
ArrayList<Coordinates> zeros = getZeroCordinates();
for(Coordinates c: zeros) {
int x=c.getX();
int y=c.getY();
while(x<7 && y<7) {
x++; y++;
Board[x][y]=0;
}
x=c.getX(); y=c.getY();
while(x>0 && y>0) {
x--; y--;
Board[x][y]=0;
}
x=c.getX(); y=c.getY();
while(x<7 && y>0) {
x++; y--;
Board[x][y]=0;
}
x=c.getX(); y=c.getY();
while(x>0 && y<7) {
x--; y++;
Board[x][y]=0;
}
}
}
private ArrayList<Coordinates> getZeroCordinates() {
ArrayList<Coordinates> zeros = new ArrayList<Coordinates>();
for(int i=0; i<8; i++)
for(int j=0; j<8; j++) {
if(Board[i][j]==0)
zeros.add(new Coordinates(i,j));
}
return zeros;
}
public void PrintBoard() {
for(int i=0; i<8; i++) {
StringBuffer sb = new StringBuffer();
for(int j=0; j<8; j++) {
sb.append(Board[i][j]).append(", ");
}
System.out.println(sb.toString());
}
}
}
class Coordinates {
private int x, y;
public Coordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
Main Method:
ChessBoard cb = new ChessBoard(1);
cb.FillZero(4, 5);
cb.FillZero(7, 2);
System.out.println("Input: ");
cb.PrintBoard();
cb.MakeDiagonalZeroWhenEncounteredZero();
System.out.println("Output: ");
cb.PrintBoard();
Input:
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 0, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 0, 1, 1, 1, 1, 1,
Output:
1, 0, 1, 1, 1, 1, 1, 1,
1, 1, 0, 1, 1, 1, 1, 1,
1, 1, 1, 0, 1, 1, 1, 0,
1, 1, 1, 1, 0, 1, 0, 1,
1, 1, 1, 1, 1, 0, 1, 1,
0, 1, 1, 1, 0, 1, 0, 1,
1, 0, 1, 0, 1, 1, 1, 0,
1, 1, 0, 1, 1, 1, 1, 1,
Labels:
2D Array,
Algorithm,
Array,
Data Structures,
Java,
Jeevan,
Jeevan Rex,
Jeevanus
Wednesday, December 2, 2015
Stack Implementation using two Queues
import java.util.LinkedList;
import java.util.Queue;
public class Stack {
Queue<Integer> Q1,Q2;
public Stack() {
Q1=new LinkedList<Integer>();
Q2=new LinkedList<Integer>();
}
public void push(int data) {
Q1.add(data);
}
public int peek() {
int size=Q1.size()-1;
for(int i=0; i<size;i++)
Q2.add(Q1.remove());
int peek = Q1.remove();
Q2.add(peek);
SwapQueues();
return peek;
}
public int pop() {
int size=Q1.size()-1;
for(int i=0; i<size;i++)
Q2.add(Q1.remove());
int pop = Q1.remove();
SwapQueues();
return pop;
}
private void SwapQueues() {
Queue<Integer> temp = Q1;
Q1=Q2;
Q2=temp;
}
}
import java.util.Queue;
public class Stack {
Queue<Integer> Q1,Q2;
public Stack() {
Q1=new LinkedList<Integer>();
Q2=new LinkedList<Integer>();
}
public void push(int data) {
Q1.add(data);
}
public int peek() {
int size=Q1.size()-1;
for(int i=0; i<size;i++)
Q2.add(Q1.remove());
int peek = Q1.remove();
Q2.add(peek);
SwapQueues();
return peek;
}
public int pop() {
int size=Q1.size()-1;
for(int i=0; i<size;i++)
Q2.add(Q1.remove());
int pop = Q1.remove();
SwapQueues();
return pop;
}
private void SwapQueues() {
Queue<Integer> temp = Q1;
Q1=Q2;
Q2=temp;
}
}
Labels:
Algorithm,
Data Structures,
Java,
Jeevan,
Jeevan Rex,
Jeevanus,
Queue,
Stack
Queue Implementation using Two Stacks
import java.util.Stack;
public class Queue {
Stack<Integer> S1;
Stack<Integer> S2;
public Queue() {
S1 = new Stack<Integer>();
S2 = new Stack<Integer>();
}
public void enqueue(int data) {
S1.push(data);
}
private void ShiftS1toS2() {
while(!S1.isEmpty())
S2.push(S1.pop());
}
public int dequeue() {
ShiftS1toS2();
return S2.pop();
}
public int lookup() {
ShiftS1toS2();
return S2.peek();
}
}
public class Queue {
Stack<Integer> S1;
Stack<Integer> S2;
public Queue() {
S1 = new Stack<Integer>();
S2 = new Stack<Integer>();
}
public void enqueue(int data) {
S1.push(data);
}
private void ShiftS1toS2() {
while(!S1.isEmpty())
S2.push(S1.pop());
}
public int dequeue() {
ShiftS1toS2();
return S2.pop();
}
public int lookup() {
ShiftS1toS2();
return S2.peek();
}
}
Labels:
Algorithm,
Data Structures,
Java,
Jeevan,
Jeevan Rex,
Jeevanus,
Queue,
Stack
Sort a Stack using one additional Stack
public Stack<Integer> SortStack(Stack<Integer> input) {
if(input.isEmpty()) return input;
Stack<Integer> buffer = new Stack<Integer>(); //Buffer Stack
while(!input.isEmpty()) {
int temp = input.pop();
if(!buffer.isEmpty() && temp<buffer.peek())
input.push(buffer.pop());
buffer.push(temp);
}
return buffer;
}
This Code doesn't work all the time
Input: [5, 7, 8, 9, 6, 0, 2]
Output: [0, 2, 6, 8, 7, 5, 9]
if(input.isEmpty()) return input;
Stack<Integer> buffer = new Stack<Integer>(); //Buffer Stack
while(!input.isEmpty()) {
int temp = input.pop();
if(!buffer.isEmpty() && temp<buffer.peek())
input.push(buffer.pop());
buffer.push(temp);
}
return buffer;
}
This Code doesn't work all the time
Input: [5, 7, 8, 9, 6, 0, 2]
Output: [0, 2, 6, 8, 7, 5, 9]
Labels:
Algorithm,
Data Structures,
Java,
Jeevan,
Jeevan Rex,
Jeevanus,
Sorting,
Stack
Finding nth Fibonacci number
public int getFibonacci(int n) {
if(n<=1) return 1;
int fibonace=0;
int f1=0;
int f2=1;
for(int i=1; i<n; i++) {
fibonace=f1+f2;
f1=f2;
f2=fibonace;
}
return fibonace;
}
Find Factorial of a Number
// Recursive approach
public int getFactorialRecursive(int n) {
if(n==0) return 1;
else
return n * getFactorial(n-1);
}
// Non Recursive approach
public int getFactorial(int n) {
int factorial=1;
if(n==0) return factorial;
while(n!=0) {
factorial=factorial*n;
n--;
}
return factorial;
}
public int getFactorialRecursive(int n) {
if(n==0) return 1;
else
return n * getFactorial(n-1);
}
// Non Recursive approach
public int getFactorial(int n) {
int factorial=1;
if(n==0) return factorial;
while(n!=0) {
factorial=factorial*n;
n--;
}
return factorial;
}
Tuesday, December 1, 2015
Find Index of an element in a Circularly Sorted Array
input=Find 3 in {6,7,8,9,0,1,2,3,4,5};
output=7
public int FindIndexCircularArray(int element, int[] input) {
int high = input.length-1;
int low = 0;
while(low<=high) {
int mid=(high+low)/2;
if(element==input[mid])
return mid;
else if(input[low]<=input[mid]) {
//left array is sorted
if(element>=input[low] && element<input[mid])
high=mid-1;
else low=mid+1;
} else if(input[mid]<=input[high]) {
//right array is sorted
if(element>input[mid] && element<=input[high])
low=mid+1;
else high=mid-1;
}
}
return -1;
}
output=7
public int FindIndexCircularArray(int element, int[] input) {
int high = input.length-1;
int low = 0;
while(low<=high) {
int mid=(high+low)/2;
if(element==input[mid])
return mid;
else if(input[low]<=input[mid]) {
//left array is sorted
if(element>=input[low] && element<input[mid])
high=mid-1;
else low=mid+1;
} else if(input[mid]<=input[high]) {
//right array is sorted
if(element>input[mid] && element<=input[high])
low=mid+1;
else high=mid-1;
}
}
return -1;
}
Starting Element of a Rotated Array using Binary Search
Sample Input:
input={6,7,8,9,0,1,2,3,4,5};
output=4
input={0,1,2,3,4,5,6,7,8,9};
output=0
public int FindStartIndex(int[] input) {
int high = input.length-1;
int low = 0;
while(low<high) {
if(input[low]<=input[high])
return low;
int mid=(high+low)/2;
if(input[mid]<input[mid+1] && input[mid]<input[mid-1])
return mid;
else if(input[mid]>input[low]) {
//left array is sorted
//start index is not in left
low=mid+1;
} else if(input[mid]<input[high]) {
//right array is sorted
//start index is not in right
high=mid-1;
}
}
return -1;
}
input={6,7,8,9,0,1,2,3,4,5};
output=4
input={0,1,2,3,4,5,6,7,8,9};
output=0
public int FindStartIndex(int[] input) {
int high = input.length-1;
int low = 0;
while(low<high) {
if(input[low]<=input[high])
return low;
int mid=(high+low)/2;
if(input[mid]<input[mid+1] && input[mid]<input[mid-1])
return mid;
else if(input[mid]>input[low]) {
//left array is sorted
//start index is not in left
low=mid+1;
} else if(input[mid]<input[high]) {
//right array is sorted
//start index is not in right
high=mid-1;
}
}
return -1;
}
Subscribe to:
Posts (Atom)