Merge remote-tracking branch 'upstream/master'

This commit is contained in:
sahilb2 2017-11-27 22:17:33 -06:00
commit 68cd8c154e
12 changed files with 544 additions and 58 deletions

View File

@ -0,0 +1,57 @@
import java.util.*;
/**
* Converts any Binary Number to a Hexadecimal Number
*
* @author Nishita Aggarwal
*
*/
public class BinaryToHexadecimal {
/**
* This method converts a binary number to
* a hexadecimal number.
*
* @param binary The binary number
* @return The hexadecimal number
*/
static String binToHex(int binary)
{
//hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for decimal numbers 0 to 15
HashMap<Integer,String> hm=new HashMap<>();
//String to store hexadecimal code
String hex="";
int i;
for(i=0 ; i<10 ; i++)
{
hm.put(i, String.valueOf(i));
}
for(i=10 ; i<16 ; i++) hm.put(i,String.valueOf((char)('A'+i-10)));
int currbit;
while(binary != 0)
{
int code4 = 0; //to store decimal equivalent of number formed by 4 decimal digits
for(i=0 ; i<4 ; i++)
{
currbit = binary % 10;
binary = binary / 10;
code4 += currbit * Math.pow(2, i);
}
hex= hm.get(code4) + hex;
}
return hex;
}
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter binary number:");
int binary = sc.nextInt();
String hex = binToHex(binary);
System.out.println("Hexadecimal Code:" + hex);
sc.close();
}
}

View File

@ -0,0 +1,145 @@
public class MatrixGraphs {
public static void main(String args[]) {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10);
graph.addEdge(1, 2);
graph.addEdge(1, 5);
graph.addEdge(2, 5);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 1);
graph.addEdge(2, 3);
System.out.println(graph);
}
}
class AdjacencyMatrixGraph {
private int _numberOfVertices;
private int _numberOfEdges;
private int[][] _adjacency;
static final int EDGE_EXIST = 1;
static final int EDGE_NONE = 0;
public AdjacencyMatrixGraph(int givenNumberOfVertices) {
this.setNumberOfVertices(givenNumberOfVertices);
this.setNumberOfEdges(0);
this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]);
for (int i = 0; i < givenNumberOfVertices; i++) {
for (int j = 0; j < givenNumberOfVertices; j++) {
this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE;
}
}
}
private void setNumberOfVertices(int newNumberOfVertices) {
this._numberOfVertices = newNumberOfVertices;
}
public int numberOfVertices() {
return this._numberOfVertices;
}
private void setNumberOfEdges(int newNumberOfEdges) {
this._numberOfEdges = newNumberOfEdges;
}
public int numberOfEdges() {
return this._numberOfEdges;
}
private void setAdjacency(int[][] newAdjacency) {
this._adjacency = newAdjacency;
}
private int[][] adjacency() {
return this._adjacency;
}
private boolean adjacencyOfEdgeDoesExist(int from, int to) {
return (this.adjacency()[from][to] != AdjacencyMatrixGraph.EDGE_NONE);
}
public boolean vertexDoesExist(int aVertex) {
if (aVertex >= 0 && aVertex < this.numberOfVertices()) {
return true;
} else {
return false;
}
}
public boolean edgeDoesExist(int from, int to) {
if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
return (this.adjacencyOfEdgeDoesExist(from, to));
}
return false;
}
/**
* This method adds an edge to the graph between two specified
* verticies
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @return returns true if the edge did not exist, return false if it already did
*/
public boolean addEdge(int from, int to) {
if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
if (!this.adjacencyOfEdgeDoesExist(from, to)) {
this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_EXIST;
this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_EXIST;
this.setNumberOfEdges(this.numberOfEdges() + 1);
return true;
}
}
return false;
}
/**
* this method removes an edge from the graph between two specified
* verticies
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @return returns false if the edge doesn't exist, returns true if the edge exists and is removed
*/
public boolean removeEdge(int from, int to) {
if(!this.vertexDoesExist(from) || !this.vertexDoesExist(to)) {
if (this.adjacencyOfEdgeDoesExist(from, to)) {
this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_NONE;
this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_NONE;
this.setNumberOfEdges(this.numberOfEdges() - 1);
return true;
}
}
return false;
}
/**
* this gives a list of verticies in the graph and their adjacencies
*
* @return returns a string describing this graph
*/
public String toString() {
String s = new String();
s = " ";
for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + String.valueOf(i) + " ";
}
s = s + " \n";
for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + String.valueOf(i) + " : ";
for (int j = 0; j < this.numberOfVertices(); j++) {
s = s + String.valueOf(this._adjacency[i][j]) + " ";
}
s = s + "\n";
}
return s;
}
}

