Lift Operation – Program Development in Java Interesting !!!

import java.awt.geom.*;

public class elevator
{

    static int floor;

    public static void main(String args[])
    {

        floor = (int) (Math.random() * 10 + 1);

        System.out.println("The elevator is now on floor " +floor);
        System.out.print("Which floor are you at now (0-10) where 0 = basement: ");
        int current_floor = Keyboard.readInt();

        if(floor == current_floor)
        {
            System.out.println("Enter the elevator");
        }
        else
        {
            MoveElevator(current_floor);
        }


        System.out.println("To which floor would you want to go (0-10) where 0 = basement");
        int target_floor = Keyboard.readInt();

        MoveElevator(target_floor);
    }

    public static void MoveElevator(int target_floor)
    {
        int direction;
        if( target_floor > floor )
        {
            System.out.println("The elevator is on it's way up...");
            direction = 1;
        }else{
            System.out.println("The elevator is on it's way down...");
            direction = -1;
        }

        while(target_floor != floor)
        {
            floor += direction;
            System.out.println(floor);
        }

        System.out.println("The elevator has arrived");
    }
Advertisements
| Leave a comment

Matrix Graph Implementation in Java

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
* vertices
*
* @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
* vertices
*
* @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 vertices 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;
}

}

| Leave a comment

HashMap Implementation in Java Easy…

import java.util.ArrayList;
import java.util.LinkedList;

public class HashMap<K,V> {
public class hmnodes{ //HashMap nodes
K key;
V value;
}

private int size=0; //size of hashmap
private LinkedList<hmnodes> buckets[]; //array of addresses of list

public HashMap(){
buckets=new LinkedList[4]; //initially create bucket of any size
for(int i=0;i<4;i++)
buckets[i]=new LinkedList<>();
}

public void put(K key,V value) throws Exception{
int bi=bucketIndex(key); //find the index,the new key will be inserted in linklist at that index
int fountAt=find(bi,key); //check if key already exists or not
if(fountAt==-1){
hmnodes temp=new hmnodes(); //if doesn’t exist create new node and insert
temp.key=key;
temp.value=value;
buckets[bi].addLast(temp);
this.size++;
}else{
buckets[bi].get(fountAt).value=value;//if already exist modify the value
}

double lambda = (this.size*1.0)/this.buckets.length;
if(lambda>2.0){
rehash(); //rehashing function which will increase the size of bucket as soon as lambda exceeds 2.0
}

return;
}

public V get(K key) throws Exception{
int bi=bucketIndex(key);
int fountAt=find(bi,key);
if(fountAt==-1){
return null;
}else{
return buckets[bi].get(fountAt).value;
}
}

public V remove(K key) throws Exception{
int bi=bucketIndex(key);
int fountAt=find(bi,key);
if(fountAt==-1){
return null;
}else{
this.size–;
return buckets[bi].remove(fountAt).value;
}
}

public boolean containskey(K key) throws Exception{
int bi=bucketIndex(key);
int fountAt=find(bi,key);
if(fountAt==-1){
return false;
}else{
return true;
}
}

public int size(){
return this.size;
}

public boolean isempty(){
return this.size==0;
}

public ArrayList<K> keyset() throws Exception{
ArrayList<K> arr=new ArrayList<>();
for(int i=0;i<buckets.length;i++){
for(int j=0;j<buckets[i].size();j++){
arr.add(buckets[i].get(j).key);
}
}
return arr;
}

public ArrayList<V> valueset() throws Exception{
ArrayList<V> arr=new ArrayList<>();
for(int i=0;i<buckets.length;i++){
for(int j=0;j<buckets[i].size();j++){
arr.add(buckets[i].get(j).value);
}
}
return arr;
}

public void display() throws Exception{
for(int i=0;i<buckets.length;i++){
System.out.print(“Bucket: “+i+” “);
for(int j=0;j<buckets[i].size();j++){
hmnodes temp=buckets[i].get(j);
System.out.print(“[“+temp.key+”->”+temp.value+”]”);
}
System.out.println();
}
}

public int find(int bi,K key) throws Exception{
for(int i=0;i<buckets[bi].size();i++){
if(key.equals(buckets[bi].get(i).key))
return i;
}
return -1;
}

public int bucketIndex(K key) throws Exception{
int bi=key.hashCode();
return Math.abs(bi%buckets.length);
}

private void rehash() throws Exception{
LinkedList<hmnodes> ob[]= buckets;
buckets=new LinkedList[ob.length*2];
for(int i=0;i<ob.length*2;i++)
buckets[i]=new LinkedList<>();

size = 0;
for(int i=0;i<ob.length;i++){
for(int j=0;j<ob[i].size();j++){
put(ob[i].get(j).key,ob[i].get(j).value);
}
}

}
}

| Leave a comment

Unzip Utility in Java

