word search in java 2d array - java

I am trying to create a simple word search for a class assignment, and I have managed to figure out how to search east (from left to right) and west(right to left). But I am having trouble trying to figure out how to search south (top to bottom).
The code that I have works for one file that I read in but the second file returns an ArrayIndexOutOfBoundsException. Is there anything that is specific in my code that would make it un-scalable?
My corrected code looks like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import wordSeek.GameBoard;
public class WordGame {
private char[][] letters;
GameBoard gb;
public static void main(String[] args) {
WordGame wg = new WordGame();
wg.play();
}
public WordGame() {
letters = readLettersFromFile();
gb = new GameBoard(letters);
}
private void play() {
Scanner s = new Scanner(System.in);
String word;
do {
System.out.println("Enter word to find: ");
word = s.next();
// reset all highlighted tiles
gb.reset();
search(word);
} while (!word.equals("QUIT"));
gb.dispose();
}
// Nothing to be done above
// Complete all the methods below
private char[][] readLettersFromFile() {
// From the data in the file Letters.txt determine the size (number of
// rows and number of columns) for the letters array
int rowCount = 0;
int colCount = 0;
char c;
File file = new File("resources/Places.txt");
Scanner fileScanner = null;
try {
fileScanner = new Scanner(file);
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<String> data = new ArrayList<String>();
while(fileScanner.hasNextLine())
{
String line = fileScanner.nextLine();
data.add(line);
}
fileScanner.close();
rowCount = data.size();
colCount = data.get(0).trim().length()/2+1;
// Instantiate a two dimensional array of characters of the appropriate
// size
letters = new char [rowCount][colCount];
// Populate the array with the letters in Letters.txt
for (int i = 0; i < rowCount; i++) {
String line = data.get(i);
int pos = 0;
for (int j = 0; j < colCount; j++) {
letters[i][j] = line.charAt(pos);
pos += 2;
}
}
// return the array
return letters;
}
private void search(String word) {
System.out.println("Searching for " + word);
//Call the other search methods below as needed
searchIterativeEast(word);
searchIterativeWest(word);
searchIterativeSouth(word);
searchIterativeNorth(word);
}
//The following four methods must employ ITERATION to search the game board
private boolean searchIterativeEast(String word) {
int k = 0;
for (int i = 0; i < letters.length; i++)
{
for (int j = 0; j < letters[i].length; j++) {
if (word.charAt(k) == letters[i][j]) {
k++;
}
else {
k = 0;
}
if (k == word.length()) {
for (int col = j - k + 1; col <= j; col++) {
gb.highlight(i, col);
}
return true;
}
}
}
return false;
}
private boolean searchIterativeWest(String word) {
String reversedWord = "";
for (int i = word.length() - 1; i != -1; i--)
{
reversedWord += word.charAt(i);
}
int k = 0;
for (int i = 0; i < letters.length; i++)
{
for (int j = 0; j < letters[i].length; j++) {
if (reversedWord.charAt(k) == letters[i][j]) {
k++;
}
else {
k = 0;
}
if (k == reversedWord.length()) {
for (int col = j - k + 1; col <= j; col++) {
gb.highlight(i, col);
}
return true;
}
}
}
return false;
}
private boolean searchIterativeSouth(String word) {
int k = 0;
int store = letters[0].length;
for (int j = 0; j < letters[store].length; j++)
{
for (int i = 0; i < letters.length; i++)
{
if (word.charAt(k) == letters[i][j])
{
k++;
}
else
{
k = 0;
}
if (k == word.length())
{
for(int row = i-k+1 ; row <= i; row++)
{
gb.highlight(row, j);
}
return true;
}
}
}
return false;
}
private boolean searchIterativeNorth(String word) {
String reversedWord = "";
for (int i = word.length() - 1; i != -1; i--)
{
reversedWord += word.charAt(i);
}
int k = 0;
int store = 0;
for(int i = 0; i < letters.length; i++)
{
store = letters[i].length;
}
for (int j = 0; j < letters[store].length; j++)
{
for (int i = 0; i < letters.length; i++)
{
if (reversedWord.charAt(k) == letters[i][j])
{
k++;
}
else
{
k = 0;
}
if (k == reversedWord.length())
{
for(int row = i-k+1 ; row <= i; row++)
{
gb.highlight(row, j);
}
return true;
}
}
}
return false;
}
The Gameboard for the first file (Animals.txt) looks like: 5X4 2d Array
X C A T
P A L Q
I R B U
G P X N
G O D W
Output highlights CARP.
The Gameboard for the second file (Places.txt) looks like: 11x15 2d Array
O M J G D A X V C S Q N K I F
D A X V T Q O M J H A A H F C
A Y W U R P N L F E I T A L Y
J N H N E T H E R L A N D S F
D B I Z X V T O A R Q O A Y K
M K I A H F K R N O D B N N I
N Z Y W P H T V C G C T A A N
R A Q O T S N L E K K I C M G
I H P U U F D C A Z D O X R D
X W O A L E U Z E N E V N E O
V S U S J R Q L I Z A R B G M

The return statement goes outside of the for loop, otherwise you will only highlight the first letter.
...
for (int row = j-k+1; row <=i; row++ )
{
//gb.highlight() just calls a method that highlights the letters.
gb.highlight(row, j);
//return true;
}
return true;
...

for (int j = 0; j < letters[i].length; j++)
instead of
for (int j = 0; j < letters.length; j++)

Related

How to implement Lazy Constraint Callbacks in CPLEX (java API)

currently I am trying to implement a CPLEX exact solution for the Asymmetric Capacitated Vehicle Routing Problem with the MTZ sub-tour elimination constraints.
My problems occurs when I try to implement Lazy Constraint Callbacks. More specifically I get a null pointer exception. There are almost no tutorials for implementing callbacks, so your help will be deeply appreciated.
This is my code:
CVRP class
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import ilog.concert.*;
import ilog.cplex.*;
public class ACVRP {
// euclidean distance method
public static double distance(int x1, int y1, int x2, int y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
public static void solveModel() {
int n = 32; // number of customers
int k = 5; // number of vehicles
int c = 100; // capacity of vehicles
int datacoords[][] = new int[n][2];
double[][] node = new double[n][n]; // dissimilarity matrix
int[] demand = new int[n]; // demand of every customer
try {
// load matrixes
FileReader frd = new FileReader("demands.txt");
FileReader frcoords = new FileReader("coords.txt");
BufferedReader brd = new BufferedReader(frd);
BufferedReader brcoords = new BufferedReader(frcoords);
String str;
int counter = 0;
while ((str = brd.readLine()) != null) {
String[] splitStr = str.trim().split("\\s+");
demand[counter] = Integer.parseInt(splitStr[1]);
counter++;
}
counter = 0;
while ((str = brcoords.readLine()) != null) {
String[] splitStr = str.trim().split("\\s+");
datacoords[counter][0] = Integer.parseInt(splitStr[1]);
datacoords[counter][1] = Integer.parseInt(splitStr[2]);
counter++;
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
node[i][j] = distance(datacoords[i][0],datacoords[i][1],datacoords[j][0],datacoords[j][1]);
// if (i == j ){
// node[i][j] = 99999999;
// }
}
}
brd.close();
brcoords.close();
IloCplex cplex = new IloCplex();
// variables
IloIntVar[][] x = new IloIntVar[n][];
for (int i = 0; i < n; i++) {
x[i] = cplex.boolVarArray(n);
for (int j = 0; j < n; j++) {
x[i][j].setName("x." + i + "." + j );
}
}
// mtz variables
IloNumVar[] u = cplex.numVarArray(n, 0, Double.MAX_VALUE);
for (int j = 0; j < n; j++) {
u[j].setName("u." + j);
}
//objective
IloLinearNumExpr conObj = cplex.linearNumExpr();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ( i != j ){
conObj.addTerm(node[i][j], x[i][j]) ;
}
}
}
cplex.addMinimize(conObj);
// constraints
for (int i = 1; i < n; i++) {
IloLinearNumExpr equation1 = cplex.linearNumExpr();
for (int j = 0; j < n; j++) {
if (i!=j) {
equation1.addTerm(1.0, x[i][j]);
}
}
cplex.addEq(equation1, 1.0);
}
for (int j = 1; j < n; j++) {
IloLinearNumExpr equation2 = cplex.linearNumExpr();
for (int i = 0; i < n; i++) {
if (i!=j) {
equation2.addTerm(1.0, x[i][j]);
}
}
cplex.addEq(equation2, 1.0);
}
IloLinearNumExpr equation3 = cplex.linearNumExpr();
for (int i = 1; i < n; i++) {
equation3.addTerm(1.0, x[i][0]);
}
cplex.addEq(equation3, k);
IloLinearNumExpr equation4 = cplex.linearNumExpr();
for (int j = 1; j < n; j++) {
equation4.addTerm(1.0, x[0][j]);
}
cplex.addEq(equation4, k);
cplex.use(new LazyContstraintMTZ(n, c, demand, x, u, cplex));
//parameters
//cplex.setParam(IloCplex.Param.TimeLimit,50);
//cplex.setParam(IloCplex.Param.Preprocessing.Reduce, 0);
// cplex.setParam(IloCplex.Param.RootAlgorithm, IloCplex.Algorithm.Primal);
// solve model
cplex.solve();
cplex.exportModel("model.lp");
System.out.println(cplex.getBestObjValue());
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j) {
if (cplex.getValue(x[i][j]) != 0) {
System.out.println("name: " + x[i][j].getName() + " value: " + cplex.getValue(x[i][j]));
}
}
}
}
// end
cplex.end();
} catch (IloException | NumberFormatException | IOException exc) {
exc.printStackTrace();
}
}
}
class for lazy constraint :
import ilog.concert.*;
import ilog.cplex.*;
public class LazyContstraintMTZ extends IloCplex.LazyConstraintCallback {
int n; // number of customers
int c; // capacity of vehicles
int[] demand; // demand of every customer
IloIntVar[][] x;
IloNumVar[] u;
IloCplex cplex;
IloRange[] rng;
//constructor
LazyContstraintMTZ(int n, int c, int[] demand, IloIntVar[][] x, IloNumVar[] u, IloCplex cplex){
this.n = n;
this.c = c;
this.demand = demand;
this.x = x;
this.u = u;
this.cplex = cplex;
}
protected void main() throws IloException {
// Get the current x solution
// double[][] sol = new double[n][n];
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < n; j++) {
// sol[i][j] = cplex.getValue(x[i][j]);
// }
// }
for (int i = 1; i < n; i++) {
for (int j = 1; j < n; j++) {
if (i!=j && demand[i]+demand[j]<=c){
IloLinearNumExpr equation5 = cplex.linearNumExpr();
equation5.addTerm(1.0, u[i]);
equation5.addTerm(-1.0, u[j]);
equation5.addTerm(c, x[i][j]);
rng[i].setExpr(equation5);
rng[i].setBounds(Double.MIN_VALUE, c-demand[j]);
cplex.addLazyConstraint(rng[i]);
}
}
}
for (int i = 1; i < n; i++) {
IloLinearNumExpr equation6 = cplex.linearNumExpr();
equation6.addTerm(1.0, u[i]);
rng[i].setExpr(equation6);
rng[i].setBounds(demand[i], c);
cplex.addLazyConstraint(rng[i]);
}
}
}
As far as I can tell, rng is never initialized in your callback class. So it is always null and as soon as you attempt to set an element in it, you will get that NullPointerException.
Note that you don't even need that array. Instead of
rng[i].setExpr(equation5);
rng[i].setBounds(Double.MIN_VALUE, c-demand[j]);
cplex.addLazyConstraint(rng[i]);
you can just write
IloRange rng = cplex.range(Double.MIN_VALUE, equation5, c - demand[j]);
cplex.addLazyConstraint(rng);
(and similarly for equation6).
Also note that Double.MIN_VALUE is likely not what you want. This gives the smallest representable number larger than 0. I guess what you want is Double.NEGATIVE_INFINITY to specify a range without lower bound. In that case you could also just write
IloRange rng = cplex.le(equation5, c - demand[j]);

