Java search algorithm for Matrix Fit for available space - java

I have space matrix like
|....
..|..
.....
||...
where . is empty space and | is non empty space.
and i have 3 shape like
TTT E.E ..L
..E L.L
EEE
. also empty. Now i want to fit these shape in space matrix using java code.
expected out space look like
|.ELE
.L|LE
..EEE
||TTT
may be other possibility of fit
Input File code "problem1.txt"
SPACE
|.......
..|||..|
..|.|...
........
SHAPE T
TTTT
SHAPE e
..e
eee
SHAPE t
.t.
ttt
SHAPE r
rr
rr
SHAPE i
i..
iii
SHAPE s
.ss
ss.
Here my code to read file in array
File f = new File("problem1.txt");
FileReader fr = new FileReader(f);
int pos = 0;
Scanner s = new Scanner(fr);
// space class
SpaceClass space = new SpaceClass();
List<Shapeclass> shapeClasses = new ArrayList<Shapeclass>();
Shapeclass shapeClass = null;
boolean spaceStated = false;
while(s.hasNext()) {
//read trim line
String line = s.nextLine().trim();
if("".equals(line)){
continue;
}
//CHECK For Space
if("SPACE".equals(line.trim().toUpperCase())) {
pos = -1;
spaceStated=true;
continue;
}
//check for space
if(line.trim().toUpperCase().startsWith("SHAPE")) {
pos = -1;
spaceStated=false;
shapeClass = new Shapeclass();
shapeClasses.add(shapeClass);
continue;
}
pos++;
//adding for space
if(spaceStated) {
space.addRow(pos, line);
}else{
//adding for shape
shapeClass.addRow(pos, line);
}
}
SpaceClass Look like
public class SpaceClass{
private int height=0;
private int width=0;
private char[][] s = new char[50][50];
public SpaceClass() {}
public void addRow(int rowNo, String row) throws Exception {
if(this.width > 0 && this.width != row.length()) {
throw new Exception("Invalid Input for SPACE at row : " + rowNo + " and row :- " + row);
} else {
char[] ch = row.toCharArray();
for(int i=0,j=ch.length;i<j;i++) {
s[rowNo][i] = ch[i];
}
this.width = ch.length;
this.height += 1;
}
}
}
And ShapeClass Look like
public class Shapeclass{
private int height;
private int width;
private char[][] s = new char[50][50];
int rotate=0;
public void addRow(int rowNo, String row) throws Exception {
if(this.width > 0 && this.width != row.length()) {
throw new Exception("Invalid Input for SPACE at row : " + rowNo + " and row :- " + row);
} else {
char[] ch = row.toCharArray();
for(int i=0,j=ch.length;i<j;i++) {
s[rowNo][i] = ch[i];
}
this.width = ch.length;
this.height += 1;
}
}
}
Now i want new Space class with Fit all Shape

Related

How do I make a Class return a sting that is the size of the object dictated in the file?