View File

@ -37,6 +37,7 @@ public class Matrix {
System.out.println("2 * m2:\n" + m2.scale(2));
System.out.println("m2 + m3:\n" + m2.plus(m3));
System.out.println("m2 - m3:\n" + m2.minus(m3));
System.out.println("m2 * m3: \n"+m2.multiply(m3));
}
@ -158,6 +159,32 @@ public class Matrix {
return new Matrix(newData);
}
/**
* Multiplies this matrix with another matrix.
*
* @param other : Matrix to be multiplied with
* @return product
*/
public Matrix multiply(Matrix other) throws RuntimeException {
int[][] newData = new int[this.data.length][other.getColumns()];
if(this.getColumns() !=other.getRows())
throw new RuntimeException("The two matrices cannot be multiplied.");
int sum;
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < other.getColumns(); ++j){
sum = 0;
for(int k=0;k<this.getColumns();++k){
sum += this.data[i][k] * other.getElement(k, j);
}
newData[i][j] = sum;
}
return new Matrix(newData);
}
/**
* Checks if the matrix passed is equal to this matrix
*

View File

@ -0,0 +1,52 @@
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
public class CoinChange {
// Driver Program
public static void main(String[] args) {
int amount = 12;
int[] coins = {1, 2, 5};
System.out.println("Number of combinations of getting change for " + amount + " is: " + change(coins, amount));
}
/**
* This method finds the number of combinations of getting change for a given amount and change coins
*
* @param coins The list of coins
* @param amount The amount for which we need to find the change
* Finds the number of combinations of change
**/
public static int change(int[] coins, int amount) {
int[] combinations = new int[amount+1];
combinations[0] = 1;
for (int coin : coins) {
for (int i=coin; i<amount+1; i++) {
if (i>=coin) {
combinations[i] += combinations[i-coin];
}
}
// Uncomment the below line to see the state of combinations for each coin
// printAmount(combinations);
}
return combinations[amount];
}
// A basic print method which prints all the contents of the array
public static void printAmount(int[] arr) {
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}

View File

@ -1,17 +0,0 @@
import java.util.Scanner;
class FloydTriangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows which you want in your Floyd Triangle: ");
int r = sc.nextInt(), n = 0;
for(int i=0; i < r; i++) {
for(int j=0; j <= i; j++) {
System.out.print(++n + " ");
}
System.out.println();
}
}
}

View File

@ -1,33 +0,0 @@
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
//take input
Scanner scn = new Scanner(System.in);
int N = scn.nextInt(); //N is the input number
int P = scn.nextInt(); //P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870.
System.out.println(squareRoot(N, P));
}
public static double squareRoot(int N, int P) {
double rv = 0; //rv means return value
double root = Math.pow(N, 0.5);
//calculate precision to power of 10 and then multiply it with root value.
int precision = (int) Math.pow(10, P);
root = root * precision;
/*typecast it into integer then divide by precision and again typecast into double
so as to have decimal points upto P precision */
rv = (int)root;
return (double)rv/precision;
}
}

73
Misc/heap_sort.java Normal file
View File

@ -0,0 +1,73 @@
public class HeapSort
{
public void sort(int arr[])
{
int n = arr.length;
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i=n-1; i>=0; i--)
{
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i)
{
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
// Driver program
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6, 7};
int n = arr.length;
HeapSort ob = new HeapSort();
ob.sort(arr);
System.out.println("Sorted array is");
printArray(arr);
}
}

View File