How would fill this array in this form?

I want my program to output this in a certain way, how would I make this possible? So far, my code is giving me the wrong thing.
Here's my .txt file:
ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO
Here's my java file:
import java.io.*;
public class EncryptDecrypt {
public static void encrypt() throws IOException {
BufferedReader in = new BufferedReader(new FileReader("cryptographyTextFile.txt"));
String line = in.readLine();
char[][] table = new char[6][5];
// fill array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
while(table[i][j] < 6) {
table[i][j] = line.charAt(j);
}
}
}
// print array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
System.out.println(table[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) throws IOException {
encrypt();
}
}
How would I print this .txt file like so:
ABCDE
GHIJK
MNOPQ
STUVW
XYZOO
OOOOO
A couple of problems
see
String line = "ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO";
char[][] table = new char[6][5];
int counter = 0;
// fill array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
table[i][j] = line.charAt(counter++); // need to increment through the String
}
}
// print array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
System.out.print(table[i][j] + " "); // not println
}
System.out.println();
}
output
A B C D E
F G H I J
K L M N O
P Q R S T
U V W X Y
Z O O O O
Although a more extensible way would be link
String line = "ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO";
String lines [] = line.split("(?<=\\G.....)");
for (String l : lines) {
System.out.println(l);
}

Java 2D Array; Variable Row & Column Length from File Input