Problem:
I'm trying to make a rectangle using strings that would look like this
===
| |
| |
| |
| |
===
So far I've tried this text I want to appear in the console when I tell the program the width and height of the rectangle that I am able to get a rectangle like seen above. Is there an easier was to do this I'm still learning how to use Java. I'm more failure with javascripting.
File: RectangleTester.java
public class RectangleTester extends ConsoleProgram
{
public void run()
{
// Create a new rectangle with a width of 10 and a height of 3
Rectangle rect = new Rectangle(10, 3);
// Print out information about the rectangle
System.out.println(rect);
// Print out the area of the rectangle
System.out.println("The area of the rectangle is " + rect.getArea());
// Print out the height of the rectangle
System.out.println("The height of the rectangle is " + rect.getHeight());
}
}
File: Rectangle.java
public class Rectangle
{
private int width;
private int height;
public String toString()
{
return makeTops() + makeSides() + makeTops();
}
public String makeTop()
{
String tops = "==";
for (int i = 0; i < width; i++){
tops += tops;
}
return tops;
}
private String makeSides(){
String sideSpace = sides + (space += space* (int)tops) + sides;
String sides = "||";
String space = " ";
for (int i = 0; i <= height; i++){
sideSpace += sideSpace;
}
return sideSpace;
}
}
So, makeTops is undefined...
public String toString()
{
return makeTops() + makeSides() + makeTops();
}
You need to change makeTop to makeTops...
public String makeTops() { ... }
I have no idea of what's going on here...
private String makeSides() {
String sideSpace = sides + (space += space * (int) tops) + sides;
String sides = "||";
String space = " ";
for (int i = 0; i <= height; i++) {
sideSpace += sideSpace;
}
return sideSpace;
}
You're trying to make use of variables which are not yet defined and you can't multiple a String, it doesn't make sense.
However, you can repeat a String...
private String makeSides() {
String sides = "||";
String space = " ";
String line = sides + (space.repeat(width - (sides.length() * 2))) + sides;
return (line + "\n").repeat(height - 2);
}
which also suggests you should change makeTops as well...
public String makeTops() {
return "=".repeat(width) + "\n";
}
Runnable example
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
Rectangle rect = new Rectangle(10, 3);
// Print out information about the rectangle
System.out.println(rect);
}
public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public String toString() {
return makeTops() + makeSides() + makeTops();
}
public String makeTops() {
return "=".repeat(width) + "\n";
}
private String makeSides() {
String sides = "||";
String space = " ";
String line = sides + (space.repeat(width - (sides.length() * 2))) + sides;
return (line + "\n").repeat(height - 2);
}
}
}
Some, the above example will print...
==========
|| ||
==========
Now, before you tell me that's not 10x3, it is, it's 10 columns, but 3 rows.
Now, if you wanted to display the "internal" area as the rectangle instead, you should change it to...
public class Rectangle {
private static String SIDE = "||";
private static String TOP = "=";
private static String SPACE = " ";
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public String toString() {
return makeTops() + makeSides() + makeTops();
}
public String makeTops() {
return TOP.repeat(width + (SIDE.length() * 2)) + "\n";
}
private String makeSides() {
String line = SIDE + (SPACE.repeat(width)) + SIDE;
return (line + "\n").repeat(height);
}
}
which will print...
==============
|| ||
|| ||
|| ||
==============