@ -1,6 +1,7 @@
import java.util.Scanner;
public class FloydTriangle {
class FloydTriangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows which you want in your Floyd Triangle: ");

View File

@ -1,15 +1,30 @@
//Oskar Enmalm 3/10/17
//This is Euclid's algorithm which is used to find the greatest common denominator
//Overide function name gcd
public class GCD{
public static int gcd(int a, int b) {
public static int gcd(int num1, int num2) {
int r = a % b;
while (r != 0) {
b = r;
r = b % r;
int gcdValue = num1 % num2;
while (gcdValue != 0) {
num2 = gcdValue;
gcdValue = num2 % gcdValue;
}
return b;
return num2;
}
public static int gcd(int[] number) {
int result = number[0];
for(int i = 1; i < number.length; i++)
//call gcd function (input two value)
result = gcd(result, number[i]);
return result;
}
public static void main(String[] args) {
int[] myIntArray = {4,16,32};
//call gcd function (input array)
System.out.println(gcd(myIntArray));
}
}

View File

@ -1,4 +1,8 @@
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {

View File

@ -0,0 +1,84 @@
import java.util.*;
/**
* Program to perform Saddleback Search
* Given a sorted 2D array(elements are sorted across every row and column, assuming ascending order)
* of size n*m we can search a given element in O(n+m)
*
* we start from bottom left corner
* if the current element is greater than the given element then we move up
* else we move right
* Sample Input:
* 5 5 ->Dimensions
* -10 -5 -3 4 9
* -6 -2 0 5 10
* -4 -1 1 6 12
* 2 3 7 8 13
* 100 120 130 140 150
* 140 ->element to be searched
* output: 4 3 // first value is row, second one is column
*
* @author Nishita Aggarwal
*
*/
public class SaddlebackSearch {
/**
* This method performs Saddleback Search
*
* @param arr The **Sorted** array in which we will search the element.
* @param crow the current row.
* @param ccol the current column.
* @param ele the element that we want to search for.
*
* @return The index(row and column) of the element if found.
* Else returns -1 -1.
*/
static int[] search(int arr[][],int crow,int ccol,int ele){
//array to store the answer row and column
int ans[]={-1,-1};
if(crow<0 || ccol>=arr[crow].length){
return ans;
}
if(arr[crow][ccol]==ele)
{
ans[0]=crow;
ans[1]=ccol;
return ans;
}
//if the current element is greater than the given element then we move up
else if(arr[crow][ccol]>ele)
{
return search(arr,crow-1,ccol,ele);
}
//else we move right
return search(arr,crow,ccol+1,ele);
}
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int arr[][];
int i,j,rows=sc.nextInt(),col=sc.nextInt();
arr=new int[rows][col];
for(i=0;i<rows;i++)
{
for(j=0;j<col;j++){
arr[i][j]=sc.nextInt();
}
}
int ele=sc.nextInt();
//we start from bottom left corner
int ans[]=search(arr,rows-1,0,ele);
System.out.println(ans[0]+" "+ans[1]);
sc.close();
}
}

78
Sorts/cyclesort.java Normal file
View File

@ -0,0 +1,78 @@
import java.util.*;
import java.lang.*;
class Sorting
{
// Function that sort the array using Cycle sort
public static void cycleSort (int arr[], int n)
{
// count number of memory writes
int writes = 0;
// traverse array elements
for (int cycle_start=0; cycle_start<=n-2; cycle_start++)
{
// initialize item as starting point
int item = arr[cycle_start];
// Find position where we put the item.
int pos = cycle_start;
for (int i = cycle_start+1; i<n; i++)
if (arr[i] < item)
pos++;
// If item is already in correct position
if (pos == cycle_start)
continue;
// ignore all duplicate elements
while (item == arr[pos])
pos += 1;
// put the item to it's right position
if (pos != cycle_start)
{
int temp = item;
item = arr[pos];
arr[pos] = temp;
writes++;
}
// Rotate rest of the cycle
while (pos != cycle_start)
{
pos = cycle_start;
// Find position where we put the element
for (int i = cycle_start+1; i<n; i++)
if (arr[i] < item)
pos += 1;
// ignore all duplicate elements
while (item == arr[pos])
pos += 1;
// put the item to it's right position
if (item != arr[pos])
{
int temp = item;
item = arr[pos];
arr[pos] = temp;
writes++;
}
}
}
}
// main program to test above function
public static void main(String[] args)
{
int arr[] = {1, 8, 3, 9, 10, 10, 2, 4 };
int n = arr.length;
cycleSort(arr, n) ;
System.out.println("After sort : ");
for (int i =0; i<n; i++)
System.out.print(arr[i] + " ");
}
}