Programming Geek
Rated 4.1/5 based on 446 reviews

Facebook Hacker Cup 2013 Qualification Round: Balanced Snileys

Facebook Hacker Cup 2013: “Balanced Smileys” Solution

The problem statement is given below:
Your friend John uses a lot of emoticons when you talk to him on Messenger. In addition to being a person who likes to express himself through emoticons, he hates unbalanced parenthesis so much that it makes him go :(
Sometimes he puts emoticons within parentheses, and you find it hard to tell if a parenthesis really is a parenthesis or part of an emoticon.
A message has balanced parentheses if it consists of one of the following:
1.  An empty string ""
2. One or more of the following characters: 'a' to 'z', ' ' (a space) or ':' (a colon)
3.  An open parenthesis '(', followed by a message with balanced parentheses, followed by a close parenthesis ')'.
4. A message with balanced parentheses followed by another message with balanced parentheses.
5. A smiley face ":)" or a frowny face ":("
Write a program that determines if there is a way to interpret his message while leaving the parentheses balanced.
Input

The first line of the input contains a number T (1 ≤ T ≤ 50), the number of test cases.
The following T lines each contain a message of length s that you got from John.

Output

For each of the test cases numbered in order from 1 to T, output "Case #i: " followed by a string stating whether or not it is possible that the message had balanced parentheses. If it is, the string should be "YES", else it should be "NO" (all quotes for clarity only)

Constraints
1 ≤ length of s ≤ 100
Sample Input
5
:((
i am sick today (:()
(:)
hacker cup: started :):)
)(
Sample Output
Case #1: NO
Case #2: YES
Case #3: YES
Case #4: YES
Case #5: NO
` `
`Here goes my solution for the “Beautiful Strings” problem:`
```
```
//Problem2.java
```import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.LineNumberReader;
import java.util.ArrayList;

/**
*
* @author VIK http://www.facebook.com/vikashvverma
*
*/
public class Problem2 {

private static File f = new File("Solution2.txt");

public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("balanced_smileystxt.txt");
LineNumberReader lnr = new LineNumberReader(fr);
int t = Integer.parseInt(lnr.readLine().trim());
ArrayList < String > list = new ArrayList < String >();
FileWriter fw = new FileWriter(f);
for (int i = 0; i < t; i++) {
list.add(lnr.readLine().trim());
String res = printResult(list.get(i), i + 1);
if ( i < t - 1 ) {
fw.write("Case #" + (i + 1) + ": " + res + "\n");
} else {
fw.write("Case #" + (i + 1) + ": " + res);
}
fw.flush();
}

}
```
``` private static String printResult ( String string, int index) {
String s = string.replaceAll ( "[^:\\(\\)]", "" );

for (int i = 0; i  <  s.length() / 2; i++) {
String lead = "";
String trail = "";
if (s.charAt(i) == '(' && s.charAt(s.length() - i - 1) == ')') {
if (i > 0) {
lead = s.substring(0, i);
trail = s.substring (s.length() - i, s.length());
}
s = lead + s.substring ( i + 1, s.length() - i - 1 ) + trail;
--i;
}
}
s = s.replaceAll( ":\\(", "" );
s = s.replaceAll( ":\\)", "" );

for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == ')') {
return "NO";
}
}

return "YES";
}
}```

`Download Source Code Here`

```The solution is quite efficient and generated output file for my input file provided by Facebook in less than one second.
Do leave comment regarding any issue or suggestion.
```

Facebook Hacker Cup Qualification Round 2013 Solution : Beautiful Strings

Facebook Hacker Cup 2013: “Beautiful Strings” Solution

The problem statement is given below:
When John was a little kid he didn't have much to do. There was no internet, no Facebook, and no programs to hack on. So he did the only thing he could... he evaluated the beauty of strings in a quest to discover the most beautiful string in the world.
Given a string s, little Johnny defined the beauty of the string as the sum of the beauty of the letters in it.
The beauty of each letter is an integer between 1 and 26, inclusive, and no two letters have the same beauty. Johnny doesn't care about whether letters are uppercase or lowercase, so that doesn't affect the beauty of a letter. (Uppercase 'F' is exactly as beautiful as lowercase 'f', for example.)
You're a student writing a report on the youth of this famous hacker. You found the string that Johnny considered most beautiful. What is the maximum possible beauty of this string?
Input

The input file consists of a single integer m followed by m lines.

Output

Your output should consist of, for each test case, a line containing the string "Case #xy" where x is the case number (with 1 being the first case in the input file, 2 being the second, etc.) and y is the maximum beauty for that test case.

Constraints
5 ≤ m ≤ 50
2 ≤ length of s ≤ 500
Sample Input
`5`
`ABbCcc`
`Good luck in the Facebook Hacker Cup this year!`
`Ignore punctuation, please :)`
`Sometimes test cases are hard to make up.`
`So I just go consult Professor Dalves`
Sample Output
`Case #1: 152`
`Case #2: 754`
`Case #3: 491`
`Case #4: 729`
`Case #5: 646`
` `
`Here goes my solution for the “Beautiful Strings” problem:`
```
```
```import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.Collections;

/**
*
* @author VIK
*/
public class Problem1 {
private static ArrayList < Integer >  integers;
private static File f=new File("Solution1.txt");
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("beautiful_stringstxt.txt");
LineNumberReader lnr = new LineNumberReader(fr);
int t = Integer.parseInt(lnr.readLine().trim());
FileWriter fw=new FileWriter(f);
for (int i = 0; i  <  t; i++) {
int sum= getMax(lnr.readLine().trim());
if ( i < t-1 )
fw.write ( "Case #" + ( i+1 ) + ": " + sum+ "\n" );
else
fw.write( "Case #" + (i+1) + ": " + sum );
fw.flush();

}
}
```

```    private static int getMax ( String string ) throws Exception {
integers = new ArrayList < Integer > ();
for ( int i = 65, j = 97; i  <=  90 && j <= 123 ;  i++, j++ ) {
String s = string.replaceAll ( "[^" + (char) i + (char) j + "]", "" );
s.trim();
integers.add(s.length());
}
int sum = 0;
Collections.sort(integers);
for ( int i = integers.size() - 1, j = 26; i  >= 0 && j  >= 1; --i, --j) {
sum += integers.get(i) * j;
}
return sum;
}
```
}

Download Source code here
`The solution is quite efficient and generated output file for my input file provided by Facebook in less than one second.`
` `
`Do leave comment regarding any issue or suggestion.`

FACEBOOK HACKER CUP 2013 QUALIFICATION ROUND

FACEBOOK HACKER CUP 2013 QUALIFICATION ROUND

The qualification round of Facebook Hacker Cup has been started in India at 5:30 AM IST . The registration process is open until qualification round lasts. Click here to register. The Registration process is quite easy; one needs to provide certain details like name, address, telephone and T-Shirt size too. This is quite amazing and I too want to grab this T-Shirt.

The qualification round consists of three problems, and any participant solving at least one problem correctly will qualify to first official round. There is a set of three problems in qualification round viz. “Beautiful Strings”, “Balanced Smileys” and “Find the min” carrying 20,35 and 45 points respectively. Although all things are working fine but two problems are being faced by the programmers:

1)     The second test case in the first problem is being wrapped up in some of browsers.
2) Few geeks are facing problem while downloading input test case due to “Kivuto Secure Download Manager.