For this intro-level assignment, I have to set up a 2D multidimensional array from a file and from a double[][] a and apply several methods to them. For now, I'm mostly concerned with simply initializing the arrays. I'm trying to figure out a way to take a test file, read the first int as the number of rows, the first integer of each line as the number of columns per row, and each double as a member of the array.
public class MDArray
{
static int rowCount;
static int columnCount;
private static double[][] mdarray = new double[rowCount][columnCount];
public MDArray(double[][] a)
{
mdarray = a;
}
public MDArray(String file)
{
Scanner input = null;
try
{
input = new Scanner(new FileInputStream("ragged.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
System.exit(0);
}
while(input.hasNextDouble())
{
rowCount = input.nextInt();
for(int i = 0; i < rowCount; i++)
{
columnCount = input.nextInt();
for(int j = 0; j < columnCount; j++)
{
double value = input.nextDouble();
mdarray[i][j] = value;
}
}
}
}
public static boolean isRagged()
{
for(int i = 0; i < mdarray.length; i++)
{
int rowLength1 = mdarray.length;
for(int j = i + 1; j < mdarray.length; j++)
{
int rowLength2 = mdarray.length;
if(rowLength1 != rowLength2)
{
return true;
}
}
}
return false;
}
public static int getNumberOfRows()
{
int numRows = 0;
for(int i = 0; i < mdarray.length; i++)
{
numRows++;
}
return numRows;
}
public static int getNumberOfCols()
{
int numCols = 0;
for(int i = 0, j = i + 1; i < mdarray.length; i++)
{
for(int k = 0; k < mdarray[i].length; k++)
{
if(mdarray[i].length > mdarray[j].length)
{
numCols++;
}
}
}
return numCols;
}
public static double getValAt(int i, int j)
{
if(i > mdarray.length || j > mdarray[i].length)
{
double invalid = Double.NaN;
return invalid;
}
double valAt = mdarray[i][j];
return valAt;
}
public static void sort(boolean byColumn)
{
if(isRagged() == true)
{
System.out.println("Ragged arrays cannot be sorted by column.");
}
else{
for(int i = 0; i < mdarray.length; i++)
{
for(int j = 0; j < mdarray[i].length; j++)
{
for(int k = j + 1; k < mdarray[i].length; k++)
{
if(mdarray[i][j] < mdarray[i][k])
{
double temp = mdarray[i][j];
mdarray[i][k] = mdarray[i][j];
mdarray[i][j] = temp;
}
}
}
}
}
}
public static int hamming(boolean byColumn)
{
int hamVal = 0;
if(isRagged() == true)
{
System.out.println("Ragged arrays cannot be sorted by column.");
}
else{
for(int i = 0; i < mdarray.length; i++)
{
for(int j = 0; j < mdarray[i].length; j++)
{
for(int k = j + 1; k < mdarray[i].length; k++)
{
if(mdarray[i][j] < mdarray[i][k])
{
double temp = mdarray[i][j];
mdarray[i][k] = mdarray[i][j];
mdarray[i][j] = temp;
hamVal++;
}
}
}
}
}
return hamVal;
}
public static double[] max()
{
double[] maxVal = new double[mdarray.length];
for(int i = 0, j = i + 1; i < maxVal.length; i++)
{
for(int k = 0; k < mdarray[i].length; k++)
{
if(mdarray[i][k] > mdarray[j][k])
{
maxVal = mdarray[i];
}
}
}
return maxVal;
}
public String toString()
{
String arrayString = "";
for(int i = 0; i < mdarray.length; i++)
{
for(int j = 0; j < mdarray[i].length; j++)
{
arrayString += ", " + mdarray[i][j];
}
arrayString = arrayString + "/n";
}
return arrayString;
}
}
This was the file I was testing the MDArray(String file) with:
3
2 4.1 8.9
5 9.5 2.0 7.3 2.1 8.9
3 1.3 5.2 3.4
I think the problem is that the rowCount and columnCount integers are not initialized, but I'm not sure how to initialize them to a variable length with basic array skills. This is also affecting the other constructor as well. Being an intro-level course, I am not supposed to use more advanced techniques such as ArrayList. In addition, I can't verify if the methods are correct, since I don't have an array to test them with.
EDIT: While I did implement many of the suggestions in the answers, such as changing everything to non-static and other changes, I'm still getting a NullPointerException for the line mdarray[i][j] = input.nextDouble();. I assume it has to do with the private double[][] mdarray, which is required in the assignment specifications. Now I'm trying to find a way to initialize it such that it can be overridden in the later methods.
You have to initialize the array in your constructor, since that's when you know the dimensions :
public MDArray(String file)
{
Scanner input = null;
try {
input = new Scanner(new FileInputStream("ragged.txt"));
}
catch (FileNotFoundException e) {
System.out.println("File Not Found.");
System.exit(0);
}
rowCount = input.nextInt();
mdarray = new double[rowCount][]; // init the array
for(int i = 0; i < rowCount; i++) {
columnCount = input.nextInt();
mdarray[i] = new double[columnCount]; // init the current row
for(int j = 0; j < columnCount; j++) {
mdarray[i][j] = input.nextDouble();
}
}
}
You could initialize your arrays by putting the amount of rows and columns on the first 2 lines of your multidimensional array, if i had 10 rows and 12 columns i could do something like this:
public void arrayStuff() {
File fileToRead = new File("YOUR LINK HERE");
String[][] data;
try (BufferedReader reader = new BufferedReader(new FileReader(fileToRead))) {
String line;
data = new String[Integer.parseInt(reader.readLine())][Integer.parseInt(reader.readLine())];
while((line = reader.readLine()) != null) {
// read the rest here..
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am using an AutoCloseable (which is why the try is between these ()'s, but this is so that i don't have to close it afterwards.
Basically, first i read the amount of rows there are and then the amount of columns there are, so if i had this file:
10
12
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
It'd be able to read all of this, because the amount of rows and columns were defined in the file.
You don't use the fields rowCount and columnCount: you can remove them
The mdarray field should be non-static, so should be the methods that use them (if it was a utility class, you wouldn't have any constructor)
The arrays can be created while reading the file:
Scanner input = null;
try
{
input = new Scanner(new FileInputStream("ragged.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
System.exit(0);
}
int rowCount = input.nextInt();
mdarray = new double[rowCount][];
for(int i = 0; i < rowCount; i++)
{
int columnCount = input.nextInt();
mdarray[i] = new double[columnCount];
for(int j = 0; j < columnCount; j++)
{
double value = input.nextDouble();
mdarray[i][j] = value;
}
}
methods getNumberOfRows() and getNumberOfCols() count be much simpler:
public int getNumberOfRows()
{
return mdarray.length;
}
public int getNumberOfCols() {
int result = 0;
for (double[] col: mdarray) {
if (col.length > result) {
result = col.length;
}
}
return result;
}
In getValueAt(), the test is wrong; it should be:
if(i >= mdarray.length || j >= mdarray[i].length)

Finding the cofactor and determinant of a 3x3 matrix

In the code listed below I am able to correctly find the sum, multiplication, and transpose of a two matrices. I am unsure how to find the cofactor and determinant going along the same type of set up I have for the other matrices. Any help would be appreciated. Thanks!!
public class MatrixMult {
public MatrixMult(int first[][], int second[][], int m, int n, int p, int q) {
doMatrixMultiply(first, second, m, n, p, q);
}
public void doMatrixMultiply(int first[][], int second[][], int m, int n,
int p, int q) {
if (n != p)
System.out
.println("Matrices with entered orders can't be multiplied with each other.");
else {
int multiply[][] = new int[m][q];
int addition[][] = new int[m][q];
int transpose[][] = new int[m][q];
int transpose2[][] = new int[m][q];
int cofactor[][] = new int[m][q];
int mult = 0;
int sum = 0;
int tran = 0;
int co = 0;
for (int c = 0; c < m; c++) {
for (int d = 0; d < q; d++) {
for (int k = 0; k < p; k++) {
mult = mult + first[c][k] * second[k][d];
}
multiply[c][d] = mult;
mult = 0;
}
}
System.out.println("Product of entered matrices:-");
for (int c = 0; c < m; c++) {
for (int d = 0; d < q; d++)
System.out.print(multiply[c][d] + "\t");
System.out.print("\n");
}
for (int c = 0; c < m; c++) {
for (int d = 0; d < q; d++) {
for (int k = 0; k < p; k++) {
sum = first[c][d] + second[c][d];
}
addition[c][d] = sum;
sum = 0;
}
}
System.out.println("Sum of entered matrices:-");
for (int c = 0; c < m; c++) {
for (int d = 0; d < q; d++)
System.out.print(addition[c][d] + "\t");
System.out.print("\n");
}
int c;
int d;
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
transpose[d][c] = first[c][d];
}
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
transpose2[d][c] = second[c][d];
}
System.out.println("Transpose of first entered matrix:-");
for (c = 0; c < n; c++) {
for (d = 0; d < m; d++)
System.out.print(transpose[c][d] + "\t");
System.out.print("\n");
}
System.out.println("Transpose of second entered matrix:-");
for (c = 0; c < n; c++) {
for (d = 0; d < m; d++)
System.out.print(transpose2[c][d] + "\t");
System.out.print("\n");
}
}
}
}
Following is the implemenation of determinant using your structure for the matrix represantation using the code from the link Determining Cofactor Matrix in Java:
public int determinant(int[][] result, int rows, int cols) {
if (rows == 2)
return result[0][0] * result[1][1] - result[0][1] * result[1][0];
int determinant1 = 0, determinant2 = 0;
for (int i = 0; i < rows; i++) {
int temp = 1, temp2 = 1;
for (int j = 0; j < cols; j++) {
temp *= result[(i + j) % cols][j];
temp2 *= result[(i + j) % cols][rows - 1 - j];
}
determinant1 += temp;
determinant2 += temp2;
}
return determinant1 - determinant2;
}
and for calculating the cofactor also using the code from the provided link:
public int[][] cofactor(int[][] matrix, int rows, int cols) {
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = (int) (Math.pow(-1, i + j) * determinant(
removeRowCol(matrix, rows, cols, i, j), rows - 1,
cols - 1));
}
}
return result;
}
public int[][] removeRowCol(int[][] matrix, int rows, int cols,
int row, int col) {
int[][] result = new int[rows - 1][cols - 1];
int k = 0, l = 0;
for (int i = 0; i < rows; i++) {
if (i == row)
continue;
for (int j = 0; j < cols; j++) {
if (j == col)
continue;
result[l][k] = matrix[i][j];
k = (k + 1) % (rows - 1);
if (k == 0)
l++;
}
}
return result;
}
A simple Google search will find you a lot of examples. E.g. http://mrbool.com/how-to-use-java-for-performing-matrix-operations/26800

Scanner isn't working - Prime Sieve. Code is finished

I'm working on an arraylist implementation of PrimeSieve and I have all the code written but it seems to not run so I'm not sure if it's because the loops are bad or because I set up the scanner wrong.
Here's the code.
import java.util.Scanner;
import java.util.ArrayList;
public class PrimeSieve {
public static void main(String[] args)
{
int inputNum;
Scanner SL = new Scanner(System.in);
System.out.print("Pick a number to count up from:");
inputNum = SL.nextInt();
ArrayList<Boolean> BL = findPrime(inputNum);
System.out.println("The prime numbers found:");
for(int i = 0; i < inputNum; i++)
{
if(BL.get(i) == true)
{
System.out.println(i + ", ");
}
}
}
public static ArrayList<Boolean> findPrime(int maxNum)
{
ArrayList<Boolean> BL = new ArrayList<Boolean>();
//Filling in the list.
for(int i = 0; i < maxNum; i++)
{
BL.add(true);
}
for(int i = 0; i * i <(maxNum); i++)
{
if(BL.get(i) == true)
{
for(int k = i*2; k < maxNum; k = k + i)
{
BL.set(i, false);
}
}
}
return BL;
}
}
Once I input any number and press enter, nothing works. My assumption would be that the program is constantly looping somewhere and it has to be broken.
You have neverending for loop here:
for(int k = i*2; k < maxNum; k = k + i)
i is 0 and k is 0 so every step k=0+0
There is your problem:
for (int i = 0; i * i < (maxNum); i++) {
if (BL.get(i) == true) {
for (int k = i * 2; k < maxNum; k = k + i) {
BL.set(i, false);
}
}
}
First iteraction ( i = 0 ) :
for (int k = 0 * 2; k < maxNum; k = k + 0)
its like :
for (int k = 0 ; k < X ; k = k + 0 )
Fix it :)
About your problem ... it's easy guy ( use debug :) ):
for (int i = 2; i * i < (maxNum); i++) {
if (BL.get(i) == true) {
for (int k = i * 2; k < maxNum; k = k + i) {
BL.set(k, false);
}
}
}
Changes :
int i = 2;
and
BL.set(k,false);
You must learn it by yourself :(

Categories