Cannot read a txt file - java

import java.io.*;
public class Point {
private double x;
private double y;
public Point(double x_coord, double y_coord) {
x = x_coord;
y = y_coord;
}
}
public class PointArray {
private Point points[];
public PointArray(FileInputStream fileIn) throws IOException {
try {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(fileIn));
int numberOfPoints = Integer.parseInt(inputStream.readLine())...points = new Point[numberOfPoints];
int i = 0;
String line;
while ((line = inputStream.readLine()) != null) {
System.out.print(line);
double x = Double.parseDouble(line.split(" ")[0]);
double y = Double.parseDouble(line.split(" ")[1]);
points[i] = new Point(x, y);
i++;
}
inputStream.close();
} catch (IOException e) {
System.out.println("Error");
System.exit(0);
}
}
}
public String toString() {
String format = "{";
for (int i = 0; i < points.length; i++) {
if (i < points.length - 1) format = format + points[i] + ", ";
else format = format + points[i];
}
format = format + "}";
return format;
}
public static void main(String[] args) {
FileInputStream five = new FileInputStream(new File("fivePoints.txt"));
PointArray fivePoints = new PointArray(five);
System.out.println(fivePoints.toString());
}
The txt file fivePoints is as shown below:
5
2 7
3 5
11 17
23 19
150 1
The first number in the first line means the number of points in the text file.
There is an error when I read the file. The output I want to get is {(2.0, 7.0), (3.0, 5.0), (11.0,17.0), (23.0, 19.0), (150.0, 1.0)}. How can I fix it?

Add a toString method to your Point which formats the Point as x, y
public class Point {
//...
#Override
public String toString() {
return x + ", " + y;
}
}
Move your toString method so it's defined in PointArray, you might also consider making use of StringJoiner to make your life simpler
public class PointArray {
//...
#Override
public String toString() {
StringJoiner sj = new StringJoiner(", ", "{", "}");
for (int i = 0; i < points.length; i++) {
sj.add("(" + points[i].toString() + ")");
}
return sj.toString();
}
}

Related

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;
}
}

Finding Max of Array of Objects/Writing To File

