How to fix this 2D array loop without going out of bounds - java
I have to write code that takes in 4 parameters (row of a tic-tac-toe board, column, the row increment, and the column increment) which is to move through the tic-tac-toe board and return the highest sequence of the symbol inside of the row and column given.
I have it mostly working, except I know that my code is faulty in that it cannot distinguish between instances where it should return 2 vs 3 (it returns 2 rather than 3), but after a solid day of trying every possible thing I could think of, most of my attempted fixes only made it more complex while causing the test to return an out of bounds exception error.
Can somebody please offer some advice as to how I could go about fixing this?
public int getMaxSequence(int row, int column, int dr, int dc, char symbol) {
int maxSequence = 0;
List<Integer> sequence = new ArrayList<Integer>();
sequence.add(0);
for (int i = row, j = column; i <getBoard().length-1 && j < getBoard()[i].length-1; i = i+dr, j = j + dc){
if (this.board[i][j].getSymbol()== symbol && this.board[i+dr][j+dc].getSymbol()!= symbol){
sequence.add(1);
}
else if (this.board[i][j].getSymbol()== symbol && this.board[i+dr][j+dc].getSymbol()== symbol){
sequence.add(2);
}
else if (this.board[i][j].getSymbol()== symbol && this.board[i+dr][j+dc].getSymbol()== symbol
&& this.board[i+dr+dr][j+dc+dc].getSymbol()== symbol){
sequence.add(3);
}
maxSequence = Collections.max(sequence);
if (isWithinBounds( row+dr, column+dc)!=true){
return Collections.max(sequence);}
}
return Collections.max(sequence);
}
}
Here is the test (line 144 marked by /*->*/ is the obstacle thus far, since 3 is expected):
public class TicTacToe5x5Tests extends TestCase {
// Piece is an immutable class so it is okay to make these constants
// Do not make static final pieces in your tests if they are mutable
public static final Piece X = new Piece('x');
public static final Piece O = new Piece('o');
public static final Piece E = new EmptyPiece();
public static final Piece B = new BlockedPiece();
public static TicTacToe5x5Game createStartGame() {
// uses the make start game method on TicTacToe5x5Game
return TicTacToe5x5Game.makeStartGame('o', 'x');
}
public static TicTacToe5x5Game createMidGame1() {
// an example board after 2 turns each (score 1 for x, 2 for o)
Piece[][] board =
{{X, E, E, E, E},
{E, E, E, E, O},
{E, E, B, O, E},
{X, E, E, E, E},
{E, E, E, E, E}};
return new TicTacToe5x5Game(board, 'o', 'x');
}
public static TicTacToe5x5Game createMidGame2() {
// an example board mid-game (score 2 for x, 3 for o)
Piece[][] board =
{{X, O, O, E, X},
{X, E, O, E, O},
{E, E, B, O, E},
{X, O, X, X, E},
{E, O, X, E, E}};
return new TicTacToe5x5Game(board, 'o', 'x');
}
public static TicTacToe5x5Game createEndGame1() {
// an example board where player x has won (score 4 for x, 3 for o)
Piece[][] board =
{{X, O, O, E, X},
{X, E, O, E, O},
{X, E, B, O, E},
{X, O, X, X, E},
{E, E, E, E, E}};
return new TicTacToe5x5Game(board, 'o', 'x');
}
public static TicTacToe5x5Game createEndGame2() {
// an example board where nobody has won (score 3 for x, 3 for o) but there are no more moves
Piece[][] board =
{{X, O, O, O, X},
{O, O, O, X, O},
{X, X, B, O, X},
{X, O, X, X, X},
{O, X, O, O, X}};
return new TicTacToe5x5Game(board, 'o', 'x');
}
public static PlacePieceAction createAction() {
// won't be valid for all TicTacToeGame states, but just an example
return new PlacePieceAction('x', 2, 1);
}
public void test_changeTurn() {
TicTacToe5x5Game game = createStartGame();
assertEquals('x', game.getNotTurn());
assertEquals('o', game.getTurn());
game.changeTurn();
assertEquals('x', game.getTurn());
assertEquals('o', game.getNotTurn());
}
public void test_PlacePieceAction() {
PlacePieceAction action1 = new PlacePieceAction('o', 3, 1);
PlacePieceAction action2 = new PlacePieceAction('o', 2, 2);
PlacePieceAction action3 = new PlacePieceAction('x', 3, 0);
// use the initial state from TicTacToe5x5
TicTacToe5x5Game game0 = createStartGame();
assertTrue(action1.isValid(game0)); // it is o's turn
assertFalse(action2.isValid(game0)); // middle square is not usable by either player
assertFalse(action3.isValid(game0)); // it is not x's turn
// test that performing action1 will put an O at 3, 1
action1.update(game0);
assertEquals('x', game0.getTurn());
Piece[][] expectedBoard1 =
{{E, E, E, E, E},
{E, E, E, E, E},
{E, E, B, E, E},
{E, O, E, E, E},
{E, E, E, E, E}};
assertTrue(Arrays.deepEquals(expectedBoard1, game0.getBoard()));
// test that performing action3 will put an X at 3, 0
assertTrue(action3.isValid(game0)); // it is o's turn now so this is ok
action3.update(game0);
assertEquals('o', game0.getTurn());
Piece[][] expectedBoard2 =
{{E, E, E, E, E},
{E, E, E, E, E},
{E, E, B, E, E},
{X, O, E, E, E},
{E, E, E, E, E}};
assertTrue(Arrays.deepEquals(expectedBoard2, game0.getBoard()));
}
public void test_hasEmptySpace() {
assertTrue(createStartGame().hasEmptySpace());
assertTrue(createMidGame1().hasEmptySpace());
assertTrue(createEndGame1().hasEmptySpace());
assertFalse(createEndGame2().hasEmptySpace());
}
public void test_getMaxSequence() {
TicTacToe5x5Game game = createMidGame2();
// test row 0
assertEquals(2, game.getMaxSequence(0, 0, 0, 1, 'o'));
assertEquals(1, game.getMaxSequence(0, 0, 0, 1, 'x'));
// test row 3
assertEquals(1, game.getMaxSequence(3, 0, 0, 1, 'o'));
assertEquals(2, game.getMaxSequence(3, 0, 0, 1, 'x'));
// test column 0
assertEquals(0, game.getMaxSequence(0, 0, 1, 0, 'o'));
assertEquals(2, game.getMaxSequence(0, 0, 1, 0, 'x'));
// test column 1
assertEquals(2, game.getMaxSequence(0, 1, 1, 0, 'o'));
assertEquals(0, game.getMaxSequence(0, 1, 1, 0, 'x'));
// test down-right diagonal 1,0
assertEquals(0, game.getMaxSequence(1, 0, 1, 1, 'o'));
assertEquals(1, game.getMaxSequence(1, 0, 1, 1, 'x'));
// test down-right diagonal 0,1
/*->*/ assertEquals(3, game.getMaxSequence(0, 1, 1, 1, 'o'));
assertEquals(0, game.getMaxSequence(0, 1, 1, 1, 'x'));
// test down-left diagonal 1,4
assertEquals(2, game.getMaxSequence(1, 4, 1, -1, 'o'));
assertEquals(1, game.getMaxSequence(1, 4, 1, -1, 'x'));
// test down-left diagonal 2,4
assertEquals(0, game.getMaxSequence(2, 4, 1, -1, 'o'));
assertEquals(2, game.getMaxSequence(2, 4, 1, -1, 'x'));
// test middle square (it is not a free square, it is blocked)
assertEquals(2, game.getMaxSequence(0, 2, 1, 0, 'o'));
assertEquals(2, game.getMaxSequence(0, 2, 1, 0, 'x'));
assertEquals(1, game.getMaxSequence(2, 0, 0, 1, 'o'));
assertEquals(0, game.getMaxSequence(2, 0, 0, 1, 'x'));
assertEquals(0, game.getMaxSequence(0, 0, 1, 1, 'o'));
assertEquals(1, game.getMaxSequence(0, 0, 1, 1, 'x'));
assertEquals(1, game.getMaxSequence(0, 4, 1, -1, 'o'));
assertEquals(1, game.getMaxSequence(0, 4, 1, -1, 'x'));
}
public void test_getScore() {
assertEquals(0, createStartGame().getScore('x'));
assertEquals(0, createStartGame().getScore('o'));
assertEquals(1, createMidGame1().getScore('x'));
assertEquals(2, createMidGame1().getScore('o'));
assertEquals(2, createMidGame2().getScore('x'));
assertEquals(3, createMidGame2().getScore('o'));
assertEquals(4, createEndGame1().getScore('x'));
assertEquals(3, createEndGame1().getScore('o'));
assertEquals(3, createEndGame2().getScore('x'));
assertEquals(3, createEndGame2().getScore('o'));
}
public void test_isWinner() {
assertFalse(createStartGame().isWinner('x'));
assertFalse(createStartGame().isWinner('o'));
assertFalse(createMidGame1().isWinner('x'));
assertFalse(createMidGame1().isWinner('o'));
assertFalse(createMidGame2().isWinner('x'));
assertFalse(createMidGame2().isWinner('o'));
assertTrue(createEndGame1().isWinner('x'));
assertFalse(createEndGame1().isWinner('o'));
assertFalse(createEndGame2().isWinner('x'));
assertFalse(createEndGame2().isWinner('o'));
}
public void test_isEnd() {
assertFalse(createStartGame().isEnd());
assertFalse(createMidGame1().isEnd());
assertFalse(createMidGame2().isEnd());
assertTrue(createEndGame1().isEnd());
assertTrue(createEndGame2().isEnd());
}
public void test_AI_getAllValidActions() {
TicTacToe5x5Game game0 = createStartGame();
TicTacToe5x5AI ai = new TicTacToe5x5AI("o");
List<Action<TicTacToe5x5Game>> actions = ai.getAllValidActions(game0);
// check to make sure at least all empty space moves are in there
int missingMoves = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (game0.getBoard()[i][j] instanceof EmptyPiece) {
boolean found = false;
for (Action<TicTacToe5x5Game> action : actions) {
PlacePieceAction ppa = (PlacePieceAction)action;
if (ppa.getRow() == i && ppa.getColumn() == j) {
found = true;
}
}
if (!found) {
missingMoves++;
}
}
}
}
assertEquals(0, missingMoves); // should be 0 missing moves
}
public void test_AI_getHeuristicScore() {
TicTacToe5x5Game game0 = createMidGame2();
TicTacToe5x5AI aiO = new TicTacToe5x5AI("o");
TicTacToe5x5AI aiX = new TicTacToe5x5AI("x");
// score of mid game 2 is 3 for player o. If player o plays at 3, 4
// then they would win with a score of 4
assertEquals(4.0, aiO.getHeuristicScore(new PlacePieceAction('o', 3, 4), game0));
// score should still be 3. if this is 4 then your heuristic is mutating
// the board and not properly undoing its mutation.
assertEquals(3.0, aiO.getHeuristicScore(new PlacePieceAction('o', 2, 4), game0));
// change the turn so if the AI is checking for validity of the action the test
// will still work
game0.changeTurn();
// score of mid game 2 is 2 for player x. However, if player x plays at 2, 0
// then they would win with a score of 4
assertEquals(4.0, aiX.getHeuristicScore(new PlacePieceAction('x', 2, 0), game0));
// score should still be 2. if this is 5 then your heuristic is mutating
// the board and not properly undoing its mutation.
System.out.println(game0);
assertEquals(2.0, aiX.getHeuristicScore(new PlacePieceAction('x', 4, 0), game0));
}
public void test_AI_getBestAction() {
// check to see if on board 2 they will make the move that will win the game
TicTacToe5x5Game game0 = createMidGame2();
TicTacToe5x5AI ai = new TicTacToe5x5AI("o");
PlacePieceAction ppa = (PlacePieceAction)ai.getBestAction(game0);
assertEquals(3, ppa.getRow());
assertEquals(4, ppa.getColumn());
}
public static void main(String[] args) {
// print some games and sample actions
System.out.println(createStartGame());
System.out.println(createMidGame2());
System.out.println(createEndGame2());
System.out.println(createAction());
}
}
You're getting an IndexOutOfBoundsException because you are only testing the top half of the range in your loop test:
for (int i = row, j = column;
i <getBoard().length-1 && j < getBoard()[i].length-1;
i = i+dr, j = j + dc)
You allow negative increments, e.g:
assertEquals(2, game.getMaxSequence(1, 4, 1, -1, 'o'));
Therefore you need to check that the index is greater than or equal to zero or you will get an exception when the index decreases to -1.
for (int i = row, j = column;
i >= 0 && j >= 0 && i < getBoard().length && j < getBoard()[i].length;
i += dr, j += dc)
Also, the upper range check should be less than the length or less than or equal to the length minus one, but not less than the length minus one or you will exclude the last element.
Related
Java 2D Array Placing Value if Adjacent value is the same
There are some similar threads and I have tried some solutions but none are working to how my result is intended to be. I have a 2d array (Which is a game board). If i want to move a playerID to a position in the board I want to check if that position has an adjacent cell that is equal to the player ID. Otherwise it wont place it. For example if i have a board: [0, 0, 0, 0, 0, 0, 0, 1, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 2, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] If i try 1 in position [0][0] it should reject it but if i try put it in either: [0][7], [0][9], [1][6], [1][7],[1][8] (this includes diagonals). My current code was a starting attempt I guess? But im not sure how I could do the clientID check: public void move(int client, int x, int y) { int startPosX = (x - 1 < MIN_X) ? x : x-1; int startPosY = (y - 1 < MIN_Y) ? y : y-1; int endPosX = (x + 1 > MAX_X) ? x : x+1; int endPosY = (y + 1 > MAX_Y) ? y : y+1; for (int rowNum=startPosX; rowNum<=endPosX; rowNum++) { for (int colNum=startPosY; colNum<=endPosY; colNum++) { if (storeArray[x][y] == EMPTY && client <= 5 && client >= 1) { storeArray[x][y] = client; int count = totals.containsKey(client) ? totals.get(client) : 1; totals.put(client, count + 1); } } } So it goes through the rows and columns and if it's in any of the surrounding cells, it should place it. But I can still place it anywhere. Is my code even close to doing what it's supposed to do? What sort of things am i missing to match my criteria and can this code be modified to make it work?
If you can't store the coordinates of clients you can modify your if statement to the following. If you can store the coordinates I would definitely use Leo Leontev's answer. /*I removed check for client to be between 1-5, can be re-added. I would add the checks for the desired spot being empty and the client being within 1-5 to the top of the method. For loop iterates over the possible spaces where the client would be in range check if client is in a space*/ if (storeArray[rowNum][colNum]==client) { //storeArray[rowNum][colNum]=0; storeArray[x][y] = client; //unchanged int count = totals.containsKey(client) ? totals.get(client) : 1; totals.put(client, count + 1); } You can also simplify your startX,Y, endX,Y by using Math.min and Math.max to avoid any indexOutOfBounds errors that may be caused by trying to move the client outside of the board. int startPosX = Math.max(x-1,0); int startPosY = Math.max(y-1,0; int endPosX = Math.min(x+1,storeArray.length-1); int endPosY = Math.min(y+1,storeArray[0].length-1); If you're not doing anything after the totals.put(client,count+1); call you can add a return; statement to exit the method. If you still need to do more work you can add a label to the outer for loop and then break out of the label. Either way will stop your count from counting more than once per move. outerloop: for(int rowNum=startPosX;rowNum<=endPosX;rowNum++){ for(int colNum=startPosY;colNum<=endPosY;colNum++){ if(...){ //code totals.put(client, count+1); break outerloop; } } } Here is the method as it is in my editor public static move(int client, int x, int y){ if(storeArray[x][y]==client) return; int startPosX = Math.max(x-1,0), startPosY=Math.max(y-1,0); int endPosX = Math.min(x+1,storeArray.length-1), endPosY = Math.min(y+1,storeArray[0].length-1); outerloop: for(int rowNum=startPosX;rowNum<=endPosX;rowNum++) { for(int colNum=startPosY;colNum<=endPosY;colNum++){ if(storeArray[rowNum][colNum]==client) { storeArray[x][y]=client; System.out.println("Successful move"); int count = totals.getOrDefault(client, 1); totals.put(client, count + 1); break outerloop; //could set colNum=endPosY+1 and rowNum=endPosX+1 if you don't want to use label/break } } } }
You can use an array to store the coordinates of clients: ArrayList<int[]> clientCoords = new ArrayList<>; And so the move method will look like that: public void move(int client, int x, int y) { int[] coords = clientCoords.get(client); int old_x = coords[0], old_y = coords[1]; // previous coordinates of the client // check that the new cell is adjacent if(Math.abs(x - old_x) <= 1 && Math.abs(y - old_y) <= 1){ clientCoords.set(client, new int[2]{x, y}); // your code int count = totals.containsKey(client) ? totals.get(client) : 1; totals.put(client, count + 1); } }
representing a matrix with column/row labels
I would like to create a 2d Array with Java, or a Matrix with a int numbers. I've already did that..but I still don't know how to assign labels to the rows/columns. I would like to be able to access any number inside the matrix based on the row/columns This is my java code Gson gson = new Gson(); int[][] data = {{78, 0, 0, 0, 0}, {0, 54, 0, 0, 0}, {0, 0, 12, 0, 0}, {0, 0, 0, 74, 0}, {0, 0, 0, 0, 11}}; String json = gson.toJson(data); // Convert JSON string into multidimensional array of int. int[][] dataHeatMap = gson.fromJson(json, int[][].class); for (int[] i : dataHeatMap) { for (int j : i) { System.out.print(j + " "); } System.out.println(""); } return json;
You can use Enums: public enum ROW {a, b, c, d, e} public enum COL {f, g, h, i, j} data[ROW.a.ordinal()][COL.f.ordinal()] = 3;
Use ENUM types which does represend the special index of your 2dim Array. Give them a field called value/name/... and create them with the index of them in the array. Afterwards you can easy call them with getting their letter-value which does represent the array index. It´s very readable and ENUM.<VALUE> does not represent an INT value. So this is the way how you can do it. public enum ROW { A(0), B(1), C(2), D(3), E(4); private final int value; ROW(int value) { this.value = value; } public int getValue() { return value; } } public enum COL { F(0), G(1), H(2), I(3), J(4); private final int value; COL(int value) { this.value = value; } public int getValue() { return value; } } public static void main(String []args){ int[][] matrix = {{78, 0, 0, 0, 0}, {0, 54, 0, 0, 0}, {0, 0, 12, 0, 0}, {0, 0, 0, 74, 0}, {0, 0, 0, 0, 11}}; System.out.println("Value: " + matrix[ROW.A.getValue()][COL.F.getValue()]); } I would prefer the way above because you see what directly happens and can assign any value you want. But you just can use ENUM.ordinal(), too. Then data[ROW.a.ordinal()][...] will return 0 for ROW because it´s listed first. b will return 1,... It just depends on the way they are listed/created on the ENUM.
Solving maze using recursion (2 disrections) in java
i kind of need help on this problem. I want to use recursion to solve a NxN binary matrix. The problem is i think my recursion implementation is somehow not correct. In this problem I'm only allowed to go right and down only. I have checked issafe() method and everything seems to return true or false according to the 1=true and 0=false. if i run the run program, nothing displays. any help would be really appreciated. public class Main { public static void main(String[] args) { int maze[][] = {{1, 0, 0, 0}, {1, 1, 0, 1}, {0, 1, 0, 0}, {1, 1, 1, 2} }; Maze rat = new Maze(); rat.solveMaze(maze, 0, 0); } } public class Maze { int maze[][]; int mazeSize; int EXIT=2; public Maze() { mazeSize=4; maze = new int[mazeSize][mazeSize]; } // check is its safe to traverse public Boolean isSafe(int x, int y, int maze[][]){ if (x>=0 && x<mazeSize && y>=0 && y<mazeSize && maze[x][y]==1){ return true; } else return false; } boolean solveMaze(int maze[][],int x,int y){ int solmaze[][]= { {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; if(maze[x][y]==EXIT){ solmaze[x][y]=1; printmaze(solmaze); return true; } if(isSafe(x, y,maze) && maze[x][y]==1){ solmaze[x][y]=1; return true; } if(isSafe(x, y,maze)==true && solveMaze(maze,x+1,y)==true){// down solmaze[x][y]=1; } if(isSafe(x, y,maze)==true && solveMaze(maze,x,y+1)==true){//right solmaze[x][y]=1; } solmaze[x][y]=0; return false; } void printmaze(int maze[][]){//print maze for(int i=0;i<maze.length;i++){ for(int j=0;j<maze.length;j++){ System.out.print(maze[i][j]); } System.out.println(); } } }
I believe that this is the solution you are looking for: public class Main2 { public static void main(String[] args) { int maze[][] = {{1, 0, 0, 0}, {1, 1, 0, 1}, {0, 1, 0, 0}, {1, 1, 1, 2} }; Maze rat = new Maze(); rat.solveAndPrintMaze(maze, 0, 0); } } public class Maze { int maze[][]; int mazeSize; int EXIT=2; public Maze() { mazeSize=4; maze = new int[mazeSize][mazeSize]; } // check is its safe to traverse public Boolean isSafe(int x, int y, int maze[][]){ if (x>=0 && x<mazeSize && y>=0 && y<mazeSize && maze[x][y]>=1){ return true; } else return false; } int solmaze[][]= { {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; boolean solveMaze(int maze[][],int x,int y){ if(maze[x][y]==EXIT){ solmaze[x][y]=1; // printmaze(solmaze); return true; } // if(isSafe(x, y,maze) && maze[x][y]==1){ // solmaze[x][y]=1; // return true; // } if(isSafe(x+1, y,maze)==true && solveMaze(maze,x+1,y)==true){// down solmaze[x][y]=1; return true; } if(isSafe(x, y+1,maze)==true && solveMaze(maze,x,y+1)==true){//right solmaze[x][y]=1; return true; } solmaze[x][y]=0; return false; } void printmaze(int maze[][]){//print maze for(int i=0;i<maze.length;i++){ for(int j=0;j<maze.length;j++){ System.out.print(maze[i][j]); } System.out.println(); } } void solveAndPrintMaze(int maze[][],int x,int y) { solveMaze(maze, x, y); printmaze(solmaze); } }
On your first call to solveMaze, the second if is true ((0,0) is safe & there is a 1 there), so you return true without having printed anything. Maybe if you explained what this is intended to do, one could help fix it (which may well be by removing it).
You're not actually attempting recursion here. To initiate recursion in the way that you're attempting, you would have to call your solveMaze method from within itself. I was wrong about that. Correct answer is given by Scott below.
Ford - Fulkerson output path used [duplicate]
This question already has answers here: What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? (26 answers) Closed 5 years ago. Here is the code: // Java program for implementation of Ford Fulkerson algorithm import java.util.*; import java.lang.*; import java.io.*; import java.util.LinkedList; class MaxFlow { static final int V = 8; //Number of vertices in graph /* Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path */ boolean bfs(int rGraph[][], int s, int t, int parent[]) { // Create a visited array and mark all vertices as not // visited boolean visited[] = new boolean[V]; for(int i=0; i<V; ++i) visited[i]=false; // Create a queue, enqueue source vertex and mark // source vertex as visited LinkedList<Integer> queue = new LinkedList<Integer>(); queue.add(s); visited[s] = true; parent[s]=-1; // Standard BFS Loop while (queue.size()!=0) { int u = queue.poll(); for (int v=0; v<V; v++) { if (visited[v]==false && rGraph[u][v] > 0) { queue.add(v); parent[v] = u; visited[v] = true; } } } // If we reached sink in BFS starting from source, then // return true, else false return (visited[t] == true); } // Returns tne maximum flow from s to t in the given graph int fordFulkerson(int graph[][], int s, int t) { int u, v; // Create a residual graph and fill the residual graph // with given capacities in the original graph as // residual capacities in residual graph // Residual graph where rGraph[i][j] indicates // residual capacity of edge from i to j (if there // is an edge. If rGraph[i][j] is 0, then there is // not) int rGraph[][] = new int[V][V]; for (u = 0; u < V; u++) for (v = 0; v < V; v++) rGraph[u][v] = graph[u][v]; // This array is filled by BFS and to store path int parent[] = new int[V]; int max_flow = 0; // There is no flow initially // Augment the flow while tere is path from source // to sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edhes // along the path filled by BFS. Or we can say // find the maximum flow through the path found. int path_flow = Integer.MAX_VALUE; for (v=t; v!=s; v=parent[v]) { u = parent[v]; path_flow = Math.min(path_flow, rGraph[u][v]); } // update residual capacities of the edges and // reverse edges along the path for (v=t; v != s; v=parent[v]) { u = parent[v]; rGraph[u][v] -= path_flow; rGraph[v][u] += path_flow; } // Add path flow to overall flow max_flow += path_flow; } // Return the overall flow return max_flow; } // Driver program to test above functions public static void main (String[] args) throws java.lang.Exception { int graph[][] =new int[][] { {0, 14, 0, 10, 0, 18, 0, 0}, {0, 0, 18, 0, 14, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 10}, {0, 0, 10, 0, 8, 0, 0, 0}, {0, 0, 14, 0, 8, 0, 20}, {0, 0, 0, 6, 0, 0, 16}, {0, 0, 16, 0, 0, 0, 0, 6}, {0,0,0,0,0,0,0,0} }; MaxFlow m = new MaxFlow(); System.out.println("The maximum possible flow is " + m.fordFulkerson(graph, 0, 7)); } } I'd like to modify it to output the path and the weight of each edge but I'm not sure how. I would like to know the path taken so i can see whats going on graphically edit: The error as someone has pointed out was that I was missing two elements when i created my matrix. Still unsure how to output the path used.
ArrayIndexOutOfBoundsException is thrown when an array is accessed at an invalid index. for (u = 0; u < V; u++) for (v = 0; v < V; v++) rGraph[u][v] = graph[u][v]; tries to access 8 indexes in 8 one-dimensional arrays in graph and rgraph. But in line# 113, {0, 0, 14, 0, 8, 0, 20}, has 7 elements, which is the 6th one-dimensional array in graph. So accessing graph[5][7] is causing the out of bound error.
Java Linear Regression
I need to find the best fitting regression line for a set of points. For example for this matrix: int b [][] = { { 3, 1, 0, 0, 0, 0, 0, 0, 0 }, { 1, 2, 3, 1, 0, 1, 0, 0, 0 }, { 0, 1, 2, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 3, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 3, 0, 0 }, { 0, 0, 0, 0, 0, 1, 2, 3, 1 }, { 0, 0, 0, 0, 0, 1, 1, 1, 2 }, { 0, 0, 0, 0, 0, 0, 0, 0, 1 } }; Every number represents the amount of data points (weight I suppose) at that location (where rows are the X axis and Columns are for the Y). I have attempted to use the SimpleRegression class from the apache mathematics library and am having some issues. First, it doesn't appear to support weights. Second I believe that I'm doing something wrong, even for a matrix that is nothing but 1's on the main diagonal the slope/intercept results make no sense. public static void main(String[] args) { double a[][] = new double[9][9]; for (int i = 0; i < 9; i++) a[i][i] = 1; SimpleRegression r = new SimpleRegression(true); r.addData(a); System.out.println("Slope = " + r.getSlope()); System.out.println("Intercept = " + r.getIntercept()); } This gives me results that are incorrect. I would assume that this matrix represents the function f(x) = x yet the slope I'm getting is -0.12499.. Could anyone point me at what I'm doing wrong? I have a feeling I'm not only misusing the code but also the mathematics.
As the comments say, addData() expects a 2xN matrix of x y positions or individual x y positions. The following example returns a slope of 1 for a diagonal matrix as expected: public static void main(String[] args) { double a[][] = new double[9][9]; for (int i = 0; i < 9; i++) a[i][i] = 1; SimpleRegression r = new SimpleRegression(true); addData(r, a); System.out.println("Slope = " + r.getSlope()); System.out.println("Intercept = " + r.getIntercept()); } public static void addData(SimpleRegression r, double[][] data) { for(int x=0; x<data.length; x++) { for(int y=0; y<data[0].length; y++) { for(int i=0; i<data[x][y]; i++) { r.addData(x, y); } } } } The example assumes that index 0 corresponds to a position of 0, index 1 corresponds to a position of 1 and so on. If this is not the case you need to add a function to transform index to position.