I have Two Function in Reducer Class : "reducer" and "execute". in "myExecute" function :
public class Reducer extends MapReduceBase
implements Reducer<IntWritable,Text, IntWritable, Text>, TIntProcedure
{
OutputCollector< IntWritable, Text> m_Collector = null;
RTree tree = new RTree();
private int m_BasePolyId;
private HashMap<Integer,PolyDefault> m_BasePolyMap = new HashMap<Integer,PolyDefault>();
private HashMap<Integer,PolyDefault> m_ClipPolyMap = new HashMap<Integer,PolyDefault>();
public void configure(JobConf conf)
{
//initialize the RTree
tree.init(null);
}
// the key is grid id and values are the polygon texts
public void reduce(IntWritable gridId, Iterator<Text> values,
OutputCollector<IntWritable, Text> collector, Reporter arg3)
throws IOException
{
m_Collector = collector;
List<PolyDefault>basePolyList = new ArrayList<PolyDefault>();
List<PolyDefault> overlayPolyList = new ArrayList<PolyDefault>();
Text clipText;
int count = 0;
String strcount = " ";
PolyDefault basePolygon = null;
String strBaseId;
String strClipId;
int baseId = 0;
int clipId = 0;
//values contain both basepolygons and clip polygons
PolyDefault clipPoly;
while(values.hasNext())
{
Text text = values.next();
if(text.charAt(0) == 'b')
{
basePolygon = new PolyDefault();
StringTokenizer baseItr = new StringTokenizer(text.toString());
//System.err.println("base : = " + baseText);
while (baseItr.hasMoreTokens()) // tokens are strings from one serialized polygon
{
if(count == 0)
{
baseItr.nextToken(); //discard
strBaseId = baseItr.nextToken(); //index or line number
baseId = Integer.parseInt(strBaseId);
Point2D lbox = new Point2D.Double(Double.parseDouble(baseItr.nextToken()), Double.parseDouble(baseItr.nextToken()));
basePolygon.setM_lbBox(lbox);
Point2D ubox = new Point2D.Double(Double.parseDouble(baseItr.nextToken()),Double.parseDouble(baseItr.nextToken()));
basePolygon.setM_ubBox(ubox);
}
count = count + 1;
double xCord,yCord;
xCord = Double.parseDouble(baseItr.nextToken());
yCord = Double.parseDouble(baseItr.nextToken());
Point2D vertex = new Point2D.Double(xCord,yCord);
basePolygon.add(vertex);
}
basePolyList.add(basePolygon);
m_BasePolyMap.put(baseId,basePolygon);
}
else
{
StringTokenizer clipItr = new StringTokenizer(text.toString());
clipPoly = new PolyDefault();
while(clipItr.hasMoreTokens())
{
if(count == 0)
{
//discard the index or line number
strClipId = clipItr.nextToken(); //index or line number
clipId = Integer.parseInt(strClipId);
Point2D lbox = new Point2D.Double(Double.parseDouble(clipItr.nextToken()), Double.parseDouble(clipItr.nextToken()));
clipPoly.setM_lbBox(lbox);
Point2D ubox = new Point2D.Double(Double.parseDouble(clipItr.nextToken()),Double.parseDouble(clipItr.nextToken()));
clipPoly.setM_ubBox(ubox);
Rectangle r2 = new Rectangle((float)lbox.getX(), (float)lbox.getY(), (float)ubox.getX(), (float)ubox.getY());
tree.add(r2, clipId);
}
count = count + 1;
double xCord,yCord;
xCord = Double.parseDouble(clipItr.nextToken());
yCord = Double.parseDouble(clipItr.nextToken());
Point2D vertex = new Point2D.Double(xCord,yCord);
clipPoly.add(vertex);
}
//overlayPolyList.add(clipPoly);
m_ClipPolyMap.put(clipId, clipPoly);
}
} //end while
Iterator<PolyDefault> itr = basePolyList.iterator();
Rectangle baseBox = new Rectangle();
PolyDefault basePoly;
while(itr.hasNext())
{
basePoly = itr.next();
baseBox.maxX = (float)basePoly.getM_ubBox().getX();
baseBox.maxY = (float)basePoly.getM_ubBox().getY();
baseBox.minX = (float)basePoly.getM_lbBox().getX();
baseBox.minY = (float)basePoly.getM_lbBox().getY();
this.m_BasePolyId = basePoly.getId();
tree.intersects(baseBox, this);
}
} //end reduce
public boolean execute(int clipPolyId)
{
PolyDefault basePoly = m_BasePolyMap.get(m_BasePolyId);
PolyDefault clipPoly = m_ClipPolyMap.get(clipPolyId);
PolyDefault resultPoly = (PolyDefault)Clip.intersection(basePoly, clipPoly);
String strResult;
if(resultPoly.isEmpty() == false)
{
strResult = Parser.serializePoly(resultPoly).toString();
try
{
m_Collector.collect(null,new Text(strResult) );
System.out.println(strResult);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
}
map and reduce run completely , but in output(part-0000) , there is no message "Result Sucess ..." .
can I call Execute function in reducer or ... ?
Thanks
Related
Someone, please assist to change the method 'getBabyNameFrequencies' in class 'Result' from using HarshMap to a normal String method as is in the main/feeder class 'Solution'
/*
* The function is expected to return a STRING.
* The function accepts the following parameters:
* 1. STRING names
* 2. STRING synonyms
*/
class Solution {
private Map<String, Integer> mp = new HashMap<>();
private Map<String, String> p = new HashMap<>();
public String[] getBabyNameFrequencies(String[] names, String[] synonyms) {
for (String e : names) {
int idx = e.indexOf("(");
String name = e.substring(0, idx);
int w = Integer.parseInt(e.substring(idx + 1, e.length() - 1));
mp.put(name, w);
p.put(name, name);
}
for (String e : synonyms) {
int idx = e.indexOf(",");
String name1 = e.substring(1, idx);
String name2 = e.substring(idx + 1, e.length() - 1);
if (!mp.containsKey(name1)) {
mp.put(name1, 0);
}
if (!mp.containsKey(name2)) {
mp.put(name2, 0);
}
p.put(name1, name1);
p.put(name2, name2);
}
for (String e : synonyms) {
int idx = e.indexOf(",");
String name1 = e.substring(1, idx);
String name2 = e.substring(idx + 1, e.length() - 1);
union(name1, name2);
}
List<String> t = new ArrayList<>();
for (Map.Entry<String, Integer> e : mp.entrySet()) {
String name = e.getKey();
if (Objects.equals(name, find(name))) {
t.add(name + "(" + e.getValue() + ")");
}
}
String[] res = new String[t.size()];
for (int i = 0; i < res.length; ++i) {
res[i] = t.get(i);
}
return res;
}
private String find(String x) {
if (!Objects.equals(p.get(x), x)) {
p.put(x, find(p.get(x)));
}
return p.get(x);
}
private void union(String a, String b) {
String pa = find(a), pb = find(b);
if (Objects.equals(pa, pb)) {
return;
}
if (pa.compareTo(pb) > 0) {
mp.put(pb, mp.getOrDefault(pb, 0) + mp.getOrDefault(pa, 0));
p.put(pa, pb);
} else {
mp.put(pa, mp.getOrDefault(pa, 0) + mp.getOrDefault(pb, 0));
p.put(pb, pa);
}
}
}
The Solution Class/ Feeder Class with the Main method.
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String names = bufferedReader.readLine();
String synonyms = bufferedReader.readLine();
String result = Result.getBabyNameFrequencies(names, synonyms);
bufferedWriter.write(result);
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
I created a program that tries to find the shortest path between train stations in NYC. I have a shortest path algorithm working with a priority queue but for some reason my queue isn't working. The autoAssLinks function is what is creating my links for my hashset. That's the only place I can think might have a problem.
public void autoAddLinks() {
InputReader input = new InputReader("StationsModified2.txt");
new Graph();
String currentLine = "";
String stationPrev = "";
String stationCurr = "";
String inputLine = input.readLine();
while (inputLine != null) {
if (inputLine.trim().equals("")) { //line is empty
inputLine = input.readLine(); //reads next line
continue; //ignore empty line
} else {
if (stationCurr.equals("")) { //first station of the line
stationCurr = inputLine.trim();
} else { //already have a station stored
stationPrev = stationCurr;
stationCurr = inputLine.trim();
addLink(stationPrev, stationCurr, currentLine);
addStation(stationCurr);
}
}
inputLine = input.readLine();
}
}
public void path(Station a, Station b){
q = new PriorityQueue();
visited = new HashMap();
Label from = new Label(a);
from.cost = 0;
q.add(from);
for(Station station: g.stations.values()){
if(!a.equals(station)){
from = new Label(station);
q.add(from);
}
}
while(!q.isEmpty()){
Label u = q.poll();
visited.put(u.here.name, u);
for(Link link: g.links){
Label v = getLabel(link.from);
if(link.from.equals(u.here.name)&& v != null){
int newCost = u.cost + link.weight;
if(newCost<v.cost){
v.cost = newCost;
v.from = u;
q.remove(v);
q.add(v);
}
}
}
}
Label label = visited.get(b.name);
route = new ArrayList();
while(!label.here.equals(a)){
route.add(label.here);
label = label.from;
}
route.add(a);
Collections.reverse(route);
for(int i =0;i<route.size();i++){
System.out.println(route.get(i).name);
}
}
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;
}
}
In this code I want to search in an ArrayList but my code returns an incorrect result and I can not resolve this problem.
ReceivedItemStructure structure:
public class ReceivedItemStructure {
public String mLastID;
public String mUserID;
public String mSmsBody;
public String mMobileNumber;
public String mDate;
public String mSenderName;
public String mSmsNumber;
public String mContactName;
public String getmLastID() {
return mLastID;
}
}
My Code:
int countSMS = 0;
String smsReceivedSender = "";
String r = new JsonService(config_username, config_password, 0, 20, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mId = json_obj.getString("id_recived_sms");
for (ReceivedItemStructure rf:items){
if( ! mId.equals(rf.getmLastID()) ) {
countSMS++;
}
}
}
My problem is this line :
if( ! mId.equals(rf.getmLastID()) ) {
if mId = 2000 and rf.getmLastID() = 1000 then count must be ++
Loop through your list and do a contains or startswith.
ArrayList<String> resList = new ArrayList<String>();
String searchString = "man";
for (String curVal : list){
if (curVal.contains(searchString)){
resList.add(curVal);
}
}
You can wrap that in a method. The contains checks if its in the list. You could also go for startswith.
Ok so to clarify please try to debug your code like this:
int countSMS = 0;
String TAG = "Debugger";
String smsReceivedSender = "";
String r = new JsonService(config_username, config_password, 0, 20, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
Log.i(TAG, "items size is " + items.size());
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mId = json_obj.getString("id_recived_sms");
Log.i(TAG, "Trying to compare " + mId);
for (ReceivedItemStructure rf:items){
Log.i(TAG, "iteration step of " + rf.getmLastID);
if( ! mId.equals(rf.getmLastID()) ) {
countSMS++;
Log.i(TAG, "they are equal, count is " + countSMS);
}
}
}
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;
}
}