I am trying to find the max score from the array of objects. The code for that is everything below the int maxValue = -1; line of code. I am also trying to write that bands information to an external file:
import java.io.FileWriter;
public class App {
public static void main(String[] args) {
Bands[] bands = new Bands[5];
bands[0] = new Bands("Joe", "Rick", "Nick", "Dalton", "Doylestown, PA", "RockOn", 4000.50 , "Rock");
bands[1] = new Bands("Luke", "Bill", "Ian", "Matt", "State College, PA", "Blink182", 3500.50 , "Alternative");
bands[2] = new Bands("Corey", "Noah", "Jon", "Kaleb", "Philadelphia, PA", "Rise Against", 10000.50 , "Rock");
bands[3] = new Bands("Jake", "Joey", "Mike", "Mac", "New York, NY", "Thousand Foot Krutch", 2000.50 , "Rock");
bands[4] = new Bands("Bob", "Jeff", "Dom", "Mark", "King of Prussia, PA", "Skillet", 5500.50 , "Rock");
bands[0].compete();
bands[1].compete();
bands[2].compete();
bands[3].compete();
bands[4].compete();
for (int i = 0; i < 5; i++) {
String bandInfo = bands[i].getInfo();
System.out.println(bandInfo);
}
System.out.println("");
//DOESNT WORK BEYOND THIS POINT
int maxValue = -1;
for (int i = 0; i < bands.length; i++) {
if (bands[i].compete() > maxValue) {
maxValue = bands[i].compete();
}
}
try {
FileWriter fw = new FileWriter("src/winners.txt", true);
fw.write(bandInfo + "\n");
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And then here is my Bands class code:
import java.util.Random;
public class Bands {
private String singerName;
private String guitarName;
private String bassistName;
private String drummerName;
private String Hometown;
private String bandName;
private double income;
private String genre;
private int score;
private int winningBand;
public Bands(String singerName, String guitarName, String bassistName, String drummerName, String Hometown, String bandName, double income, String genre)
{
this.singerName = singerName;
this.guitarName = guitarName;
this.bassistName = bassistName;
this.drummerName = drummerName;
this.bandName = bandName;
this.Hometown = Hometown;
this.income = income;
this.genre = genre;
this.score = -1;
this.winningBand = -1;
}
public void compete()
{
Random rand = new Random();
this.score = rand.nextInt(20);
}
public int getScore()
{
return this.score;
}
public String getInfo()
{
String bandInfo = "Band: " + this.bandName + ", Singer: " + this.singerName + ", Guitarist: " + this.guitarName + ", Bassist: " + this.bassistName +
", Drummer: " + this.drummerName + ", Hometown: " + this.Hometown + ", Income: " + this.income + ", Genre: " +
this.genre + ", Final Score: " + this.score;
return bandInfo;
}
}
As for your question about only printing band with highest score info:
Create a global variable (In this case I called it winningBand as an Integer)
Then edit your loop:
for (int i = 0; i < bands.length; i++) {
if (bands[i].getScore() > maxValue) {
maxValue = bands[i].getScore();
winningBand = i;
}
}
Then when you write to the file, only write the winningBand:
try {
FileWriter fw = new FileWriter("src/winners.txt", true);
fw.write(band[winningBand].getInfo);
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
You are trying to find the highest score? Well in your code below
for (int i = 0; i < bands.length; i++) {
if (bands[i].compete() > maxValue) {
maxValue = bands[i].compete();
}
}
When you say .compete(), this does nothing. It assigns a random score in the Bands class. Instead it should look like this if you want to compare scores.
for (int i = 0; i < bands.length; i++) {
if (bands[i].getScore() > maxValue) {
maxValue = bands[i].getScore();
}
}
NOTE: You need to write a getScore() method in the band class that returns the score like the one below:
public Integer getScore(){
return score;
}
As for your question about writing to the file, this should work:
try {
FileWriter fw = new FileWriter("src/winners.txt", true);
for(int i = 0; i <= 4; i++){
fw.write(band[i].getInfo + "\n");
}
fw.close();
} catch (Exception e) {
e.printStackTrace();
}

How to input Strings into a 2D array

I have this code and I need to export the strings 'Name','Testav','HWav','Lows','grade' into a 2D array with the columns being the following respectively. I then need to export the 2D array into a csv file. Any help would be greatly appreciated.
import java.util.*;
import java.io.*;
import java.io.PrintWriter;
import java.text.*;
public class ComputeGrades {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.printf("Please enter the name of the input file: ");
String input_name = in.next();
System.out.printf("Please enter the name of the output CSV file: ");
String csv_name = in.next();
System.out.printf("Please enter the name of the output pretty-print file: ");
String pretty_name = in.next();
processGrades(input_name, csv_name, pretty_name);
System.out.printf("\nExiting...\n");
}
public static void processGrades (String input_name, String csv_name, String pretty_name)
{
PrintWriter csv = null;
PrintWriter pretty = null;
String[][] data = readSpreadsheet(input_name);
boolean resultb = sanityCheck(data);
int length = data.length;
ArrayList<String> test_avg = new ArrayList<String>();
ArrayList<String> HW_avg = new ArrayList<String>();
ArrayList<String> NAME = new ArrayList<String>();
ArrayList<String> ColN = new ArrayList<String>();
ArrayList<String> Hell = new ArrayList<String>();
String[][] kill_me = new String[length][];
for(int row = 1; row<length; row++)
{
String name = data[row][0];
String name2 = data[row][1];
String Name = name+" "+name2;
int test1 = Integer.parseInt(data[row][2]);
int test2 = Integer.parseInt(data[row][3]);
int test3 = Integer.parseInt(data[row][4]);
int Test = (test1+test2+test3)/3;
String Testav = Integer.toString(Test);
int hw1 = Integer.parseInt(data[row][5]);
int hw2 = Integer.parseInt(data[row][6]);
int hw3 = Integer.parseInt(data[row][7]);
int hw4 = Integer.parseInt(data[row][8]);
int hw5 = Integer.parseInt(data[row][9]);
int hw6 = Integer.parseInt(data[row][10]);
int hw7 = Integer.parseInt(data[row][11]);
int HW = (hw1+hw2+hw3+hw4+hw5+hw6+hw7)/7;
String HWav = Integer.toString(HW);
int[] trying = {Test, HW};
int low = find_min(trying);
String Lows = Integer.toString(low);
String grade = null;
if(low>=90)
{
grade ="A";
}
if(low < 90 && low>= 80)
{
grade = "B";
}
if(low <80 && low>=70)
{
grade ="C";
}
if(low<70 && low>=60)
{
grade="D";
}
if(low<60)
{
grade = "F";
}
test_avg.add(Testav);
HW_avg.add(HWav);
NAME.add(Name);
Hell.add(Name);
Hell.add(Testav);
Hell.add(HWav);
Hell.add(Lows);
Hell.add(grade);
}
System.out.println(Hell);
System.out.printf("\n");
File csvFile = new File(csv_name);
try (PrintWriter csvWriter = new PrintWriter(new FileWriter(csvFile));){
Hell.stream().forEach(csvWriter::println);
} catch (IOException e) {
}
}
public static int find_min(int[] values)
{
int result = values[0];
for(int i = 0; i<values.length; i++)
{
if(values[i]<result)
{
result = values[i];
}
}
return result;
}
public static boolean sanityCheck(String[][] data)
{
if (data == null)
{
System.out.printf("Sanity check: nul data\n");
return false;
}
if(data.length<3)
{
System.out.printf("Sanity check: %d rows\n",data.length);
return false;
}
int cols= data[0].length;
for(int row = 0; row<data.length; row++)
{
int current_cols = data[row].length;
if(current_cols!=cols)
{
System.out.printf("Sanity Check: %d columns at rows%d\n", current_cols, row);
return false;
}
}
return true;
}
public static String[][] readSpreadsheet(String filename)
{
ArrayList<String> lines = readFile(filename);
if (lines == null)
{
return null;
}
int rows = lines.size();
String[][] result = new String[rows][];
for (int i = 0; i < rows; i++)
{
String line = lines.get(i);
String[] values = line.split(",");
result[i] = values;
}
return result;
}
public static ArrayList<String> readFile(String filename)
{
File temp = new File(filename);
Scanner input_file;
try
{
input_file = new Scanner(temp);
} catch (Exception e)
{
System.out.printf("Failed to open file %s\n",
filename);
return null;
}
ArrayList<String> result = new ArrayList<String>();
while (input_file.hasNextLine())
{
String line = input_file.nextLine();
result.add(line);
}
input_file.close();
return result;
}
}
input file:
First,Last,Exam1,Exam2,Final,H1,H2,H3,H4,H5,H6,H7
Ping,Milledge,43,59,68,69,62,43,60,38,37,40
Elisa,Oltz,76,94,73,100,99,100,90,97,100,92
Leonard,Havers,67,95,57,69,95,71,68,61,93,61
Setsuko,Lovera,78,100,84,89,88,92,65,85,66,97
Franklyn,Degnim,54,74,50,63,78,42,42,41,67,64
Gwyneth,Marsico,61,89,81,59,59,62,88,60,66,66
Abigail,Greep,69,99,93,94,91,85,78,91,69,71
Majorie,Granvold,78,100,100,82,96,100,89,100,100,94
Daphine,Polaco,62,82,88,81,68,89,62,73,90,62
An,Corvera,44,71,37,46,57,42,59,66,54,60
Ayanna,Pensiero,64,42,56,37,53,66,69,52,43,58
Era,Deming,98,81,100,69,65,73,77,78,73,89
Michal,Slentz,73,85,81,82,74,93,81,76,69,81
Corie,Brazen,86,99,66,100,69,97,96,100,70,84
Dona,Tufte,63,54,70,71,55,68,86,66,75,63
Juan,Rohdenburg,78,89,100,91,80,97,92,100,98,100
Orville,Samit,88,63,60,88,81,56,91,76,77,80
Ricky,Knoechel,100,100,93,81,100,90,100,92,100,84
Blythe,Threet,38,68,35,61,63,51,48,72,49,51
Sammie,Wachs,46,53,52,76,50,52,56,68,46,75
Estelle,Veazey,72,87,69,98,96,77,95,91,100,91
Agatha,Keckler,100,92,90,95,85,100,94,85,92,100
Novella,Oros,85,76,100,92,84,77,77,90,86,98
Tanya,Quinlisk,47,78,71,50,79,52,69,66,51,45
Marion,Coltrin,68,68,54,39,61,44,66,58,47,74
Helene,Karow,100,100,75,79,100,100,100,92,89,96
Shonta,Bourek,100,96,90,81,97,84,91,100,100,100
Hyon,Anglemyer,81,76,43,43,47,53,44,60,57,65
Ervin,Kenison,78,53,54,75,55,46,61,75,56,69
Renato,Urch,71,64,64,84,49,57,63,69,81,64
Mikel,Burleigh,88,100,90,100,90,91,90,80,74,74
Val,Royal,100,80,100,99,100,100,76,86,100,96
Jodie,Adolfo,94,77,59,83,67,79,87,82,82,75
Roselee,Lienhard,68,75,58,82,96,62,60,94,68,58
Austin,Holznecht,76,49,79,48,58,68,67,71,70,61
Emelia,Toney,70,95,74,90,99,68,100,66,98,98
Lucy,Rhodd,71,91,100,82,100,93,100,100,71,81
Sacha,Chee,78,71,90,82,74,64,62,87,69,84
Julio,Lackner,56,86,53,88,88,73,57,59,80,85
Salvador,Gretzner,54,83,91,66,78,67,61,84,82,6
export file(csv_name)
name,exam_score,hw_score,min_score,grade
Ping Milledge,56.666667,49.857143,49.857143,F
Elisa Oltz,81.000000,96.857143,81.000000,B
Leonard Havers,73.000000,74.000000,73.000000,C
Setsuko Lovera,87.333333,83.142857,83.142857,B
Franklyn Degnim,59.333333,56.714286,56.714286,F
Gwyneth Marsico,77.000000,65.714286,65.714286,D
Abigail Greep,87.000000,82.714286,82.714286,B
Majorie Granvold,92.666667,94.428571,92.666667,A
Daphine Polaco,77.333333,75.000000,75.000000,C
An Corvera,50.666667,54.857143,50.666667,F
Ayanna Pensiero,54.000000,54.000000,54.000000,F
Era Deming,93.000000,74.857143,74.857143,C
Michal Slentz,79.666667,79.428571,79.428571,C
Corie Brazen,83.666667,88.000000,83.666667,B
Dona Tufte,62.333333,69.142857,62.333333,D
Juan Rohdenburg,89.000000,94.000000,89.000000,B
Orville Samit,70.333333,78.428571,70.333333,C
Ricky Knoechel,97.666667,92.428571,92.428571,A
Blythe Threet,47.000000,56.428571,47.000000,F
Sammie Wachs,50.333333,60.428571,50.333333,F
Estelle Veazey,76.000000,92.571429,76.000000,C
Agatha Keckler,94.000000,93.000000,93.000000,A
Novella Oros,87.000000,86.285714,86.285714,B
Tanya Quinlisk,65.333333,58.857143,58.857143,F
Marion Coltrin,63.333333,55.571429,55.571429,F
Helene Karow,91.666667,93.714286,91.666667,A
Shonta Bourek,95.333333,93.285714,93.285714,A
Hyon Anglemyer,66.666667,52.714286,52.714286,F
Ervin Kenison,61.666667,62.428571,61.666667,D
Renato Urch,66.333333,66.714286,66.333333,D
Mikel Burleigh,92.666667,85.571429,85.571429,B
Val Royal,93.333333,93.857143,93.333333,A
Jodie Adolfo,76.666667,79.285714,76.666667,C
Roselee Lienhard,67.000000,74.285714,67.000000,D
Austin Holznecht,68.000000,63.285714,63.285714,D
Emelia Toney,79.666667,88.428571,79.666667,C
Lucy Rhodd,87.333333,89.571429,87.333333,B
Sacha Chee,79.666667,74.571429,74.571429,C
Julio Lackner,65.000000,75.714286,65.000000,D
Salvador Gretzner,76.000000,71.714286,71.714286,C
export file 2(pretty_name)
name: exam score, hw score, min score, grade
Ping Milledge: 56.67, 49.86, 49.86, F
Elisa Oltz: 81.00, 96.86, 81.00, B
Leonard Havers: 73.00, 74.00, 73.00, C
Setsuko Lovera: 87.33, 83.14, 83.14, B
Franklyn Degnim: 59.33, 56.71, 56.71, F
Gwyneth Marsico: 77.00, 65.71, 65.71, D
Abigail Greep: 87.00, 82.71, 82.71, B
Majorie Granvold: 92.67, 94.43, 92.67, A
Daphine Polaco: 77.33, 75.00, 75.00, C
An Corvera: 50.67, 54.86, 50.67, F
Ayanna Pensiero: 54.00, 54.00, 54.00, F
Era Deming: 93.00, 74.86, 74.86, C
Michal Slentz: 79.67, 79.43, 79.43, C
Corie Brazen: 83.67, 88.00, 83.67, B
Dona Tufte: 62.33, 69.14, 62.33, D
Juan Rohdenburg: 89.00, 94.00, 89.00, B
Orville Samit: 70.33, 78.43, 70.33, C
Ricky Knoechel: 97.67, 92.43, 92.43, A
Blythe Threet: 47.00, 56.43, 47.00, F
Sammie Wachs: 50.33, 60.43, 50.33, F
Estelle Veazey: 76.00, 92.57, 76.00, C
Agatha Keckler: 94.00, 93.00, 93.00, A
Novella Oros: 87.00, 86.29, 86.29, B
Tanya Quinlisk: 65.33, 58.86, 58.86, F
Marion Coltrin: 63.33, 55.57, 55.57, F
Helene Karow: 91.67, 93.71, 91.67, A
Shonta Bourek: 95.33, 93.29, 93.29, A
Hyon Anglemyer: 66.67, 52.71, 52.71, F
Ervin Kenison: 61.67, 62.43, 61.67, D
Renato Urch: 66.33, 66.71, 66.33, D
Mikel Burleigh: 92.67, 85.57, 85.57, B
Val Royal: 93.33, 93.86, 93.33, A
Jodie Adolfo: 76.67, 79.29, 76.67, C
Roselee Lienhard: 67.00, 74.29, 67.00, D
Austin Holznecht: 68.00, 63.29, 63.29, D
Emelia Toney: 79.67, 88.43, 79.67, C
Lucy Rhodd: 87.33, 89.57, 87.33, B
Sacha Chee: 79.67, 74.57, 74.57, C
Julio Lackner: 65.00, 75.71, 65.00, D
Salvador Gretzner: 76.00, 71.71, 71.71, C
This should do it, if you have question about the code, just ask.
public static void processGrades (String input_name, String csv_name, String pretty_name) {
DecimalFormat decimalFormat = new DecimalFormat(".000000");
String[][] data = readSpreadsheet(input_name);
String[][] result = new String[data.length][];
result[0] = new String[]{"name", "exam_score", "hw_score", "min_score", "grade"};
// Export to 2D String array
for(int row = 1; row < data.length; row++) {
String name = data[row][0] + " " + data[row][1];
double testAverage = average(data[row], 2, 5);
double homeworkAverage = average(data[row], 5, 12);
double min = Math.min(testAverage, homeworkAverage);
char grade = (char) (74 - ((int) min / 10));
grade = grade > 'D' ? 'F' : grade;
result[row] = new String[]{
name,
decimalFormat.format(testAverage),
decimalFormat.format(homeworkAverage),
decimalFormat.format(min),
Character.toString(grade)
};
}
// Export 2D array into a csv String
String csv = "";
for (int y = 0; y < result.length; y++) {
for (int x = 0; x < result[y].length - 1; x++) {
csv += result[y][x] + ",";
}
csv += result[y][result[y].length - 1] + "\n";
}
// Save String in file
File file = new File(csv_name);
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
bw.write(csv);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static double average(String[] row, int fromIndex, int toIndex) {
double total = 0;
for (int i = fromIndex; i < toIndex; i++) {
total += Integer.parseInt(row[i]);
}
return total / (toIndex - fromIndex);
}

How to resolve huge matrix multiplication performance issue in Android

I have huge .csv files (the biggest one, 72mb) that I need to load to my Android App. They contain matrices e.g [7500x1000], which I later use to multiply another one. Because their are too big to read them at one time () I'm reading line after line and perform some multiplication. I tested this on Nexus 4 and It took something about 15 minutes to do everything. When I copied the code from Android project to JAVA one(the only difference is that in Android i'm using Bitmap and in JAVA BufferedImage) and ran this as java application it took few seconds. Do you have any idea why is so and how to shorten this time? Here Is my code:
Android:
public class NetworkThread extends Thread {
private static boolean threadIsWorking = false;
private Context context;
private SQLiteHandler sql;
private static NetworkThread REFERENCE = null;
private String w1 = "w1.csv";
private String w2 = "w2.csv";
private String w3 = "w3.csv";
private String w4 = "w4.csv";
String NEURON_PATH = "/data/data/com.ZPIProject/neuronFiles/";
public static NetworkThread getInstance(Context context, SQLiteHandler sql) {
if (REFERENCE == null)
REFERENCE = new NetworkThread(context, sql);
return REFERENCE;
}
private NetworkThread(Context context, SQLiteHandler sql) {
this.context = context;
this.sql = sql;
}
#Override
public void start() {
if (!threadIsWorking) {
threadIsWorking = true;
try {
Log.i("MATRIX", "THREAD ID: " + Thread.currentThread().getId());
Bitmap bit = BitmapFactory.decodeResource(context.getResources(), R.drawable.aparat_small);
double[] imageInfo = ImageUtils.getImageInfo(bit);
copyNeuronWeightsToMemoryOnPhone();
double[] m4 = multiplyImageWithNeuronWeights(imageInfo);
List<WeightWithId> best10 = findBest10Results(m4);
for (int i = 0; i < best10.size(); i++) {
Log.e("IDS", best10.get(i).getId() + "");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private List<WeightWithId> findBest10Results(double[] m4) throws SQLException, CloneNotSupportedException {
List<WeightWithId> best10 = new ArrayList<WeightWithId>(20);
for (int j = 0; j < 19; j++) {
Map<Integer, double[]> readDescriptions = sql.getDescriptionForShoeId(j * 100, j * 100 + 100);
List<WeightWithId> distances = new ArrayList<WeightWithId>(100);
for (Integer i : readDescriptions.keySet()) {
double dist = dist(m4, readDescriptions.get(i));
distances.add(new WeightWithId(i, dist));
}
Collections.sort(distances);
for (int i = 0; i < 10; i++) {
best10.add(distances.get(i).clone());
}
Collections.sort(best10);
if (best10.size() > 10) {
for (int i = 10; i < best10.size(); i++) {
best10.remove(i);
}
}
}
return best10;
}
private double[] multiplyImageWithNeuronWeights(double[] imageInfo) throws IOException {
Log.i("MATRIX MULTIPLY", "M1");
double[] m1 = MatrixMaker.multiplyMatrixWithCsvMatrix(NEURON_PATH + w1, imageInfo, 1000, false);
Log.i("MATRIX MULTIPLY", "M2");
double[] m2 = MatrixMaker.multiplyMatrixWithCsvMatrix(NEURON_PATH + w2, m1, 500, false);
Log.i("MATRIX MULTIPLY", "M3");
double[] m3 = MatrixMaker.multiplyMatrixWithCsvMatrix(NEURON_PATH + w3, m2, 250, false);
Log.i("MATRIX MULTIPLY", "M4");
return MatrixMaker.multiplyMatrixWithCsvMatrix(NEURON_PATH + w4, m3, 50, true);
}
private void copyNeuronWeightsToMemoryOnPhone() throws IOException {
Log.i("MATRIX COPY", "W1");
CopyUtils.copyFileIntoDevice(NEURON_PATH, w1, context);
Log.i("MATRIX COPY", "W2");
CopyUtils.copyFileIntoDevice(NEURON_PATH, w2, context);
Log.i("MATRIX COPY", "W3");
CopyUtils.copyFileIntoDevice(NEURON_PATH, w3, context);
Log.i("MATRIX COPY", "W4");
CopyUtils.copyFileIntoDevice(NEURON_PATH, w4, context);
}
private double dist(double[] a, double[] b) {
double result = 0;
for (int i = 0; i < a.length; i++)
result += (a[i] - b[i]) * (a[i] - b[i]);
return result;
}
}
Matrix Operations:
public class MatrixMaker {
public static double[] multiplyImageInfoWithCsvMatrix(String csvFilePath, double[] imageInfo, int expectedSize, boolean lastOne) throws IOException {
InputStream inputStream = new FileInputStream(new File(csvFilePath));
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
//counter - to which position calculated value should be setted
int counter = 0;
//result array
double[] multipliedImageInfoWithCsvMatrix = new double[expectedSize + 1];
//declaration of array for read line (parsed into double array)
double[] singleLineFromCsv = new double[imageInfo.length];
while ((line = bufferedReader.readLine()) != null) {
//splitting and parsing values from read line
String[] splitted = line.split(",");
for (int i = 0; i < splitted.length; i++) {
singleLineFromCsv[i] = Double.valueOf(splitted[i]);
}
//multiply imageInfo array with single row from csv file
multipliedImageInfoWithCsvMatrix[counter] = multiplyOneRow(imageInfo, singleLineFromCsv);
//ugly flag 'lastOne' needed to other business case
if (!lastOne) {
multipliedImageInfoWithCsvMatrix[counter] = 1d / (1 + Math.exp(-multipliedImageInfoWithCsvMatrix[counter]));
}
counter++;
//logging progress
if (counter % 100 == 0)
Log.i("MULTIPLY PROGRESS", counter + " " + System.currentTimeMillis());
}
if (!lastOne)
multipliedImageInfoWithCsvMatrix[expectedSize] = 1d;
bufferedReader.close();
inputStream.close();
return multipliedImageInfoWithCsvMatrix;
}
private static double multiplyOneRow(double first[], double second[]) {
double result = 0d;
for (int i = 0; i < first.length; i++) {
result += first[i] * second[i];
}
return result;
}
}
onCreate in one of Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
final SQLiteHandler sql = new SQLiteHandler(this);
sql.init();
NetworkThread.getInstance(this, sql).start();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
JAVA:
Multiply equivalent of Matrix Maker
import java.io.*;
public class Multiply {
public static double[] multiplyMatrixWithCsvMatrix(String csvFilePath, double[] imageInfo,
int expectedSize, boolean lastOne) throws IOException {
InputStream inputStream = new FileInputStream(new File(csvFilePath));
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
// counter - to which position calculated value should be setted
int counter = 0;
// result array
double[] multipliedImageInfoWithCsvMatrix = new double[expectedSize + 1];
// declaration of array for read line (parsed into double array)
double[] singleLineFromCsv = new double[imageInfo.length];
while ((line = bufferedReader.readLine()) != null) {
// splitting and parsing values from read line
String[] splitted = line.split(",");
for (int i = 0; i < splitted.length; i++) {
singleLineFromCsv[i] = Double.valueOf(splitted[i]);
}
// multiply imageInfo array with single row from csv file
multipliedImageInfoWithCsvMatrix[counter] = multiplyOneRow(imageInfo, singleLineFromCsv);
// ugly flag 'lastOne' needed to other business case
if (!lastOne) {
multipliedImageInfoWithCsvMatrix[counter] = 1d / (1 + Math
.exp(-multipliedImageInfoWithCsvMatrix[counter]));
}
counter++;
// logging progress
if (counter % 100 == 0)
System.out.println(counter + " " + System.currentTimeMillis());
}
if (!lastOne)
multipliedImageInfoWithCsvMatrix[expectedSize] = 1d;
bufferedReader.close();
inputStream.close();
return multipliedImageInfoWithCsvMatrix;
}
private static double multiplyOneRow(double first[], double second[]) {
double result = 0d;
for (int i = 0; i < first.length; i++) {
result += first[i] * second[i];
}
return result;
}
}
Executable class
public class MRunner {
private static final int RED_INDEX = 0;
private static final int GREEN_INDEX = 2500;
private static final int BLUE_INDEX = 5000;
private static final String w1 = "w1.csv";
private static final String NEURON_PATH = "C:\\Users\\Vortim\\Desktop\\";
public static void main(String[] args) {
new Thread(new Runnable() {
#Override
public void run() {
try {
Multiply.multiplyMatrixWithCsvMatrix(NEURON_PATH + w1, getImageInfo(ImageIO
.read(new File("C:\\Users\\Vortim\\git\\MatrixMaker\\but.png"))), 1000,
false);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public static double[] getImageInfo(BufferedImage source) {
double[] result = new double[7501];
int width = source.getWidth();
int height = source.getHeight();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (x == 0) {
result[y + RED_INDEX] = 255d;
result[y + GREEN_INDEX] = 255d;
result[y + BLUE_INDEX] = 255d;
} else if (y == 0) {
result[x * 50 + RED_INDEX] = 255d;
result[x * 50 + GREEN_INDEX] = 255d;
result[x * 50 + BLUE_INDEX] = 255d;
} else {
int pixel = source.getRGB(x, y);
double r = (pixel) >> 16 & 0xff;
double g = (pixel) >> 8 & 0xff;
double b = (pixel) & 0xff;
result[x * y + RED_INDEX] = 1d - (r / 255d);
result[x * y + GREEN_INDEX] = 1d - (g / 255d);
result[x * y + BLUE_INDEX] = 1d - (b / 255d);
}
}
}
result[7500] = 1;
return result;
}
}

Setting the name of an arraylist object java - homework

I have a homework problem that I have been working on for quit a while now. I am creating objects which are shapes then putting them in an arrayList then putting a collection of those shapes in another array list. Then drawing the shape as a picture all at one time. I need to name them so I can use the name of the collection Picture to draw the text file. I got the program working (it draws the shapes correctly) but when set the name of the picture then get it, it returns null. I believe that it is because my method I am not properly passing the name. Of Course help would be Greatly appreciated.
//read in text from file
start picture A // I want to name the picture A
circle 100 100 20
rectangle 100 100 20 30
draw A // I want to draw picture A
import java.awt.Graphics;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;
public class Driver {
private static String fileName;
private static String line;
private static Graphics g;
private static char[] name1;
public static void main(String[] args) {
ArrayList<Picture> collection = new ArrayList<Picture>();
try {
readLines(collection);
} catch (Exception e) {
e.printStackTrace();
}
}
static void readLines(ArrayList<Picture> collection) throws Exception {
Picture<Shape> pictures = new Picture<Shape>();
Scanner input = new Scanner(System.in);
System.out.print("Please enter the file name ---> ");
fileName = input.next();
FileReader fr = new FileReader(fileName);
BufferedReader inFile = new BufferedReader(fr);
// loop through lines
while ((line = inFile.readLine()) != null) {
System.out.println(line);
txtAnalysis(line, collection,pictures);
}
// close file
inFile.close();
}
public static void txtAnalysis(String name, ArrayList<Picture> collection, Picture<Shape> pictures ) {
if (line.startsWith("start picture")) {
String picName = line.split(" ")[2];
pictures = new Picture<Shape>();
//set the name here
pictures.setName(picName);
//here it works
System.out.print(pictures.getName());
}
else if (line.startsWith("circle")) {
String[] parts = line.split(" ");
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
//new object circle
Circle c1 = new Circle("circ", x, y, z);
//add object
System.out.println("calling add " + c1);
pictures.addShape(c1);
}
else if (line.startsWith("rectangle")) {
String[] parts = line.split(" ");
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
//new object rectangle
Rectangle r1 = new Rectangle("rect", x, y, z); // small and upper
//add object
pictures.addShape(r1);
}
else if (line.startsWith("draw")) {
collection.add(pictures);
//problem here
pictures.draw(pictures.getName());
//returns null!!!!!
System.out.print(pictures.getName());
line = null;
}
else {
System.out.println("end of loop");
}
}
}
Picture class
import java.awt.Graphics;
import java.util.*;
public class Picture <E extends Shape> {
private ArrayList<Shape> shapes;
private String name;
public Picture() {
shapes = new ArrayList<Shape>();
}
public String getName() {
//System.out.println("getting the name");
return name;
}
public String setName(String name) {
// System.out.println("setting the name " + name);
this.name = name;
return name;
}
public boolean addShape(E newA) {
// System.out.println("add shape" + newA);
boolean b = shapes.add(newA);
return b;
}
public void draw(String name) {
DrawingPanel panel = new DrawingPanel(600, 600);
Graphics g = panel.getGraphics();
for (Shape shape : shapes) {
System.out.print("this is cool");
shape.draw(g, 0, 0);
}
}
public String toString(String name) {
String s = "Picture " + name + " hosts these shapes:\n";
for (int i = 0; i < shapes.size(); i++) {
s += " " + shapes.get(i).toString() + "\n";
}
return s;
}
}
The problem is that pictures = new Picture<Shape>(); doesn't affect the global value of pictures; it only affects the local value of pictures in txtAnalysis(). A simple code shift should get you the result you're looking for, by setting the value of pictures in a place where it will actually stick:
static void readLines(ArrayList<Picture> collection) throws Exception {
Picture<Shape> pictures = null; //Just do null here
Scanner input = new Scanner(System.in);
System.out.print("Please enter the file name ---> ");
fileName = input.next();
FileReader fr = new FileReader(fileName);
BufferedReader inFile = new BufferedReader(fr);
// loop through lines
while ((line = inFile.readLine()) != null) {
System.out.println(line);
if (line.startsWith("start picture")) {
String picName = line.split(" ")[2];
pictures = new Picture<Shape>();
//set the name here
pictures.setName(picName);
//here it works
System.out.print(pictures.getName());
}
else {
txtAnalysis(line, collection,pictures);
}
}
// close file
inFile.close();
}
public static void txtAnalysis(String name, ArrayList<Picture> collection, Picture<Shape> pictures ) {
if (line.startsWith("circle")) {
String[] parts = line.split(" ");
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
//new object circle
Circle c1 = new Circle("circ", x, y, z);
//add object
System.out.println("calling add " + c1);
pictures.addShape(c1);
}
else if (line.startsWith("rectangle")) {
String[] parts = line.split(" ");
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
//new object rectangle
Rectangle r1 = new Rectangle("rect", x, y, z); // small and upper
//add object
pictures.addShape(r1);
}
else if (line.startsWith("draw")) {
collection.add(pictures);
//problem here
pictures.draw(pictures.getName());
//returns null!!!!!
System.out.print(pictures.getName());
line = null;
}
else {
System.out.println("end of loop");
}
}

Categories