public class UnzipUtility
{
/* Automaticaly UnCompress Tar files
* @author Ashoka BM
*
*/

public static List unTar(File tarFile, File directory) throws IOException {
List<String> result = new ArrayList<String>();
InputStream inputStream = new FileInputStream(tarFile);
TarArchiveInputStream in = new TarArchiveInputStream(inputStream);
TarArchiveEntry entry = in.getNextTarEntry();
while (entry != null) {
if (entry.isDirectory()) {
entry = in.getNextTarEntry();
continue;
}
File curfile = new File(directory, entry.getName());
File parent = curfile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
OutputStream out = new FileOutputStream(curfile);
IOUtils.copy(in, out);
out.close();
result.add(entry.getName());
entry = in.getNextTarEntry();
}
in.close();
return result;
}

}

| Leave a comment

Check the Operating System – Java Utility

public class SystemUtility {

private static String OS = System.getProperty(“os.name”).toLowerCase();

/**
* If System is Windows OS
* @return
*/
public static boolean isWindows() {

return (OS.indexOf(“win”) >= 0);

}

/**
* If System OS is Mac
* @return
*/
public static boolean isMac() {

return (OS.indexOf(“mac”) >= 0);

}

/**
* If System OS is Linux/Unix
* @return
*/
public static boolean isUnix() {

return (OS.indexOf(“nix”) >= 0 || OS.indexOf(“nux”) >= 0 || OS.indexOf(“aix”) > 0 );

}

/**
* If System OS is Solaries
* @return
*/
public static boolean isSolaris() {

return (OS.indexOf(“sunos”) >= 0);

}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
if (isWindows()) {
System.out.println(“This is Windows”);
} else if (isMac()) {
System.out.println(“This is Mac”);
} else if (isUnix()) {
System.out.println(“This is Unix or Linux”);
} else if (isSolaris()) {
System.out.println(“This is Solaris”);
} else {
System.out.println(“Your OS is not support!!”);
}
}
}

| Leave a comment

Compare two table columns attributes data – Using SQL Queries

/**
* Create Source table for Compare CSV Files Data
* @param filePath
* @param conn
* @param chunkId
* @param subsetId
* @throws Exception
*/
public void getFileContentSRC(String filePath,Connection conn,String chunkId,String subsetId) throws Exception
{
String sql=””;
CSVParser parser = new CSVParser(new FileReader(filePath), CSVFormat.DEFAULT.withSkipHeaderRecord());

/*sql = “BEGIN EXECUTE IMMEDIATE ‘DROP TABLE ZZ_COMPARE_CSV_SRC’;EXCEPTION WHEN OTHERS THEN NULL;END; “;
ps = conn.prepareStatement(sql);
ps.executeUpdate(sql);*/

sql = “CREATE TABLE ZZ_COMPARE_CSV_SRC_”+chunkId+”_”+subsetId+”(MSISDN VARCHAR2(20)) ” ;
try(PreparedStatement ps = conn.prepareStatement(sql)){
ps.executeUpdate(sql);
}
sql = “INSERT INTO ZZ_COMPARE_CSV_SRC_”+chunkId+”_”+subsetId+”(MSISDN) VALUES (?)”;
try(PreparedStatement ps = conn.prepareStatement(sql)){
final int batchSize = 1000;
int count = 0;

for (CSVRecord record : parser) {
ps.setString(1, record.get(0));
ps.addBatch();

if(++count % batchSize == 0) {
ps.executeBatch();
}
}
parser.close();
ps.executeBatch(); // insert remaining records
ps.close();
//conn.close();
}
}
/**
* Create Destination Table for Compare CSV files Data
* @param filePath
* @param conn
* @param chunkId
* @param subsetId
* @throws Exception
*/
public void getFileContentDST(String filePath,Connection conn,String chunkId,String subsetId) throws Exception
{
String sql=””;
CSVParser parser = new CSVParser(new FileReader(filePath), CSVFormat.DEFAULT.withSkipHeaderRecord());

/*sql = “BEGIN EXECUTE IMMEDIATE ‘DROP TABLE ZZ_COMPARE_CSV_DST’;EXCEPTION WHEN OTHERS THEN NULL;END; “;
ps = conn.prepareStatement(sql);
ps.executeUpdate(sql);*/

sql = “CREATE TABLE ZZ_COMPARE_CSV_DST_”+chunkId+”_”+subsetId+”(MSISDN VARCHAR2(20)) ” ;
try(PreparedStatement ps = conn.prepareStatement(sql)){
ps.executeUpdate(sql);
}

sql = “INSERT INTO ZZ_COMPARE_CSV_DST_”+chunkId+”_”+subsetId+”(MSISDN) VALUES (?)”;
try(PreparedStatement ps = conn.prepareStatement(sql)){
final int batchSize = 1000;
int count = 0;

for (CSVRecord record : parser) {
ps.setString(1, record.get(0));
ps.addBatch();

if(++count % batchSize == 0) {
ps.executeBatch();
}
}
parser.close();
ps.executeBatch(); // insert remaining records*/
ps.close();
}
//conn.close();
}