Two of the three problems are quite easy and third one is little bit difficult for large test cases. I solved two out of three problems  in a easy way and third solution takes at least 7 to 8 minutes to generate output  for large inputs. My best rank was 425 when I solved first and second problem.

Below, There are links to the problems and my solutions:

3)Find the Min

MUPHORIA organized by MU Sigma

MUPHORIA
Do you enjoy solving problems?
Do you like flaunting your programming skills?
Wanna do this by being part of a category defining company

Participate in MuPhoriaTM. Win upto Rs.6 Lakhs*and a chance to work with Mu Sigma!

Although the contest is now over, I want to give a brief introduction of this contest along with my submission:

PURPOSE

MuPhoria (the “Contest”) was designed to:
1.Create awareness about the Decision Sciences industry.
2.Encourage and inspire students to gain exposure to real world business problems.
3.Provide students an opportunity to innovate by integrating Math, Business and Technology.

I too partcipated in MUPHORIA and got selected in top five thrice thereby secured an interview with MU Sigma.
To see the sample problem : please visit http://www.mu-sigma.com/muphoria .
Download the datasets, visit http://www.mu-sigma.com/muphoria .
The problem was to find the shortest routes for a set of vehicles so as to minimize the total cost for three years.
Although I tried best but my solution was not so great. Here goes my solution for the concerned problem:

Business logic class: Muphoria

```//Muphoria.java

import java.io.FileReader;
import java.io.FileWriter;
import java.io.LineNumberReader;
import java.util.ArrayList;
import javax.swing.JOptionPane;

/**
*
* @author VIKASH MAYANK
*/
public final class Muphoria {

/**
* instance variables
*
*/
private long total = 0;//stores total distance travelled
private String storeDcMatrix[][] = new String[602][602];//2D array to store the distance among stores and distribution centre containing first row of stores name also
private int distanceSheetMatrix[][] = new int[601][601];//2D array to store distance among store and distribution centre i.e an array containg 601 rows and 601 columns
private String storeWeightMatrix[][] = new String[600][2];//stores store name and their respective demand
private int weightSheetMatrix[] = new int[600];//this array contains only demands of all the 600 stores
private Store[] stores = new Store[600];//this array contains store information
private ArrayList<Truck> truckList = new ArrayList<Truck>();//an arraylist containing list of trucks
private ArrayList<Integer> deliveredStoreindexList = new ArrayList<Integer>();//this arraylist stores index  of store where goods have been delivered
private boolean flag = true;//this becomes false as soon a store is served
private FileWriter fileWriter;//writes csv(comma separated values) file
private int adjustmentFactor = 1000;//determine the maximum goods delivered by a truck so that adjustStore(-,-,-) method can be called...
private String sheet1 = "";//get sheet1.csv
private String sheet2 = "";//get sheet2.csv
/**
* constructor
*/

public Muphoria(String sheet1, String sheet2) {
this.sheet1 = sheet1;
this.sheet2 = sheet2;
readData();
}//constructor-----end-----

/**reads data from comma delimited csv  file
*
*/
private void readData() {
try {
FileReader file = new FileReader(sheet1);//gets file
LineNumberReader lnr = new LineNumberReader(file);//reads one line at a time

//skip four lines of csv file to start reading data
lnr.readLine();
lnr.readLine();
lnr.readLine();
lnr.readLine();

//read csv file line by line and store data in storeDcMatrix
for (int i = 0; i < 602; i++) {
//read one line
String string = lnr.readLine();
//split the string on the basis of comma(,) as a regular expression
storeDcMatrix[i] = string.split("[,]");
}

file = new FileReader(sheet2);//get dataSheet2
lnr = new LineNumberReader(file);
//skip two lines
lnr.readLine();
lnr.readLine();

//stores store and their respective demand in storeWeightMatrix
for (int i = 0; i < storeWeightMatrix.length; i++) {
//read a line
String string = lnr.readLine();
for (int j = 0; j < storeWeightMatrix[i].length; j++) {
storeWeightMatrix[i] = string.split("[,]");//split the string and return values...
}
}
} catch (Exception e) {
System.err.println("System can not find the file specified...\nMake sure...\na)sheet1.csv and sheet2.csv are in the current directory...\nb)Please take a look at readme.pdf document for setup instructions...");
javax.swing.JOptionPane.showMessageDialog(null, "System can not find the file specified...\nMake sure...\na)sheet1.csv and sheet2.csv are in the current directory...\nb)Please take a look at readme.pdf document for setup instructions...", "Error Occured!", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}

//transferring string array(storeDcMatrix) values into int array(distanceSheetMatrix)
for (int i = 0; i < distanceSheetMatrix.length; i++) {
for (int j = 0; j < distanceSheetMatrix[i].length; j++) {
if (i + 1 == j + 1) {
distanceSheetMatrix[i][j] = 0;//put zero as distance of a store from itself is zero
} else {
/**To avoid weird behaviour of floating arithmetic...
* We have multiplied distance by 100 here and casted the data into int type so as to ease calculation part ...
* This does not affect the calculation and actual output because the 65 km distance limit has been checked properly ...
*/
distanceSheetMatrix[i][j] = (int) (Float.parseFloat(storeDcMatrix[i + 1][j + 1]) * 100);//distanceSheetMatrix contains distance only, storeDcMatrix contains name of the store as well
}
}
}

//get demand of 600 stores in stores array as well as in weightSheetMatrix
for (int i = 0; i < 600; i++) {
weightSheetMatrix[i] = Integer.parseInt(storeWeightMatrix[i][1].trim());
stores[i] = new Store();
stores[i].setDemand(Integer.parseInt(storeWeightMatrix[i][1].trim()));
}

}//readData()--------------end-------------------

/**
* getResult() method changes the value of adjustmentFactor which determines the minimum amount of goods so that
* a truck can adjust its store by making a calll to adjustStore(-,-,-) method.
*
* This determines the best value of adjustmentFactor so that total cost over three year is minimum...
*/
public void getResult() {
//make a new Muphoria class object(adjustmentFactor is by default 1000)
Muphoria muphoria = new Muphoria(sheet1, sheet2);
muphoria.readData();//read data from csv files...
muphoria.process();//process the result...
muphoria.calculateTotalCost();//calculate total cost

//loop again and again determine the best adjustmentfactor for ehich total cost over three year is minimum...
for (int i = 1000; i > 900; i--) {
truckList.clear();//clear the current truckList...
deliveredStoreindexList.clear();//clear the deliveredStoreIndexlist..
for (int j = 0; j < stores.length; j++) {//set status of every store to true...
stores[j].setStatus(true);
}
adjustmentFactor = i;//set the new adjustmentFactor
flag = true;//set flag true...
this.process();//process result...
this.calculateTotalCost();//calculate total cost considering new adjustment factor...
if (total < muphoria.total) {//if total cost for this adjustment factor is minimum then store the truckList and total cost in muphoria(object of Muphoria class)...
muphoria.total = total;//set new total cost
muphoria.truckList.clear();//clear muphoria object truckList
for (Truck t : truckList) {
muphoria.truckList.add(t);
}
}
}
muphoria.generateOutput();//generate the best output...
System.out.println("output.csv file is generated in the current directory!");
javax.swing.JOptionPane.showMessageDialog(null, "output.csv file is generated in the current directory!", "Output Generated", JOptionPane.INFORMATION_MESSAGE);
}//getResult()--------------end----------

//find the total number of truck needed...
private void process() {
int j = 1;
while (deliveredStoreindexList.size() < 600) {
Truck truck = new Truck(j);
truckList.add(truck);
flag = true;
findRoutes(truckList.get(j - 1));
// truckList.add(truck);
j++;
}
}//process()--------------------end---------------

//calculate total cost...
private void calculateTotalCost() {
total = 0;
//calculate total distance travelled
for (Truck truck : truckList) {
total += truck.getDistance();
}
total = (total * 30 * 365 * 3) / 100;//cost of travel for three year...
total += truckList.size() * 20000 * 12 * 3;//total cost over three year...
}//calculateTotalCost()----------------end-------------

//generate output.csv file...
private void generateOutput() {
int maximumSore = 0;
total = 0;
//find the maximum number of store delivered by a truck...
for (Truck truck : truckList) {
total += truck.getDistance();
if (maximumSore < truck.getPath().size()) {
maximumSore = truck.getPath().size();
}
}

try {
fileWriter = new FileWriter("output.csv", false);//create a output.csv file
fileWriter.write("          Total  truck  needed : " + truckList.size() + "\n          Total distance  travelled each day(in km) : " + (float) total / 100.0f + "\n");
calculateTotalCost();
fileWriter.write("          Total cost over three years  :  " + total + "\n");
fileWriter.write("\n          DC : Distribution Centre (DC is not a stop)\n");
fileWriter.write("\n          Routing for each truck   \n\n");
fileWriter.close();
//this for loop write name of each truck in output.csv file...
for (Truck truck : truckList) {
fileWriter = new FileWriter("output.csv", true);
fileWriter.write(truck.getName() + ",");
fileWriter.close();
}

//write route of each truck...
for (int i = 0; i < maximumSore; i++) {
fileWriter = new FileWriter("output.csv", true);
fileWriter.flush();
fileWriter.write("\n");
for (int j = 0; j < truckList.size(); j++) {
Truck truck = truckList.get(j);
if (truck.getPath().size() > i) {
fileWriter.write(truck.getPath().get(i) + ",");
} else {
fileWriter.write(",");
}
}
fileWriter.close();
}
} catch (Exception e) {
System.err.println("can not generate output file...\nMake sure...\n1)The output.csv file is not being used by another process.\n2)Current directory has sufficient file write permission...");
javax.swing.JOptionPane.showMessageDialog(null, "can not generate output file...\nMake sure...\n1)The output.csv file is not being used by another process.\n2)Current directory has sufficient file write permission...", "Error generating file!", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}//generateOutput()----------------------end---------

//finds the route of trucks
private void findRoutes(Truck truck) {
Store store = new Store();
int index = 0;
int demand = 0;
int distance = 0;
// while(-) runs until all the stores are visited
while (flag) {
if (deliveredStoreindexList.size() == 600) {
flag = false;
break;
}

if (truck.isStatus()) {
if (truck.getIndex().size() == 0) {
//  get nearest store from distribution centre
store = getNextStore(distanceSheetMatrix[600]);
truck.addPath("DC");
} else {
//get store nearest to previous store
store = getNextStore(distanceSheetMatrix[truck.getIndex().get(truck.getIndex().size() - 1)]);
}

//get details of nearest store
index = store.getIndex();
demand = store.getDemand();
distance = store.getDistance();
//update truck
truck.addDistance(distance);
truck.addIndex(index);
truck.setDelivered(demand);
truck.setTime();
store.setStatus(false);
/**if goods delivered exceeds 1000 kg or
* time spent exceeds 10800 seconds =3 hours or
* distance travelled + return distance exceeds 65km then remove the last updated record
*
*/
if (truck.getDelivered() > 1000 || truck.getTime() > 10800 || (truck.getDistance() + distanceSheetMatrix[600][index]) / 100 > 65) {
store.setStatus(true);
truck.getIndex().remove(truck.getIndex().size() - 1);
distance = -distance;
truck.addDistance(distance);
demand = -demand;
truck.setDelivered(demand);
truck.setTime();

//adjust the last store with a new store where goods to be delivered is less than required to complete 1000 kg
if (truck.getDelivered() < adjustmentFactor) {
store = adjustStore(distanceSheetMatrix[truck.getIndex().get(truck.getIndex().size() - 1)], 1000 - truck.getDelivered());

//get details of nearest store
index = store.getIndex();
demand = store.getDemand();
distance = store.getDistance();
//update truck
truck.addDistance(distance);
truck.addIndex(index);
truck.setDelivered(demand);
truck.setTime();
store.setStatus(false);
deliveredStoreindexList.add(index);
}

//set truck status false
truck.setStatus(false);
//add return distance
truck.addDistance(distanceSheetMatrix[600][truck.getIndex().get(truck.getIndex().size() - 1)]);

//time exceeds 3 hours then remove the last updation
if (truck.getTime() > 10800) {
store.setStatus(true);
truck.getIndex().remove(truck.getIndex().size() - 1);
distance = -distance;
truck.addDistance(distance);
demand = -demand;
truck.setDelivered(demand);
truck.setTime();
deliveredStoreindexList.remove(deliveredStoreindexList.size() - 1);
}

// distance travelled exceeds 65 km then remove the last updation
if ((truck.getDistance() / 100) > 65) {//truck.getDistance() is  divided by 100 as we originally multiplied each distance by 100 in distanceSheetMatrix
store.setStatus(true);
truck.getIndex().remove(truck.getIndex().size() - 1);
distance = -distance;
truck.addDistance(distance);
demand = -demand;
truck.setDelivered(demand);
truck.setTime();
deliveredStoreindexList.remove(deliveredStoreindexList.size() - 1);

}
flag = false;
truck.addPath("DC");

} else {
//add visited store name in path
truck.addPath(storeDcMatrix[0][index + 1]);

//update deliveredStoreindexList
deliveredStoreindexList.add(index);

}

//add return distance of the truck if all the stores are visited
if (deliveredStoreindexList.size() == 600 && truck.getIndex().size() < 35 && truck.getDelivered() <= 1000) {
truck.addDistance(distanceSheetMatrix[600][truck.getIndex().get(truck.getIndex().size() - 1)]);
flag = false;
truck.addPath("DC");
}

//set truck status false if 35 stores are served ...
if (truck.getIndex().size() == 35) {
truck.setStatus(false);
truck.addDistance(distanceSheetMatrix[600][truck.getIndex().get(truck.getIndex().size() - 1)]);
flag = false;
truck.addPath("DC");
}
}
}//while end ...
}//findRoutes()------------end-----------

//getNextStore(-,-,-) finds the nearest store from the previously visited store
private Store getNextStore(int[] prevStore) {
int index = 0;
int distance = 0;

//find store where goods have not been delivered...
for (int i = 0; i < 600; i++) {
if (prevStore[i] != 0 && stores[i].isStatus()) {
index = i;
distance = prevStore[i];
stores[i].setIndex(index);
stores[i].setDistance(distance);
break;
}
}

//find the nearest store where goods have not been delivered...
for (int i = 0; i < 600; i++) {
if (prevStore[i] != 0 && (prevStore[i]) <= distance && stores[i].isStatus()) {
distance = prevStore[i];
index = i;
stores[i].setIndex(index);
stores[i].setDistance(distance);
}
}

//return the nearest store
return stores[index];

}//getNextStore(-)-------------end------------

/**called when  the last nearest store has more demand of goods than goods that can be delivered by the truck keeping 1000 kg limit
* this method takes input as previous store and required goods in the truck and returns the store having highest demand of goods(less than required goods)...
*/
private Store adjustStore(int[] prevStore, int required) {
int index = 0;
int distance = 0;
int weight = 0;
//finds a store which is not visited...
for (int i = 0; i < 600; i++) {
if (prevStore[i] != 0 && stores[i].isStatus() && weightSheetMatrix[i] < required) {
index = i;
distance = prevStore[i];
weight = weightSheetMatrix[i];
stores[i].setIndex(index);
stores[i].setDistance(distance);
break;
}
}

//finds the store having highest demand of goods(less than required)...
for (int i = 0; i < 600; i++) {
if (prevStore[i] != 0 && (weightSheetMatrix[i]) >= weight && weightSheetMatrix[i] < required && stores[i].isStatus()) {
distance = prevStore[i];
weight = weightSheetMatrix[i];
index = i;
stores[i].setIndex(index);
stores[i].setDistance(distance);
}
}

return stores[index];
}//adjustStore(-,-)----------------------end---------------
}//Muphoria-------------------business logic class--------------

//
class Store {

private int distance;//distance of a store from previously visited store(dynamically changes as the previously visited store changes)...
private int demand;//demand of goods...
private int index;//index position in array...
private boolean status;//becomes false as soon as goods have been delivered...

public Store() {
status = true;
}

public boolean isStatus() {
return status;
}

public void setStatus(boolean status) {
this.status = status;
}

public int getDemand() {
return demand;
}

public void setDemand(int demand) {
this.demand = demand;
}

public int getDistance() {
return distance;
}

public void setDistance(int distance) {
this.distance = distance;
}

public int getIndex() {
return index;
}

public void setIndex(int index) {
this.index = index;
}
}//Store-------business logic class------------

//
class Truck {

private boolean status = true;//status becomes false as soon as any constraints like time limit  ,maximum goods that can be delivered or maximum distance that can be travelled tends to be invalid
private int distance;//total distance travelled...
private ArrayList<string> path = new ArrayList<string>();//keep track of stores where goods have been delivered...
private ArrayList<Integer> index = new ArrayList<Integer>();//keep track of index of stores in array
private int delivered;//total goods delivered...
private int time;//time spent...
private String name;//name of the truck...

public Truck(int number) {
setName("Truck#" + number);
}

public int getDelivered() {
return delivered;
}

public void setDelivered(int delivered) {
this.delivered += delivered;
}

public String getName() {
return name;
}

private void setName(String name) {
this.name = name;
}

public int getTime() {
return time;
}

public void setTime() {
//aeach truck can travel upto 3 hours to deliver goods i.e. 60*60*60=10800 seconds
int seconds = 0;
//add total time taken to travel the distance
seconds += getDistance() * 90 / 100;
//add 5 minutes =5*60 = 300 seconds for each stop
seconds += getIndex().size() * 300;
this.time = seconds;

}

public int getDistance() {
return distance;
}

public void setDistance(int distance) {

this.distance += distance;
}

public void addDistance(int distance) {
this.distance += distance;
}

public ArrayList<Integer> getIndex() {
return index;
}

public void setIndex(ArrayList<Integer> index) {
this.index = index;
}

public void addIndex(int index) {
this.index.add(index);
}

public ArrayList<string> getPath() {
return path;
}

public void setPath(ArrayList<string> path) {
this.path = path;
}

public void addPath(String path) {
this.path.add(path);
}

public boolean isStatus() {
return status;
}

public void setStatus(boolean status) {
this.status = status;
}
}//Truck---------------business logic class-------------

```
Execution logic class: Main
```
//Main.java
public class Main
{
public static void main(String[] args)
{
Muphoria muphoria=new Muphoria("sheet1.csv","sheet2.csv");
muphoria.getResult();
}
}//Main---------execution logic class-------

```