JAVA Question: Index 130 out of bounds for length 130 [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am running the following code and I keep getting the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 130 out of bounds for length 130
at Datachange.init(Datachange.java:55)
at Datachange.main(Datachange.java:38)
I am trying to read a file and manipulated into an output and its seems that its not reading the file well.
'
import java.io.*;
public class Datachange
{
public class variables
{
private char [] body;
private int ID;
private int population;
private int populationchilds;
private int populationchildspoverty;
private double populationchildpovertypercent;
variables(char [] input)
{
body = input;
char[] stateID = java.util.Arrays.copyOfRange(body,0,2);
ID = Integer.parseInt(new String(stateID).trim());
char[] totalpopulation = java.util.Arrays.copyOfRange(body,83,90);
population = Integer.parseInt(new String(totalpopulation).trim());
char [] childpopulation = java.util.Arrays.copyOfRange(body,92,99);
populationchilds = Integer.parseInt(new String(childpopulation).trim());
char [] povertychilds = java.util.Arrays.copyOfRange(body,101,108);
populationchildspoverty = Integer.parseInt(new String(povertychilds).trim());
}
}
public static void main(String[] args)
{
Datachange DS = new Datachange();
DS.init();
}
public void init()
{
variables dataframe[] = new variables[13286];
try (FileReader inputDataframe = new FileReader("file.txt"))
{
int c;
int i = 0;
int j = 0;
char variableinput [] = new char[130];
while((c = inputDataframe.read())!=-1)
{
variableinput[i] = (char) c;
i++;
if(c==10)
{
dataframe[j] = new variables(variableinput);
j++;
i = 0;
}
}
}
catch(IOException except)
{
System.out.println("There is Input/Output Error:" + except.getMessage());
}
this.newdata(dataframe);
}
public variables[] newdata(variables[] dataset)
{
variables[] newdata=new variables[57];
try (BufferedWriter outData = new BufferedWriter(new
FileWriter("manipulatedfile.txt")))
{
int stateID = 1; //First ID
int statePop= 0;
int stateChdPop=0;
int stateChdPovertyPop=0;
for(int i=0;i<dataset.length;i++)
{
if (dataset[i].ID == stateID)
{
statePop += dataset[i].population;
stateChdPop += dataset[i].populationchilds;
stateChdPovertyPop += dataset[i].populationchildspoverty;
}
else
{
double stateChdPovertyPopPercent=0;
if (stateChdPop != 0)
{
stateChdPovertyPopPercent = (double)
stateChdPovertyPop/stateChdPop * 100;
int z = 12;
}
else
{
stateChdPovertyPopPercent = 0;
}
outData.append(stateID + "\t" + statePop + "\t" +
stateChdPop + "\t" + stateChdPovertyPop+
"\t" + stateChdPovertyPopPercent + "\n");
statePop = 0;
stateChdPop = 0;
stateChdPovertyPop = 0;
i--;
stateID++;
}
}
}
catch(IOException except)
{
System.out.println("I/O Error:" + except.getMessage());
}
int x = 12;
return newdata;
}
}
'
It is reading the file just fine, otherwise it would throw an IOException instead of an ArrayIndexOutOfBoundsException.
From the Oracle Documentation about ArrayIndexOutOfBoundsException:
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
That happens in your init() method if I am not mistaken. You have an array that has a limit of 130 and trying to get the element at index 130+ (because arrays start counting at 0) will give you that exception.
variableinput[130] will throw it.

Trying to add an enum into a 2D array properly

So I am trying to add a cellType into a 2D array. The input from the file looks like a 6x6 file where it can be any combination of the enum type in my enum class below. For some reason when I try to troubleshoot the program, only WALL is getting added into my 2D array. I'm thinking there might be an error in my where I am trying to iterate through the 2D array, but I can't see it.
Here is where I am trying to add it within my 2D array
MazeCell.CellType[][] cell;
int rows = 6;
int cols = 6;
MazeCell.CellType cell2Add;
while(inputFile.hasNext())
{
String mazeStart = inputFile.nextLine().trim();
String [] mazeRowsAndCols = mazeStart.split(" ");
//System.out.println(mazeStart);
//System.out.println(mazeRowsAndCols[2]);
MazeCell.CellType cell2Add;
for(int r = 1; r < rows+1; r++)
{
System.out.print(r-1);
for(int c = 1; c<cols+1; c++)
{
if(mazeRowsAndCols[r-1].equals("W"))
{
cell2Add = MazeCell.CellType.WALL;
}
else if(mazeRowsAndCols[r-1].equals("M"))
{
cell2Add = MazeCell.CellType.START;
}
else if (mazeRowsAndCols[r-1].equals("C"))
{
cell2Add = MazeCell.CellType.END;
}
else if (mazeRowsAndCols[r-1].equals("O"))
{
cell2Add = MazeCell.CellType.OPEN;
}
else if (mazeRowsAndCols[r-1].equals(" "))
{
cell2Add = MazeCell.CellType.CURRENT_PATH;
}
else if (mazeRowsAndCols[r-1].equals("S"))
{
cell2Add = MazeCell.CellType.END_FOUND;
}
else if (mazeRowsAndCols[r-1].equals("X"))
{
cell2Add = MazeCell.CellType.REJECTED;
}
System.out.print(c);
cell[r-1][c-1] = cell2Add;
}
System.out.println();
}
}
}
inputFile.close()
Here is my enum class.
public class MazeCell
{
public static enum CellType
{
WALL("W"), START("M"), END("C"), OPEN("O"), CURRENT_PATH(" "), END_FOUND("S"), REJECTED("X");
private final String display;
private String type;
CellType(String display)
{
this.display = display;
}
public String getDisplay() { return display;}
public void setType(String type){this.type = type;}
};
What the input file looks like:
W W W W W W
W W M W W W
W W O O O W
W O W O O W
W W C O O W
W W W W W W W
W W W W W W
within cel[][] all I seem to be getting is Wall,
(mazeRowsAndCols[r-1].equals("S"))
you are using OUTER index to iterate over INNER elements (input line length). Try
(mazeRowsAndCols[c-1].equals("S"))
Moreover I would rather use switch for that (yes it is possible with string).
Besides I don't like the fact that you have outer for as this should be limited by input lines so while should be more then enough.
So in fact it should be something like that:
int row=0;
while(input.hasNext()){
String line=input.nextLine();
String parts[]=input.split(" ");
for(int c=0;c<parts.length;c++){
element=parts[c];
switch(element){
case W: enumToAdd=WALL; break;
case ......
///////////do the magic with `switch` here
}
maze[r][c]=enumToAdd;
}
row++;
}
public static CellType[][] read(Scanner scan) {
final int totalRows = 6;
final int totalColumns = 6;
CellType[][] maze = new CellType[totalRows][totalColumns];
for (int row = 0; row < totalRows; row++) {
String line = scan.nextLine();
for (int col = 0; col < totalColumns; col++)
maze[row][col] = CellType.parseId(line.charAt(col));
}
return maze;
}
public enum CellType {
WALL('W'),
START('M'),
END('C'),
OPEN('O'),
CURRENT_PATH(' '),
END_FOUND('S'),
REJECTED('X');
private final char id;
CellType(char id) {
this.id = id;
}
public static CellType parseId(char id) {
for (CellType type : values())
if (type.id == id)
return type;
throw new EnumConstantNotPresentException(CellType.class, String.valueOf(id));
}
}
I would suggest a few changes to make this a little easier to reason about.
First, let's fix up cell type a little to make it easier to use:
We should add a static fromDisplay(String s) method.
We should probably remove setType, because any call to setType will set that variable for that enum value everwhere, as there is only ever one instance of an enum value.
The resultant code is
public class MazeCell
{
public static enum CellType
{
WALL("W"),
START("M"),
END("C"),
OPEN("O"),
CURRENT_PATH(" "),
END_FOUND("S"),
REJECTED("X");
static {
final Map<String, CellType> fDisplay = new HashMap<>();
for(final CellType c : CellType.values()) {
fDisplay.put(c.display, c);
}
fromDisplay = fDisplay;
}
private static final Map<String, CellType> fromDisplay;
private final String display;
CellType(String display)
{
this.display = display;
}
public String getDisplay() { return display; }
public static CellType fromDisplay(final String display) {
return fromDisplay.getOrDefault(display, REJECTED);
}
}
}
Now, let's fix up the code. The problem is, as pointed out, that you only parse the first line every time. Let's fix that and clean up the code a little, too.
// Read our input in a try-with-resources
try(final File file = ...) {
final Scanner input = new Scanner(file);
// initialize the array
final MazeCell.CellType[][] cells = new MazeCell.CellType[6][6];
// assuming there are 6 rows
for(int r=0; r<6; r++) {
if(!input.hasNext()) throw new RuntimeException("Input file does not match our expectations! Only " + (r) + " lines!");
// assuming the columns are separated by spaces
final String[] cols = input.nextLine().trim().split(" ");
if(cols.length != 6) throw new RuntimeException("Input file does not match our expectations! Row " + (r + 1) + " had " + cols.length + " columns!");
for(int c=0; c<6; c++) {
cells[r][c] = MazeCell.CellType.fromDisplay(cols[c]);
}
}
// print it out or whatever
Arrays.stream(cells).map(Arrays::toString).forEach(System.out::println);
}
That should do it. Hope this helps!

How to load/create a level/room from a text file in java?

Basically each room has a size of 10 by 10, the "W" represents the Walls, and the blank spaces -" " represent the Floor, and the numbers are Doors.I figured the best way to create the room is to create a method that receives a file and reads it and put its "information" into a String[10][10], and then create another method(or just do it in my Main) that receives the String[10][10] created and creates the room(adds the images to the room), but i am having some difficulties reading the file so if you guys could help me with that part i would be thankful.
Here is the type of text files from which i want to create my room:
WWWW0WWWWW
W W
W W
W W
W W
W WW
W WW
W WW
W W1
WWWWWWWWWW
Here are the Door, Wall and Floor classes:
public class Door implements ImageTile {
private Position position;
public Door(Position position) {
this.position = position;
}
#Override
public String getName() {
return "Door";
}
#Override
public Position getPosition() {
return position;
}
}
public class Floor implements ImageTile {
private Position position;
public Floor(Position position) {
this.position = position;
}
#Override
public String getName() {
return "Floor";
}
#Override
public Position getPosition() {
return position;
}
}
public class Wall implements ImageTile {
private Position position;
public Wall(Position position) {
this.position = position;
}
#Override
public String getName() {
return "Wall";
}
#Override
public Position getPosition() {
return position;
}
}
And this is my method for adding images to my frame:
public void newImages(final List<ImageTile> newImages) {
if (newImages == null)
return;
if (newImages.size() == 0)
return;
for (ImageTile i : newImages) {
if (!imageDB.containsKey(i.getName())) {
throw new IllegalArgumentException("No such image in DB " + i.getName());
}
}
images.addAll(newImages);
frame.repaint();
}
If you guys could help me i would appreciate it very much, thanks guys.Her is what i have now:
public class Room {
private String[][]room;
public Room(){
room = new String[10][10]; }
public static Room fromFile(File file){
if(file.exists()){
Scanner sc = null;
Room room = new Room();
try {
sc = new Scanner(file);
while(sc.hasNextLine()){
if(sc.nextLine().startsWith("#"))
sc.nextLine();
else{
String[] s0 = sc.nextLine().split("");
//Here is where my trouble is, i dont know how to add the content of this String s0 to the String s
if(s0.length==10){
for(int x = 0; x < 10; x++){
for(int y = 0; y < 10; y++){
String[x][y] s= String[x] s0;
}
}
} catch (FileNotFoundException e) {
System.out.println("Ficheiro "+file.getAbsolutePath()+
" não existe. "); }
finally{
if(sc!=null)sc.close();
}
}
else
System.out.println("Ficheiro "+file.getAbsolutePath()+
" não existe. ");
return null;
}
Each call to sc.nextLine() is reading another line from your file. You need to save the line into a temporary variable, and then refer to that temporary.
Maintain a counter of lines you've processed, so you can fill in the appropriate line in your s[][] matrix.
You only need to allocate storage for the 10 rows, since splitting the line you read in will result in an array of strings (the columns in one row) being allocated for you.
int row = 0;
String[][] s = new String[10][];
while(sc.hasNextLine() && i < 10) {
String line = sc.nextLine();
if( !line.startsWith("#")) {
String[] s0 = sc.line.split("");
s[row] = s0;
row++;
}
}
BTW, Use String[][] is overkill; since each string will only hold one character. Perhaps you could consider using char[][]. And line.toCharArray() would split the line into a char[] for you.
EDIT: (Due to edit of your question's code)
Instead of:
if(s0.length==10){
for(int x = 0; x < 10; x++){
for(int y = 0; y < 10; y++){
String[x][y] s= String[x] s0;
}
}
}
you want:
if(s0.length==10){
for(int y = 0; y < 10; y++){
s[row][y] = s0[y];
}
row++;
}
With row being the row counter in my above code.

Client and Object Class outputting values

I have an object and client class created which prints coordinates in order of their distance from the origin. The client class asks the user how many dimensions they want the array to have (x,y or x,y,z) how many points they want generated, and a range from which each coordinate will run from (ex. -x to x, -y to y etc.). When I run the program it prints out the correct number of points, but there is always one extra element in the array (etc. when user enters dimension of array as '4', it always prints out one extra element -> [4, 5, 9, 6, 1]). Why is this happening?
Client Class
import java.io.*;
public class MA {
public MA() { }
public static void main(String args[]) throws IOException {
String myString = "arrayNumPoints.txt";
int numpoints = 0;
int dimension = 0;
double lengthscale = 0;
double [][] points = new double[numpoints][dimension + 1];
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
MB pointsB = new MB();
System.out.println("Enter number of points:");
String numpointsA = myInput.readLine();
numpoints = Integer.parseInt(numpointsA);
pointsB.setnumpoints(numpoints);
System.out.println("Enter the dimension:");
String dimensionA = myInput.readLine();
dimension = Integer.parseInt(dimensionA);
pointsB.setdim(dimension);
System.out.println("Enter length(range):");
String lengthscaleA = myInput.readLine();
lengthscale = Double.parseDouble(lengthscaleA);
pointsB.setlengthscale(lengthscale);
pointsB = new MB(numpoints, lengthscale, dimension, points);
pointsB.fillarray(pointsB.getarray(), pointsB.getlengthscale(), pointsB.getdim(), pointsB.getnumpoints());
pointsB.caldistance(pointsB.getarray(), pointsB.getnumpoints(), pointsB.getdim());
pointsB.sort(pointsB.getarray(), 0, pointsB.getnumpoints()-1, pointsB.getdim());
pointsB.writefile(pointsB.getarray(), pointsB.getnumpoints(), myString);
pointsB.readfile(myString);
}
}
Object Class
import java.io.*;
import java.util.Arrays;
public class MB {
//variables and arrays are declared
private double lengthscale;
private int numpoints;
private int dimension;
private double [][] points;
//constructor
public MB() { }
//constructor
public MB(double [][] points) {
numpoints = 0;
lengthscale = 0;
dimension = 0;
points = new double[numpoints][dimension + 1];
}
//constructor
public MB(int mynumpoints, double mylengthscale, int mydimension, double [][] mypoints) {
numpoints = mynumpoints;
lengthscale = mylengthscale;
dimension = mydimension;
points = new double[numpoints][dimension + 1];
}
//numpoints getter
public int getnumpoints()
{
return numpoints;
}
//numpoints setter
public void setnumpoints(int mynumpoints) {
numpoints = mynumpoints;
}
//lengthscale getter
public double getlengthscale() {
return lengthscale;
}
//lengthscale setter
public void setlengthscale(double mylengthscale) {
lengthscale = mylengthscale;
}
//dimension getter
public int getdim() {
return dimension;
}
//dimension setter
public void setdim(int mydimension) {
dimension = mydimension;
}
//array getter
public double[][] getarray() {
return points;
}
//array setter
public void setarray(double [][]mypoints, int numpoints, int dimension) {
points[numpoints][dimension] = mypoints[numpoints][dimension];
}
//fill array method
public void fillarray(double [][]mypoints, double mylengthscale, int mydimension, int mynumpoints) throws IOException {
for(int x = 0; x < mynumpoints; x++)
{
for(int y = 0; y < mydimension; y++) {
//fills array with random points within the specified range
mypoints[x][y] = (dimension * Math.random() - 1) * mylengthscale;
}//end for
}//end for
}
//writefile method
public void writefile(double [][]mypoints, int mynumpoints, String myString) throws IOException {
//writes to myString
PrintWriter fileOut = new PrintWriter(new FileWriter(myString));
//for loop runs for length of mylengthscale
for(int m = 0; m < mynumpoints; m++) {
//prints points to file
fileOut.println(Arrays.toString(mypoints[m]));
}
//close file
fileOut.close();
//end for
}
//readfile metod
public void readfile(String myString) throws IOException
{
String filePath = myString;
//reads data from mString
BufferedReader in = new BufferedReader(new FileReader(new File(myString)));
String line = null;
while(( (line = in.readLine()) != null))
System.out.println(line);
in.close();
}
//caldistance method
public void caldistance(double [][]mypoints, int mynumpoints, int mydimension) {
//for loop; calculates distance for specified number of points
for(int i = 0; i < mynumpoints; i++) {
for(int k = 0; k < mydimension; k++) {
mypoints[i][mydimension] = mypoints[i][k] * mypoints[i][k];
}//end for loop
mypoints[i][mydimension] = Math.sqrt(mypoints[i][mydimension]);
}//end for loop
}
//sort method
public double[][] sort(double[][] mynewpoints, int down, int top, int mydimension) {
System.arraycopy(mynewpoints, 0, mynewpoints, 0, mynewpoints.length);
//variables are declared
int d = down;
int u = top;
//determines pivot point
double [] pivot = mynewpoints[(down + top)/2];
//sorts the values of the array, comparing it to the pivot
do {
while (mynewpoints[d][mydimension] < pivot[mydimension]) {
d++;
}
while (mynewpoints[u][mydimension] > pivot[mydimension]) {
u--;
}
if (d <= u) {
double[] temporary = new double[mynewpoints[d].length];
//compres values in array and switches them
for (int y = 0; y < mynewpoints[d].length; y++) {
temporary[y] = mynewpoints[d][y];
mynewpoints[d][y] = mynewpoints[u][y];
mynewpoints[u][y] = temporary[y];
}
d++;
u--;
}
} while (d <= u);
if (down < u) {
mynewpoints = sort(mynewpoints, mydimension, down, u);
}
if (d < top) {
mynewpoints = sort(mynewpoints, mydimension, d, top);
}
return mynewpoints;
}
}
You should be more specific (show us the code fragments, which you use and which go wrong).
However do you realize, that in your MB constructor :
//constructor
public MB(double [][] points) {
numpoints = 0;
lengthscale = 0;
dimension = 0;
points = new double[numpoints][dimension + 1];
}
The last line is not doing anything? You have to write it like this :
this.points = new double[numpoints][dimension + 1];
Because you have two variables points, one is class variable, second is passed as parameter. If this happens, without using this the non-class variable is chosen.
Probably because you're adding 1 to the dimension given by the user:
points = new double[numpoints][dimension + 1];
This results in the array having one more column than value of dimension.

Categories

Resources