/**
* Generate Log Files
* @param filePath
* @param conn
* @throws Exception
*/
public void generateLogFiles(String filePath,Connection conn,String chunkId,String subsetId) throws Exception
{
//Statement ps=null;
String sql=””;
ResultSet resultSet = null;
sql = “SELECT ROWNUM AS ROWNR,’OK’ AS STATUS,S.MSISDN FROM ZZ_COMPARE_CSV_SRC_”+chunkId+”_”+subsetId+” S,ZZ_COMPARE_CSV_DST_”+chunkId+”_”+subsetId+” D WHERE S.MSISDN=D.MSISDN ORDER BY ROWNR “;
try(Statement ps = conn.createStatement()){
resultSet = ps.executeQuery(sql);
ResultSetMetaData meta = resultSet.getMetaData() ;
int numberOfColumns = meta.getColumnCount() ;
String dataHeaders = “” + meta.getColumnName(1) + “” ;
for (int i = 2 ; i < numberOfColumns + 1 ; i ++ ) {
dataHeaders += “,” + meta.getColumnName(i) + “” ;
}
String[] tableHeader = dataHeaders.split(“,”) ;
CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator(“\n”);
String[] headers = format.getHeader();
String FILE_NAME = filePath;
File file = new File(FILE_NAME);
FileWriter fw = new FileWriter(file);
CSVPrinter printer = new CSVPrinter(fw, format.withFirstRecordAsHeader());
for (int i = 0; i < tableHeader.length; i++) {
printer.print(tableHeader[i]);
}
printer.println();
printer.printRecords(resultSet);
fw.close();
printer.close();
}
//conn.close();
}

/**
* Generate Bad Files
* @param filePath
* @param conn
* @throws Exception
*/
public void generateBadFiles(String filePath,Connection conn,String chunkId,String subsetId) throws Exception
{
String sql=””;
ResultSet resultSet = null;
sql = “SELECT ROWNUM AS ROWNR,’2627′ AS ERROR_CODE,’NOT_LOADED’ AS ERROR_REASON,MSISDN FROM ZZ_COMPARE_CSV_SRC_”+chunkId+”_”+subsetId+” WHERE MSISDN NOT IN (SELECT MSISDN FROM ZZ_COMPARE_CSV_DST_”+chunkId+”_”+subsetId+”) ORDER BY ROWNR”;
try(Statement ps = conn.createStatement()){
resultSet = ps.executeQuery(sql);
ResultSetMetaData meta = resultSet.getMetaData() ;
int numberOfColumns = meta.getColumnCount() ;
String dataHeaders = “” + meta.getColumnName(1) + “” ;
for (int i = 2 ; i < numberOfColumns + 1 ; i ++ ) {
dataHeaders += “,” + meta.getColumnName(i) + “” ;
}
String[] tableHeader = dataHeaders.split(“,”) ;
CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator(“\n”);
String[] headers = format.getHeader();
String FILE_NAME = filePath;
File file = new File(FILE_NAME);
FileWriter fw = new FileWriter(file);
CSVPrinter printer = new CSVPrinter(fw, format.withFirstRecordAsHeader());
for (int i = 0; i < tableHeader.length; i++) {
printer.print(tableHeader[i]);
}
printer.println();
printer.printRecords(resultSet);
fw.close();
printer.close();
//conn.close();
}
}

/**
* This will drop the compare tables Source and Destination tables
* @param conn
* @param chunkId
* @param subsetId
* @throws Exception
*/
public void dropComparisonTables(Connection conn,String chunkId,String subsetId) throws Exception
{

String sqlSource=””;
String sqlDestination=””;

sqlSource = “BEGIN EXECUTE IMMEDIATE ‘DROP TABLE ZZ_COMPARE_CSV_SRC_”+chunkId+”_”+subsetId+”‘;EXCEPTION WHEN OTHERS THEN NULL;END; “;
try(PreparedStatement psSource = conn.prepareStatement(sqlSource)){
psSource.executeUpdate(sqlSource);
}

sqlDestination = “BEGIN EXECUTE IMMEDIATE ‘DROP TABLE ZZ_COMPARE_CSV_DST_”+chunkId+”_”+subsetId+”‘;EXCEPTION WHEN OTHERS THEN NULL;END; “;
try(PreparedStatement psDestination = conn.prepareStatement(sqlDestination)){
psDestination.executeUpdate(sqlDestination);
}
//conn.close();
}

| Leave a comment

Get the common files names in 2 different directories – Java Utility

/**
* This will return common file names from the List
* @param localListOfFiles
* @param sdpListOfFiles
* @return
*/
public static List getCommonFileNames(File[] localListOfFiles,File[] sdpListOfFiles)
{
List<String> commonFiles=new ArrayList<String>();
for (int j = 0; j < localListOfFiles.length; j++) {
for (int k = 0; k < sdpListOfFiles.length; k++) {
//System.out.println(“File ” + localListOfFiles[i].getName());
String localName = localListOfFiles[j].getName();
String sdpName= sdpListOfFiles[k].getName();
if(localName.equalsIgnoreCase(sdpName))
{
commonFiles.add(localName);
}
}
}
return commonFiles;
}

| Leave a comment