JAVA Program to Establish Connection with IBM DB2

JAVA Program to Establish Connection with IBM DB2 database and executing several Queries

The following program demonstrates the connection with IBM DB2 using jdbc driver. To run the below program you need to perform following steps:

Step1:  Download the jdbc driver here.
Step2: Include jdbc driver in “CLASSPATH” environment variable or copy      “db2jcc.jar”and ”db2jcc4.jar” files to”\jdk1.7.0\jre\lib\ext”.
where is your directory where JAVA is installed . In my case it is “C:\Program Files (x86)\Java”

Copy the program given below:
```import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
*
* @author VIK
*/
public class DB2Conn {

public static void main(String[] args) {

Connection con = null;
Statement st = null;
PreparedStatement pstmt = null;
//load driver class
System.out.println("Loading driver class...");
try {
Class.forName("com.ibm.db2.jcc.DB2Driver");
} catch (ClassNotFoundException e) {
System.err.println("Driver class not found\nexiting...");
}
System.out.println("Connecting...");
try {
con = DriverManager.getConnection("jdbc:db2://localhost:50000/SAMPLE", "db2admin", "db2admin");

} catch (SQLException e) {
System.err.println("Failed to connect to DB2\nexiting...");
}

if (con != null) {
System.out.println("connected!!!");
} else {
System.out.println("failed to connect!!!\n exiting...");
return;
}
try {
st = con.createStatement();
//to create table with blob field (One time only)
st.executeUpdate("CREATE TABLE student(sroll integer,sname varchar(10) , sadd varchar(50))");
} catch (SQLException e) {
System.err.println("Table already exists...");
}
System.out.println("Inserting Data in table...");
try {
pstmt = con.prepareStatement("INSERT INTO student VALUES(?,?,?)");
pstmt.setInt(1, 1);
pstmt.setString(2, "VIKASH");
pstmt.setString(3, "Dhanbad");
int result = pstmt.executeUpdate();
if (result >= 1) {
System.out.println("Details added successfully...!");
}
} catch (SQLException e) {
System.err.println("Error in inserting details...");
}
try {
//Retrieving details from database...
System.out.println("Retrieving details from database...");
ResultSet rs = st.executeQuery("select * from STUDENT");
while (rs.next()) {
System.out.println("SROLL : " + rs.getInt(1) + "  SNAME : " + rs.getString(2) + "  SADD : " + rs.getString(3));
}
} catch (SQLException e) {
System.err.println("Error in retrieving details...\nexiting...");

}
}
}

```

Step3: Save the program as “DB2Conn.java”.

Step4: Open command prompt in directory where DB2Conn.java is present and type the following command to compile and execute the program .

To Compile:

Javac DB2Conn.java

To run:

Java DB2Conn

See the screenshot below: