hashed search program endless loop - java

My code is getting stuck in the second while loop in my hash search method. It seems like the conditions keep staying true, when they should eventually become false if the key is not in the dataset or if the key is found. Can someone help me find the bug?
Thanks
//////
this is the whole.. i been working on it.. still cant find the error.
public void HashedSearch()
{
HSAverageAccessTime = 0;
HSAverageCompSuc = 0;
HSAverageCompFailed = 0;
HSNumberKeysSuc = 0;
HSNumberKeysFailed = 0;
Initialize();
int SearchKey;
int TotalNumberOfComparisons;
int address;
int M;
M = FindPrime();
for(int i=0; i<NumberOfDataItems; i++)
{
address = OriginalArray[i] % M;
if (HashedArray[address]== -1)
HashedArray[address]= OriginalArray[i];
else
{
address = (address+1) % M;
while(HashedArray[address]!=-1)
{
address=(address+1)%M;
}
HashedArray[address]=OriginalArray[i];
}
}
System.out.println("after mapping" + M);
long startTime = System.nanoTime();
boolean found = false;
for (int k = 0; k <NumberOfKeys; k++)
{
found = false;
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
address = KeysArray[k] % M;
//System.out.println("address" + address);
//System.out.println(" inside if 1 --- address" + address);
while ( HashedArray[address]!= SearchKey && HashedArray[address]!= -1)
{
if (HashedArray [address] == SearchKey)
{
found = true;
TotalNumberOfComparisons++;
HSAverageCompSuc = HSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
System.out.println("Stuck after here");
HSAverageCompFailed = HSAverageCompFailed + TotalNumberOfComparisons;
HSNumberKeysFailed ++;
//address=(address+1)%M;
address++;
}
System.out.println(" outside while --- found" + found);
//if(HashedArray[address] == SearchKey)
//found = true;
//else found = false;
//address=(address+1)%M;
//address++;
}
if(found)
{
HSAverageCompSuc = HSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
HSAverageCompFailed = HSAverageCompFailed + TotalNumberOfComparisons;
HSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
HSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
HSAverageAccessTime = 0;
if(HSNumberKeysSuc != 0)
HSAverageCompSuc = Math.round (HSAverageCompSuc / HSNumberKeysSuc) ;
else
HSAverageCompSuc = 0;
if (HSNumberKeysFailed != 0)
HSAverageCompFailed = Math.round (HSAverageCompFailed / HSNumberKeysFailed) ;
else
HSNumberKeysFailed = 0;
System.out.println("time after search" + estimatedTime);
return;
}

while ( HashedArray[address]!= SearchKey && HashedArray[address]!= -1)
{
address=(address+1)%M;
}
Your loop never terminates if your SearchKey or -1 is not in HashedArray. I cannot give you any more clarifications unless you post the complete code.

#Bashir #KevinDiTraglia #Steinar
import javax.swing.*;
//File-related imports
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
import java.util.Arrays;
import java.math.*;
public class ArrayOperations
{
// File Parameters
String DataFilePath;
String DataFileName;
String KeysFilePath;
String KeysFileName;
int NumberOfDataItems;
int NumberOfKeys ;
int N ;
int BucketHashArraySize;
int NoBuckets;
//Array
int[] OriginalArray = new int[1000000];
int[] SortedArray = new int[1000000];
int[] HashedArray = new int[2000000];
int[] BucketHashedArray = new int[2000000];
int[] KeysArray = new int[1000000];
long SSAverageAccessTime;
long SSAverageCompSuc ;
long SSAverageCompFailed;
long SSNumberKeysSuc ;
long SSNumberKeysFailed ;
long BSAverageAccessTime;
long BSAverageCompSuc ;
long BSAverageCompFailed;
long BSNumberKeysSuc ;
long BSNumberKeysFailed ;
long HSAverageAccessTime;
long HSAverageCompSuc ;
long HSAverageCompFailed;
long HSNumberKeysSuc ;
long HSNumberKeysFailed ;
public ArrayOperations()
{
// File Parameters
DataFilePath = null;
DataFileName = null;
KeysFilePath = null;
KeysFileName = null;
NumberOfDataItems=0;
NumberOfKeys =0;
N =0;
BucketHashArraySize = 0;
NoBuckets =0;
// Statistics
SSAverageAccessTime = 0;
SSAverageCompSuc = 0;
SSAverageCompFailed = 0;
SSNumberKeysSuc = 0;
SSNumberKeysFailed = 0;
BSAverageAccessTime = 0;
BSAverageCompSuc = 0;
BSAverageCompFailed = 0;
BSNumberKeysSuc = 0;
BSNumberKeysFailed = 0;
HSAverageAccessTime = 0;
HSAverageCompSuc = 0;
HSAverageCompFailed = 0;
HSNumberKeysSuc = 0;
HSNumberKeysFailed = 0;
}
public void ReadDataFile() throws IOException
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
DataFilePath = chooser.getSelectedFile().getPath();
DataFileName = chooser.getSelectedFile().getName();
}
// read data file and copy it to original array
if (DataFilePath != null)
{
try
{
int index = 0;
Scanner integerTextFile = new Scanner(new File(DataFilePath));
while (integerTextFile.hasNext())
{
// read the next integer
OriginalArray[index] = integerTextFile.nextInt();
index++;
}
// end of file detected
integerTextFile.close();
NumberOfDataItems = index;
}
catch (IOException ioe)
{
System.exit(0);
}
}
else
NumberOfDataItems = 0;
}
public void ReadKeysFile() throws IOException
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Keys File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
KeysFilePath = chooser.getSelectedFile().getPath();
KeysFileName = chooser.getSelectedFile().getName();
}
// read data file and copy it to original array
if (KeysFilePath != null)
{
try
{
int index = 0;
Scanner integerTextFile = new Scanner(new File(KeysFilePath));
while (integerTextFile.hasNext())
{
// read the next integer
KeysArray[index]= integerTextFile.nextInt();
index++;
}
// end of file detected
integerTextFile.close();
NumberOfKeys = index;
}
catch (IOException ioe)
{
System.exit(0);
}
}
else
NumberOfKeys = 0;
}
public void SequentialSearch()
{
SSAverageAccessTime = 0;
SSAverageCompSuc = 0;
SSAverageCompFailed = 0;
SSNumberKeysSuc = 0;
SSNumberKeysFailed = 0;
int SearchKey;
int TotalNumberOfComparisons;
long startTime = System.nanoTime();
boolean found = false;
for (int k=0; k<NumberOfKeys; k++)
{
found = false;
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
for (int d=0; d<NumberOfDataItems; d++)
{
TotalNumberOfComparisons++;
if (SearchKey == OriginalArray[d])
{
found = true;
}
if (found)break;
}
if(found)
{
SSAverageCompSuc = SSAverageCompSuc + TotalNumberOfComparisons;
SSNumberKeysSuc ++;
}
else
{
SSAverageCompFailed = SSAverageCompFailed + TotalNumberOfComparisons;
SSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
SSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
SSAverageAccessTime = 0;
if(SSNumberKeysSuc != 0)
SSAverageCompSuc = Math.round (SSAverageCompSuc / SSNumberKeysSuc) ;
else
SSAverageCompSuc = 0;
if (SSNumberKeysFailed != 0)
SSAverageCompFailed = Math.round (SSAverageCompFailed / SSNumberKeysFailed) ;
else
SSNumberKeysFailed = 0;
return;
}
public void BinarySearch()
{
BSAverageAccessTime = 0 ;
BSAverageCompSuc = 0 ;
BSAverageCompFailed = 0 ;
BSNumberKeysSuc = 0 ;
BSNumberKeysFailed = 0 ;
int SearchKey;
int TotalNumberOfComparisons;
boolean found = false;
for (int i=0; i<NumberOfDataItems; i++)
{
SortedArray[i] = OriginalArray[i];
}
Arrays.sort(SortedArray);
long startTime = System.nanoTime();
for (int k=0; k<NumberOfKeys; k++)
{
found = false;
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
//binary starts
int start = 0;
int end = SortedArray.length - 1;
int middle;
while ( end >= start )
{
middle = ( start + end )/ 2; // element in middle of array
if ( SortedArray[middle] == SearchKey )
{
TotalNumberOfComparisons++;
found = true;
}
else
if ( SortedArray[middle] > SearchKey )
{ TotalNumberOfComparisons++;
end = middle - 1;
} // search left side of array
else
{ TotalNumberOfComparisons++;
start = middle + 1; } // search right side of array
if (found)
break;
//binaryends
}
if(found)
{
BSAverageCompSuc = BSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
BSAverageCompFailed = BSAverageCompFailed + TotalNumberOfComparisons;
BSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
BSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
BSAverageAccessTime = 0;
if(BSNumberKeysSuc != 0)
BSAverageCompSuc = Math.round (BSAverageCompSuc / BSNumberKeysSuc) ;
else
BSAverageCompSuc = 0;
if (BSNumberKeysFailed != 0)
BSAverageCompFailed = Math.round (BSAverageCompFailed / BSNumberKeysFailed) ;
else
BSNumberKeysFailed = 0;
return;
}
public void HashedSearch()
{
HSAverageAccessTime = 0;
HSAverageCompSuc = 0;
HSAverageCompFailed = 0;
HSNumberKeysSuc = 0;
HSNumberKeysFailed = 0;
Initialize();
int SearchKey;
int TotalNumberOfComparisons;
int address;
int M;
M = FindPrime();
for(int i=0; i<NumberOfDataItems; i++)
{
address = OriginalArray[i] % M;
if (HashedArray[address]== -1)
HashedArray[address]= OriginalArray[i];
else
{
address = (address+1) % M;
while(HashedArray[address]!=-1)
{
address=(address+1)%M;
}
HashedArray[address]=OriginalArray[i];
}
}
System.out.println("after mapping" + M);
long startTime = System.nanoTime();
boolean found = false;
for (int k = 0; k <NumberOfKeys; k++)
{
found = false;
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
address = KeysArray[k] % M;
//System.out.println("address" + address);
//System.out.println(" inside if 1 --- address" + address);
while ( HashedArray[address]!= SearchKey && HashedArray[address]!= -1)
{
if (HashedArray [address] == SearchKey)
{
found = true;
TotalNumberOfComparisons++;
HSAverageCompSuc = HSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
System.out.println("Stuck after here");
HSAverageCompFailed = HSAverageCompFailed + TotalNumberOfComparisons;
HSNumberKeysFailed ++;
//address=(address+1)%M;
address++;
}
System.out.println(" outside while --- found" + found);
//if(HashedArray[address] == SearchKey)
//found = true;
//else found = false;
//address=(address+1)%M;
//address++;
}
if(found)
{
HSAverageCompSuc = HSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
HSAverageCompFailed = HSAverageCompFailed + TotalNumberOfComparisons;
HSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
HSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
HSAverageAccessTime = 0;
if(HSNumberKeysSuc != 0)
HSAverageCompSuc = Math.round (HSAverageCompSuc / HSNumberKeysSuc) ;
else
HSAverageCompSuc = 0;
if (HSNumberKeysFailed != 0)
HSAverageCompFailed = Math.round (HSAverageCompFailed / HSNumberKeysFailed) ;
else
HSNumberKeysFailed = 0;
System.out.println("time after search" + estimatedTime);
return;
}
public int FindPrime()
{
boolean prime = true;
for(int i=NumberOfDataItems * 2-1; i>=0; i--)
{
System.out.println(" i = " +i);
prime = true;
for(int J =2; J< Math.sqrt(i); J++)
{
if (i % J == 0)
{
prime = false;
}
if (prime == false) break;
}
if (prime == true)
{
System.out.println(i);
return i;
}
}
return -1;
}
public void Initialize()
{
for (int i=0; i<NumberOfDataItems; i++)
{
HashedArray[i] = -1;
}
}
public void BHSearch()
{
}
}

Related

Trouble receiving images from an 8 modem server

I have implemented this java app communicating with a remote 8 modem server and when I request for an image from a security camera (error free or not) the outcome is a 1 byte image (basically a small white square). Can you help me find the error?
Here is my code:
import java.io.*;
import java.util.Scanner;
import ithakimodem.Modem;
public class g {
private static Scanner scanner = new Scanner(System.in);
private static String EchoCode = "E3369";
private static String noImageErrorscode = "M2269";
private static String imageErrorsCode = "G6637";
private static String GPS_Code = "P7302";
private static String ACK_Code = "Q2591";
private static String NACK_Code = "R4510";
public static void main(String[] args) throws IOException, InterruptedException {
int timeout = 2000;
int speed = 80000;
Modem modem = new Modem(speed);
modem.setTimeout(timeout);
modem.write("ATD2310ITHAKI\r".getBytes());
getConsole(modem);
modem.write(("test\r").getBytes());
getConsole(modem);
while (true) {
System.out.println("\nChoose one of the options below :");
System.out.print("Option 0: Exit\n" + "Option 1: Echo packages\n" + "Option 2: Image with no errors\n" + "Option 3: Image with errors\n" + "Option 4: Tracks of GPS\n"
+ "Option 5: ARQ\n" );
System.out.print("Insert option : ");
int option = scanner.nextInt();
System.out.println("");
switch (option) {
case 0: {
// Exit
System.out.println("\nExiting...Goodbye stranger");
modem.close();
scanner.close();
return;
}
case 1: {
// Echo
getEcho(modem, EchoCode);
break;
}
case 2: {
// Image with no errors
getImage(modem, noImageErrorscode, "no_error_image.jpg");
break;
}
case 3: {
// Image with errors
getImage(modem, imageErrorsCode, "image_with_errors.jpg");
}
case 4: {
// GPS
getGPS(modem, GPS_Code);
break;
}
case 5: {
// ARQ
getARQ(modem, ACK_Code, NACK_Code);
break;
}
default:
System.out.println("Try again please\n");
}
}
}
public static String getConsole(Modem modem) {
int l;
StringBuilder stringBuilder= new StringBuilder();
String string = null;
while (true) {
try {
l = modem.read();
if (l == -1) {
break;
}
System.out.print((char) l);
stringBuilder.append((char) l);
string = stringBuilder.toString();
} catch (Exception exc) {
break;
}
}
System.out.println("");
return string;
}
private static void getImage(Modem modem, String password, String fileName) throws IOException {
int l;
boolean flag;
FileOutputStream writer = new FileOutputStream(fileName, false);
flag = modem.write((password + "\r").getBytes());
System.out.println("\nReceiving " + fileName + "...");
if (!flag) {
System.out.println("Code error or end of connection");
writer.close();
return;
}
while (true) {
try {
l = modem.read();
writer.write((char) l);
writer.flush();
if (l == -1) {
System.out.println("END");
break;
}
}
catch (Exception exc) {
break;
}
}
writer.close();
}
private static void getGPS(Modem modem, String password) throws IOException {
int rows = 99;
String Rcode = "";
Rcode = password + "R=10200" + rows;
System.out.println("Executing R parameter = " + Rcode + " (XPPPPLL)");
modem.write((Rcode + "\r").getBytes());
String stringConsole = getConsole(modem);
if (stringConsole == null) {
System.out.println("Code error or end of connection");
return;
}
String[] stringRows = stringConsole.split("\r\n");
if (stringRows[0].equals("n.a")) {
System.out.println("Error : Packages not received");
return;
}
System.out.println("**TRACES**\n");
float l1 = 0, l2 = 0;
int difference = 8;
difference *= 100 / 60;
int traceNumber = 7;
String[] traces = new String[traceNumber + 1];
int tracesCounter = 0, flag = 0;
for (int i = 0; i < rows; i++) {
if (stringRows[i].startsWith("$GPGGA")) {
if (flag == 0) {
String str = stringRows[i].split(",")[1];
l1 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
flag = 1;
}
String str = stringRows[i].split(",")[1];
l2 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
if (Math.abs(l2 - l1) >= difference) {
traces[tracesCounter] = stringRows[i];
if (tracesCounter == traceNumber)
break;
tracesCounter++;
l1 = l2;
}
}
}
for (int i = 0; i < traceNumber; i++) {
System.out.println(traces[i]);
}
String w = "", T_cd_fnl = password + "T=";
int p = 1;
System.out.println();
for (int i = 0; i < traceNumber; i++) {
String[] strSplit = traces[i].split(",");
System.out.print("T parameter = ");
String str1 = strSplit[4].substring(1, 3);
String str2 = strSplit[4].substring(3, 5);
String str3= String.valueOf(Integer.parseInt(strSplit[4].substring(6, 10)) * 60 / 100).substring(0, 2);
String str4= strSplit[2].substring(0, 2);
String str5= strSplit[2].substring(2, 4);
String str6= String.valueOf(Integer.parseInt(strSplit[2].substring(5, 9)) * 60 / 100).substring(0, 2);
w = str1 + str2 + str3 + str4 + str5 + str6 + "T";
p = p + 5;
System.out.println(w);
T_cd_fnl = T_cd_fnl + w + "=";
}
T_cd_fnl = T_cd_fnl.substring(0, T_cd_fnl.length() - 2);
System.out.println("\nSending code: " + T_cd_fnl);
getImage(modem, T_cd_fnl, "traces GPS.jpg");
}
private static void getEcho(Modem modem, String strl) throws InterruptedException, IOException {
FileOutputStream echo_time_writer = new FileOutputStream("echoTimes.txt", false);
FileOutputStream echo_counter_writer = new FileOutputStream("echoCounter.txt", false);
int h;
int runtime = 5, packetCounter = 0;
String str = "";
System.out.println("\nRuntime (mins) = " + runtime + "\n");
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receiveTime = 0;
String time = "", ClockTime = "";
echo_time_writer.write("Clock Time\tSystem Time\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
packetCounter++;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
while (true) {
try {
h = modem.read();
System.out.print((char) h);
str += (char) h;
if ( h== -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (str.endsWith("PSTOP")) {
receiveTime = System.currentTimeMillis();
ClockTime = str.substring(18, 26) + "\t";
time = String.valueOf((receiveTime - send_time) + "\r\n");
echo_time_writer.write(ClockTime.getBytes());
echo_time_writer.write(time.getBytes());
echo_time_writer.flush();
str = "";
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
}
echo_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
echo_counter_writer.write(("\r\nPackets Received: " + String.valueOf(packetCounter)).getBytes());
echo_counter_writer.close();
echo_time_writer.close();
}
private static void getARQ(Modem modem, String strl, String nack_code) throws IOException, InterruptedException {
FileOutputStream arq_time_writer = new FileOutputStream("ARQtimes.txt", false);
FileOutputStream arq_counter_writer = new FileOutputStream("ARQcounter.txt", false);
int runtime = 5;
int xor = 1;
int f = 1;
int m;
int packageNumber = 0;
int iterationNumber = 0;
int[] nack_times_counter = new int[15];
int nack_to_package = 0;
String time = "", clock_time = "", s = "";
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receive_time = 0;
System.out.printf("Runtime (mins) = " + runtime + "\n");
arq_time_writer.write("Clock Time\tSystem Time\tPacket Resends\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
if (xor == f) {
packageNumber++;
nack_times_counter[nack_to_package]++;
nack_to_package = 0;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
} else {
iterationNumber++;
nack_to_package++;
modem.write((nack_code + "\r").getBytes());
}
while (true) {
try {
m = modem.read();
System.out.print((char) m);
s += (char) m;
if (m == -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (s.endsWith("PSTOP")) {
receive_time = System.currentTimeMillis();
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
String[] string = s.split("<");
string = string[1].split(">");
f = Integer.parseInt(string[1].substring(1, 4));
xor = string[0].charAt(0) ^ string[0].charAt(1);
for (int i = 2; i < 16; i++) {
xor = xor ^ string[0].charAt(i);
}
if (xor == f) {
System.out.println("Packet ok");
receive_time = System.currentTimeMillis();
time = String.valueOf((receive_time - send_time) + "\t");
clock_time = s.substring(18, 26) + "\t";
arq_time_writer.write(clock_time.getBytes());
arq_time_writer.write(time.getBytes());
arq_time_writer.write((String.valueOf(nack_to_package) + "\r\n").getBytes());
arq_time_writer.flush();
} else {
xor = 0;
}
s = "";
}
arq_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
arq_counter_writer.write("\r\nPackets Received (ACK): ".getBytes());
arq_counter_writer.write(String.valueOf(packageNumber).getBytes());
arq_counter_writer.write("\r\nPackets Resent (NACK): ".getBytes());
arq_counter_writer.write(String.valueOf(iterationNumber).getBytes());
arq_counter_writer.write("\r\nNACK Time Details".getBytes());
for (int i = 0; i < nack_times_counter.length; i++) {
arq_counter_writer.write(("\r\n" + i + ":\t" + nack_times_counter[i]).getBytes());
}
arq_counter_writer.close();
arq_counter_writer.close();
System.out.println("Packets Received: " + packageNumber);
System.out.println("Packets Resent: " + iterationNumber);
System.out.println("\n\nFile arqTimes.txt is created.");
System.out.println("File arqCounter.txt is created.");
}
}
I know the problem is most probably in the getImage() function but I haven't figured it out yet.

Drag and drop between two Jtables

So I managed to make Jtable working one way, from table1 to table2. but I don't really know how to make it work both ways(from table2 to table1). I was trying putting transferhandler on both Jtables, but I guess that they interfere with each other. So I'm pretty much stuck. Can someone explain how should I do it?
Here is the implementation (when I'm trying to do the same with the second Jtable it is not working):
table1.setDragEnabled(true);
table2.setTransferHandler(new TransferHandler() {
public boolean canImport(TransferSupport support) {
if (!support.isDrop()) {
return false;
}
if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
return false;
}
return true;
}
public boolean importData(TransferSupport support) {
if (!canImport(support)) {
return false;
}
int row2 = table1.getSelectedRow();
int rows[] = table1.getSelectedRows();
if (rows.length > 1){
Object strings2[][] = new String[rows.length][2];
for (int i=0; i<rows.length; i++) {
for (int j = 0; j < 2; j++)
strings2[i][j] = table1.getValueAt(rows[i], j);
}
String pathToCopy, pathToPaste;
for (int k=0; k<strings2.length; k++) {
if (path.equals("C:\\"))
pathToCopy = text1.getText() + trimmer(strings2[k][0].toString());
else
pathToCopy = text1.getText() + "\\" + trimmer(strings2[k][0].toString());
if (path2.equals("C:\\"))
pathToPaste = path2 + trimmer(strings2[k][0].toString());
else
pathToPaste = text2.getText() + "\\" + trimmer(strings2[k][0].toString());
File toCopy = new File(pathToCopy);
File toPaste = new File(pathToPaste);
try {
copyPaste(toCopy, toPaste);
} catch (IOException e) {
System.out.println("Nie można skopiować pliku!");
}
}
return true;
}
else {
if (row2 != -1) {
for (int i = 0; i < 2; i++)
strings[i] = table1.getValueAt(row2, i);
}
String pathToCopy, pathToPaste;
if (path.equals("C:\\"))
pathToCopy = text1.getText() + trimmer(strings[0].toString());
else
pathToCopy = text1.getText() + "\\" + trimmer(strings[0].toString());
if (path2.equals("C:\\"))
pathToPaste = path2 + trimmer(strings[0].toString());
else
pathToPaste = text2.getText() + "\\" + trimmer(strings[0].toString());
File toCopy = new File(pathToCopy);
File toPaste = new File(pathToPaste);
try {
copyPaste(toCopy, toPaste);
} catch (IOException e) {
System.out.println("Nie można skopiować pliku!");
}
return true;
}
}
});

Display the Shortest Path using BFS in java

This is my BFS algorithm code.
I can calculate the shortest path distance, but somehow I am not able to display the shortest path.
Like for example, I calculated the shortest path from source to destination is 2. But i would like to also display the pathway. (PlaceA -> PlaceB -> PlaceC) for example.
May i know how do i display out the shortest path out using Java?
Please do help me! Thank you!
public static void main(String[] args) {
// TODO Auto-generated method stub
chooseNumOfVertices();
chooseNumOfEdges();
generateGraph();
in.close();
}
private static void generateGraph() {
int source = 0;
int destination = 0;
int edge = chooseEdge;
// TODO Auto-generated method stub
ArrayList<LinkedList<Integer>> graph = new ArrayList<LinkedList<Integer>>();
for (int i = 0; i < limit; i++) {
LinkedList<Integer> vertex = new LinkedList<Integer>();
vertex.add(i);
graph.add(vertex);
}
while (chooseEdge > 0) {
// Randomize the value
int value = new Random().nextInt(cityMapping.size());
int value2 = new Random().nextInt(cityMapping.size());
//
if (value != value2 && !graph.get(value).contains(value2) && !graph.get(value2).contains(value)) {
graph.get(value).add(value2);
graph.get(value2).add(value);
chooseEdge--;
}
}
// Printing out the Nodes
for (int i = 0; i < graph.size(); i++) {
// Return each LinkedList nodes
// System.out.println(graph.get(i));
for (int j = 0; j < graph.get(i).size(); j++) {
// Return each individual nodes inside LinkedList
for (Entry<Integer, String> entry : cityMapping.entrySet()) {
if (entry.getKey() == graph.get(i).get(j)) {
//System.out.print(graph.get(i).get(j) + "-> ");
System.out.print(graph.get(i).get(j) + ". " + entry.getValue() + " -> ");
}
}
}
System.out.println();
}
do {
for (
int i = 0; i < limit; i++) {
int[] newArray = new int[limit];
distance.add(newArray);
predecessor.add(newArray);
}
long time = System.nanoTime();
System.out.println("Searching BFS");
System.out.println("--------------------------------------------");
for (int i = 0; i < limit; i++) {
BFS(graph, i);
}
long CPUTime = (System.nanoTime() - time);
System.out.println("CPU Time for BFS for " + limit + "vertices and " + edge + "edges (in ns): " + CPUTime);
System.out.print("Enter -1 to exit! Enter source vertex (between 0 to " + (limit - 1) + ") : ");
source = in.nextInt();
if (source == -1) {
System.out.print("System terminating...");
break;
}
System.out.print("Enter destination vertex (between 0 to " + (limit - 1) + ") : ");
destination = in.nextInt();
System.out.println("Distance from " + source + " to " + destination + " is: " +
getDistance(source, destination));
System.out.println("The Predecessor of the path from " + source + " to " + destination + " is: "
+ getPredecessor(source, destination));
} while (source != -1);
}
private static void BFS(ArrayList<LinkedList<Integer>> graph, int i) {
// TODO Auto-generated method stub
boolean[] mark = new boolean[graph.size()];
Queue<Integer> L = new ArrayBlockingQueue<Integer>(graph.size()); //Queue
L.add(i);
mark[i] = true;
Arrays.fill(predecessor.get(i), -1);
Arrays.fill(distance.get(i), -1);
distance.get(i)[i] = 0;
while (!L.isEmpty()) {
int vertex = L.remove();
for (int i1 = 0; i1 < graph.get(vertex).size(); i1++) {
int v = graph.get(vertex).get(i1);
if (!mark[v]) {
mark[v] = true;
predecessor.get(i)[v] = vertex;
L.add(v);
distance.get(i)[v] = distance.get(i)[predecessor.get(i)[v]] + 1;
}
}
}
}
public static int getDistance(int start, int end) {
return (distance.get(start)[end]);
}
public static int getPredecessor(int start, int end) {
return (predecessor.get(start)[end]);
}
private static void chooseNumOfEdges() {
System.out.println("Please input the number of Edges:");
chooseEdge = in.nextInt();
}
// Number of Vertices
private static void chooseNumOfVertices() {
in = new Scanner(System.in);
System.out.println("Please input the number of Vertices:");
limit = in.nextInt();
// Read CSV
List<String[]> content = readCsvFile();
// Map each number to a city name
cityMapping = new HashMap<>();
for (int i = 0; i < limit; i++) {
cityMapping.put(i, content.get(i)[0]);
}
// System.out.println(cityMapping);
}
// Read CSV file
public static List<String[]> readCsvFile() {
String csvFile = "./Lab 4/country.csv";
BufferedReader br = null;
ArrayList<String> names = new ArrayList<String>();
List<String[]> content = new ArrayList<>();
String cvsSplitBy = ",";
try {
String line = "";
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
content.add(line.split(cvsSplitBy));
}
} catch (Exception e) {
e.printStackTrace();
}
Random r = new Random();
Collections.shuffle(content);
return content;
}
}

Submit Hadoop Map Reduce Job With Secondary Data File?

I'm trying to do a Map-Reduce job on big text file which contains my data. To process this data I actually need another array to do lookup's with the data I'm processing.
So ideally the reducers would load this file and populate the array, then start reducing.
I'm trying to use Google Cloud platform because I get £250 free computation, Without going into massive detail about the project, I'm new to map-reduce, only having done a small university course on extreme computing and need a little direction for the best way to achieve this. There are a few things I haven't fixed yet like the output types etc but what I'm struggling with is the setup() function, exactly how to populate my array before the reducer starts reducing, any help would be greatly appreciated!
public static class MapForEquityCalculator extends Mapper<LongWritable, Text, Text, IntWritable> {
public int GetIndex(int R1, int R2, boolean IsSuited) {
if (IsSuited) {
return (int)(((13 - Math.ceil((double)Math.max(R1, R2) / 4)) * 13) + (13 - Math.ceil((double)Math.min(R1, R2) / 4)));
} else {
return (int)(((13 - Math.ceil((double)Math.min(R1, R2) / 4)) * 13) + (13 - Math.ceil((double)Math.max(R1, R2) / 4)));
}
}
public void map(LongWritable key, Text value, Context con) throws IOException, InterruptedException {
String line = value.toString();
String[] cards=line.split(",");
int ind_1 = GetIndex(Integer.parseInt(cards[0]),Integer.parseInt(cards[1]),Integer.parseInt(cards[0])%4 == Integer.parseInt(cards[1])%4);
int ind_2 = GetIndex(Integer.parseInt(cards[2]),Integer.parseInt(cards[3]),Integer.parseInt(cards[2])%4 == Integer.parseInt(cards[3])%4);
int ind_3 = GetIndex(Integer.parseInt(cards[4]),Integer.parseInt(cards[5]),Integer.parseInt(cards[4])%4 == Integer.parseInt(cards[4])%4);
Text outputKey = new Text(Integer.toString(ind_1) +"," + Integer.toString(ind_2) +"," + Integer.toString(ind_3));
Text outputValue = new Text(line);
con.write(outputKey, outputValue);
}
}
public static class ReduceForEquityCalculator extends Reducer<Text, IntWritable, Text, IntWritable> {
public static final int HandRankSize = 32487834;
public static int HR[] = new int[HandRankSize];
protected static final int littleEndianByteArrayToInt(byte[] b, int offset) {
return (b[offset + 3] << 24) + ((b[offset + 2] & 0xFF) << 16)
+ ((b[offset + 1] & 0xFF) << 8) + (b[offset] & 0xFF);
}
public void setup(Context context) throws IOException{
Path pt=new Path("gs://mybucket/HandRanks.dat");
Configuration conf = new Configuration();
FileSystem fs = pt.getFileSystem(conf);
int tableSize = HandRankSize*4;
byte[] b = new byte[tableSize];
try {
FileInputStream fr = new FileInputStream(fs.open(pt));
int bytesRead = fr.read(b, 0, tableSize);
if (bytesRead != tableSize) {
}
fr.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
for (int i = 0; i < HandRankSize; i++) {
HR[i] = littleEndianByteArrayToInt(b, i * 4);
}
}
public void reduce(Text word, Text value, Context con) throws IOException, InterruptedException {
String line = value.toString();
String[] cards_string=line.split(",");
Integer[] cards = new Integer[cards_string.length];
int i=0;
for(String str:cards_string){
cards[i]=Integer.parseInt(str);//Exception in this line
i++;
}
int c0, c1, c2, c3, c4, c5, c6;
int u0, u1, u2, u3, u4, u5;
int su0, su1, su2, su3, su4, su5;
int tu0, tu1, tu2, tu3, tu4, tu5;
u0 = HR[53+cards[0]];
u1 = HR[u0+cards[1]];
su0 = HR[53+cards[2]];
su1 = HR[su0+cards[3]];
tu0 = HR[53+cards[4]];
tu1 = HR[su0+cards[5]];
int A_B_C = 0;
int A_C_B = 0;
int A_BC = 0;
int AB_C = 0;
int AC_B = 0;
int ABC = 0;
int B_A_C = 0;
int B_C_A = 0;
int B_AC = 0;
int BC_A = 0;
int C_A_B = 0;
int C_B_A = 0;
int C_AB = 0;
for (int com1 = 1; com1 < 49; com1++) {
if (com1 != cards[0] && com1 != cards[1] && com1 != cards[2] && com1 != cards[3] && com1 != cards[4] && com1 != cards[5]) {
u2 = HR[u1+com1];
su2 = HR[su1+com1];
tu2 = HR[tu1+com1];
for (int com2 = com1 + 1; com2 < 50; com2++) {
if (com2 != cards[0] && com2 != cards[1] && com2 != cards[2] && com2 != cards[3] && com2 != cards[4] && com2 != cards[5]) {
u3 = HR[u2+com2];
su3 = HR[su2+com2];
tu3 = HR[tu2+com2];
for (int com3 = com2 + 1; com3 < 51; com3++) {
if (com3 != cards[0] && com3 != cards[1] && com3 != cards[2] && com3 != cards[3] && com3 != cards[4] && com3 != cards[5]) {
u4 = HR[u3+com3];
su4 = HR[su3+com3];
tu4 = HR[tu3+com3];
for (int com4 = com3 + 1; com4 < 52; com4++) {
if (com4 != cards[0] && com4 != cards[1] && com4 != cards[2] && com4 != cards[3] && com4 != cards[4] && com4 != cards[5]) {
u5 = HR[u4+com4];
su5 = HR[su4+com4];
tu5 = HR[tu4+com4];
for (int com5 = com4 + 1; com5 < 53; com5++) {
if (com5 != cards[0] && com5 != cards[1] && com5 != cards[2] && com5 != cards[3] && com5 != cards[4] && com5 != cards[5]) {
int rank_a = HR[u5 + com5];
int rank_b = HR[su5 + com5];
int rank_c = HR[tu5 + com5];
if (rank_a > rank_b && rank_b > rank_c) {
A_B_C++;
} else if (rank_a > rank_c && rank_c > rank_b) {
A_C_B++;
} else if (rank_a > rank_b && rank_b == rank_c) {
A_BC++;
} else if (rank_a == rank_b && rank_b > rank_c) {
AB_C++;
} else if (rank_a == rank_c && rank_c > rank_b) {
AC_B++;
} else if (rank_a == rank_c && rank_a == rank_b) {
ABC++;
} else if (rank_b > rank_a && rank_a > rank_c) {
B_A_C++;
} else if (rank_b > rank_c && rank_c > rank_a) {
B_C_A++;
} else if (rank_b > rank_a && rank_a == rank_c) {
B_AC++;
} else if (rank_b == rank_c && rank_c > rank_a) {
BC_A++;
} else if (rank_c > rank_a && rank_a > rank_b) {
C_A_B++;
} else if (rank_c > rank_b && rank_b > rank_a) {
C_B_A++;
} else {
C_AB++;
}
}
}
}
}
}
}
}
}
}
}
Text outputValue = new Text(Integer.toString(A_B_C) +"," + Integer.toString(A_C_B) + "," + Integer.toString(A_BC)+"," + Integer.toString(A_BC) +","+ Integer.toString(AB_C)+","+ Integer.toString(AC_B) +","+ Integer.toString(ABC)+"," +Integer.toString(B_A_C) +","+Integer.toString(B_C_A)+","+Integer.toString(B_AC) +","+Integer.toString(BC_A)+","+Integer.toString(C_A_B) +","+Integer.toString(C_B_A)+","+Integer.toString(C_AB) + "\n");
con.write(word, outputValue);
}
}
}

SPOJ Time Limit Exceeded - GENERAL

I'm trying to solve this problem of SPOJ: http://br.spoj.com/problems/GENERAL/
My solution works in Ideone (http://ideone.com/Xj2B9Y), but when I put the same solution in SPOJ, it reports that TLE - Time Limit Exceeded.
I have searched in the Internet to find a solution to improve my code. I replaced the "Scanner" by "BufferedReader", but I keep getting the message TLE.
Please could someone tell me where I am going wrong?
public static void main(String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
//Scanner scan = new Scanner(System.in);
int instancias = Integer.parseInt(br.readLine());
int count = 0;
while(instancias != 0)
{
count = 0;
boolean possible = true;
boolean impossible = false;
st = new StringTokenizer(br.readLine());
int numSoldados = Integer.parseInt(st.nextToken());
int distancia = Integer.parseInt(st.nextToken());
int[] listaSoldados = new int[numSoldados];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < numSoldados; i++)
{
listaSoldados[i] = Integer.parseInt(st.nextToken());
}
while(possible)
{
possible = false;
for (int i = 0; i < numSoldados; i++)
{
if(numSoldados - (i + distancia) >= 1)
{
int alturaPS = listaSoldados[i];
int alturaSS = listaSoldados[i + distancia];
if(alturaPS > alturaSS)
{
listaSoldados[i] = alturaSS;
listaSoldados[i + distancia] = alturaPS;
count = count + 1;
possible = true;
}
}
else
{
if(!possible)
{
for (int j = 0; j < numSoldados - 1; j++)
{
if(listaSoldados[j] > listaSoldados[j+1])
{
impossible = true;
break;
}
}
break;
}
break;
}
}
}
if(impossible)
System.out.println("impossivel");
else
System.out.println(count);
instancias--;
}
}

Categories