Multi dimelsional slop using recursion - java

That's the multi dimensional array :
{ 3 13 15 28 30} ,
{55 54 53 27 26} ,
{54 12 52 51 50} ,
{50 10 8 53 11} ,
The output should be if num = 1 : 6 , because from [1][0] to [1][2] its 3 and then from [2][2] to [2][3] its 2 so it will be 6 , num its the slope that the user want , the slope can be to the right or to down , its forbidden to use loop of any kind , only recursion, tried for like 8 hours to solve it but i am so confused , here is my code :
private static int longestSlope (int [][] mat, int num , int i , int j , int count , int temp,int oldi,int oldj,boolean found)
{
System.out.println("oldi " +oldi);
System.out.println("oldj " +oldj);
System.out.println("temp " +temp);
System.out.println("count "+count);
System.out.println("i "+i);
System.out.println("j "+j);
if(i == mat.length-1 && j == mat[0].length-1)
return count;
if(i != mat.length && j != mat[0].length)
{
if(j < mat[0].length-1 && mat[i][j] - num == mat[i][j+1] ) // keep j+
{
if(temp == 0)
{
found = true;
oldj = j;
oldi = i;
}
System.out.println("check2");
if(j == 0)
temp = longestSlope(mat,num,i,j+1,count,temp+1,oldi,oldj,found);
else
temp = longestSlope(mat,num,i,j+1,count,temp+1,oldi,oldj+1,found);
}
else if(i < mat.length-1 && mat[i][j] - num == mat[i+1][j])
{
if(temp == 0)
{
found = true;
oldj = j;
oldi = i;
}
temp = longestSlope(mat,num,i+1,j,count,temp+1,oldi,oldj,found);
}
else if(j < mat[0].length-1)
temp = longestSlope(mat,num,i,j+1,count,temp,oldi,oldj,found);
else if(found)
{
System.out.println(found);
System.out.println("found i "+i);
System.out.println("found j "+j);
found = false;
if(j != mat[0].length-1)
temp = longestSlope(mat,num,oldi,oldj,count,0,oldi,oldj,found);
else if(j == mat[0].length-1 && temp != 0)
temp = longestSlope(mat,num,oldi,oldj,count,0,oldi,oldj,found);
else
temp = longestSlope(mat,num,oldi+1,0,count,0,oldi,oldj,found);
}
}
if(i < mat.length-1 && !found)
{
System.out.println("oldj222222222 "+oldj);
return longestSlope(mat,num,i+1,0,count,0,0,0,found);
}
return 0;
}

Related

Something wrong with galton box project results in java

I've written this piece of code to simulate a galton box for a school project:
'''
public class GaltonBoxProject {
public static void main(String[]args){
//This will keep track of the final positions and will sort them
int[] finalColumns = {0,0,0,0,0,0,0};
//will track current pos of the ball
//8 tiers
//start from middle of the box
int randChance;
for(int a = 0; a < 100; a++) {
int currentPos = 3;
for (int i = 0; i < 9; i++) {
//resets the number
randChance = (int) (Math.random() * 100) + 1;
//if less than 50 go to the left
//if 0 --> +
//if 8 --> -
if(currentPos == 0 && randChance > 50) {
currentPos++;
}
else if (currentPos == 7 && randChance <= 50) {
currentPos--;
}
else if(currentPos != 7 && currentPos != 0 && randChance > 50){
currentPos++;
}
else if(currentPos != 7 && currentPos != 0 && randChance < 50){
currentPos--;
}
//If you want to know why I got these results
//I genuinely can't find the reason why this pattern happens
//System.out.print(" RAND: " + randChance);
//System.out.println(" POS: " + currentPos);
}
//Also debugging
//System.out.println(a + " CURRENT POS: " + currentPos);
//This will sort the numbers
for(int k = 0; k < 7; k++){
if(k == currentPos){
finalColumns[k]++;
}
}
}
//for(int i = 0; i < 8; i ++) {
// System.out.println("KEY: " + finalColumns[i]);
}
for(int k = 0; k < 7; k++){
System.out.print(k + ": ");
for(int j = 0; j < finalColumns[k]; j++){
System.out.print("*");
}
System.out.println("");
}
}
'''
I get this result:
0: ********
1: ********
2: **********************
3: ***
4: ******************************
5: *****
6: *****************
I should be getting a bell curve and I don't know why the code is doing this

How do I combine an Output of two for loops into a "table" format?

I used two for loops to convert miles to km and km to miles respectively for selected values. However the issue I am facing is that the output for the first for loop is not side by side with the output of the second table. Appreciate some help on this!
public static double miletoKilometer(double mile) {
double conversion = mile * 1.609;
return conversion;
}
public static double kilometerToMile(double km) {
double conversion2 = km / 1.609;
return conversion2;
}
public static void main(String[] args) {
int mileInput = 0;
double kmOutput = 0;
int kmInput = 0;
double mileOutput = 0;
int displayRow1 = 0;
int displayRow2 = 0;
System.out.print("Miles\tKilometres\tKilometres\tMiles \n");
for (int i = 0; i < 11; i++) {
if (i == 1 || i == 2 || i == 9 || i == 10) {
mileInput = i;
System.out.printf("\n" + i);
kmOutput = miletoKilometer(mileInput);
System.out.printf("\t %.3f\n", kmOutput);
}
}
for (int j = 0; j < 66; j++) {
if (j == 20 || j == 25 || j == 60 || j == 65) {
kmInput = j;
System.out.printf("\n\t\t " + j);
mileOutput = kilometerToMile(kmInput);
System.out.printf("\t\t%.3f", mileOutput);
}
}
}
Current Output:
enter image description here
Changing your loop to match the code below should put everything in the right order. Not the most elegant solution but it gets the job done.
int j = 0;
for (int i = 0; i < 11; i++) {
if (i == 1 || i == 2 || i == 9 || i == 10) {
mileInput = i;
System.out.printf("\n" + i);
kmOutput = miletoKilometer(mileInput);
System.out.printf("\t %.3f", kmOutput);
for (; j < 66; j++) {
if (j == 20 || j == 25 || j == 60 || j == 65) {
kmInput = j;
System.out.printf("\t\t " + j);
mileOutput = kilometerToMile(kmInput);
System.out.printf("\t\t%.3f\n", mileOutput);
j++;
break;
}
}
}
}

How to convert integers 0-80 to point coordinates (0,0) -> (8,8)?

I'm coding up a Sudoku solving program and have a double for loop for iterating through all the coordinate points from (0,0) to (8,8), 9x9=81 cells in total. I'm trying to write my values into the cells with a string of digits, but can't find any useful methods apart from .charAt(i), which doesn't work.
I'm using a double for loop (for i = 0; i < 9; i++) and (for j = 0; j < 9; j++) to iterate through my coordinates new Point(i,j).
Does anyone know how to convert integers from 0-80 to point coordinate form (preferably without double for loops).
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (i == 0 && j == 0) {
sb.append(
sudokuPuzzle.getSudokuCell(new Point(j, i)).toString().substring(76, 77));
} else if (i == 0 && j == 1 || i == 1 && j == 0) {
sb.append(
sudokuPuzzle.getSudokuCell(new Point(j, i)).toString().substring(77, 78));
} else if (i == 0 && j < 9 || i == 1 && j == 1 || i >= 2 && j == 0) {
sb.append(
sudokuPuzzle.getSudokuCell(new Point(j, i)).toString().substring(78, 79));
} else if (i == 1 && j < 9 || i >= 2 && j == 1) {
sb.append(
sudokuPuzzle.getSudokuCell(new Point(j, i)).toString().substring(79, 80));
} else if (i >= 2 && j < 9 || i >= 2 && j == 1) {
sb.append(
sudokuPuzzle.getSudokuCell(new Point(j, i)).toString().substring(80, 81));
}
}
}
System.out.println(sb);
// for all sudoku cells
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.println(sb.charAt(i));
int nextValue = sb.charAt(i);
if (nextValue != 0) {
// get next sudoku cell
SudokuCell sudokuCell = sudokuPuzzle.getSudokuCell(new Point(j, i));
// set values
sudokuCell.setValue(nextValue);
sudokuCell.setIsInitial(true);
sudokuPuzzle.removePossibleValue(sudokuCell);
sudokuCell.clearPossibleValues();
sudokuFrame.repaintSudokuPanel();
}
}
}
Just use the mapping i -> (i / 9, i % 9), which corresponds to the normal mapping you'd expect.

Java Connect 4 MinMax Algorithm

EDIT: I don't know why somebody links me a TicTacToe as duplicate for my question, there isn't even a MinMax-Algorithm in it.
Currently i'm working on a Connect4 game against the computer which should use the MinMax-Algorithm.
Before that, we wrote a TicTacToe which also uses the MinMax, but i'm not sure how to change my old algorithm to match the Connect4-Game :/.
In TicTacToe i evaluated each possible move with the win-conditions i wrote, it worked fine, but now it won't work with my new conditions.
My makeAMove etc. works fine!
These are my old conditions and the MinMax for TicTacToe:
//Player 1 wins
static boolean has1Won(int[][] array) {
gameBoard = array;
//Diagonal
if ((gameBoard[0][0] == gameBoard[1][1] && gameBoard[0][0] == gameBoard[2][2] && gameBoard[0][0] == 1)
|| (gameBoard[0][2] == gameBoard[1][1] && gameBoard[0][2] == gameBoard[2][0] && gameBoard[0][2] == 1)) {
return true;
}
//Spalten/Zeilen
for (int i = 0; i < 3; ++i) {
if (((gameBoard[i][0] == gameBoard[i][1] && gameBoard[i][0] == gameBoard[i][2] && gameBoard[i][0] == 1)
|| (gameBoard[0][i] == gameBoard[1][i] && gameBoard[0][i] == gameBoard[2][i] && gameBoard[0][i] == 1))) {
return true;
}
}
return false;
}
// Player 2 wins
static boolean has2Won(int[][] array) {
gameBoard = array;
//Diagonal
if ((gameBoard[0][0] == gameBoard[1][1] && gameBoard[0][0] == gameBoard[2][2] && gameBoard[0][0] == 2)
|| (gameBoard[0][2] == gameBoard[1][1] && gameBoard[0][2] == gameBoard[2][0] && gameBoard[0][2] == 2)) {
return true;
}
//Spalten/Zeilen
for (int i = 0; i < 3; ++i) {
if (((gameBoard[i][0] == gameBoard[i][1] && gameBoard[i][0] == gameBoard[i][2] && gameBoard[i][0] == 2)
|| (gameBoard[0][i] == gameBoard[1][i] && gameBoard[0][i] == gameBoard[2][i] && gameBoard[0][i] == 2))) {
return true;
}
}
return false;
}
As I said, i used these conditions for my MinMax like this:
public static int minimax(int depth, int turn) {
if (Board.has1Won(Board.gameBoard)){
return +1; // Der Computer gewinnt
}
if (Board.has2Won(Board.gameBoard)){
return -1; // Der Spieler gewinnt
}
List<GameMove> gameMovesAvailable = GameMove.getAvailableGameMoves();
if (gameMovesAvailable.isEmpty()){
return 0; // Das Spiel endet unentschieden
}
...
I'm not sure how i can get this to work with my new conditions:
I think i have to write an evaluating function which checks this for example (this is my wincondition for Rows):
boolean getWinnerInRow (Playboard brd){
int count = 0;
for (int i = 0; i < 6; i++){
for (int j = 0; j < 7; j++){
if (brd.gameBoard[i][j] != 0 && brd.gameBoard[i][j] == brd.gameBoard[i][j+1]){
count++;
} else {
count = 1;
}
if (count >= 4){
return true;
}
}
}
return false;
I know it's a lot of text, but maybe somebody can give me some useful tips :)
Thanks!
Max
I'm not sure that your test to find the winner is correct. Try this (you'll need to change it a little bit, but at least I'm sure that it's correct):
public static boolean testWinner(int[][] game, int lastColumn, Integ e) {
int lastRow = 0;
while (lastRow < 6 && game[lastRow][lastColumn] == 0) {
lastRow++;
}
lastRow = lastRow;
int i = 0;
int j = 0;
int currentPlayer = game[lastRow][lastColumn];
e.setI(currentPlayer);
int sequence = 0;
i = lastRow;
boolean b = i < 3
&& game[i][lastColumn] == currentPlayer
&& game[i+1][lastColumn] == currentPlayer
&& game[i+2][lastColumn] == currentPlayer
&& game[i+3][lastColumn] == currentPlayer;
if(b) {
return true;
}
sequence = 0;
j = lastColumn;
do {
j--;
} while(0 < j && game[lastRow][j] == currentPlayer);
if(j < 0 || game[lastRow][j] != currentPlayer) {
j++;
}
while(j <= 6 && game[lastRow][j] == currentPlayer) {
j++;
sequence++;
}
if (sequence >= 4) {
return true;
}
sequence = 0;
i = lastRow;
j = lastColumn;
do {
i--;
j--;
} while(0 < i && 0 < j && game[i][j] == currentPlayer);
if(i < 0 || j < 0 || game[i][j] != currentPlayer) {
i++;
j++;
}
while(i <= 5 && j <= 6 && game[i][j] == currentPlayer) {
i++;
j++;
sequence++;
}
if (sequence >= 4) {
return true;
}
sequence = 0;
i = lastRow;
j = lastColumn;
do {
i++;
j--;
} while(i < 5 && 0 < j && game[i][j] == currentPlayer);
if (5 < i || j < 0 || game[i][j] != currentPlayer) {
i--;
j++;
}
while(0 <= i && j <= 6 && game[i][j] == currentPlayer) {
i--;
j++;
sequence++;
}
if (sequence >= 4) {
return true;
}
return false;
}
Integ is just a class with an integer. I've created it because the wrapper is not really an object (can't pass by reference).
private static class Integ {
private int i;
public Integ() {
this.i = 0;
}
public void increment() {
this.i = this.i + 1;
}
public int getI() {
return this.i;
}
public void setI(int i) {
this.i = i;
}
}

how to write a conditional telling java that the array index is invalid

(this is a 2d array filled with objects) So the places marked "//Out of Grid" is where I don't know how to tell java that the index its looking for is not in the grid and to move on.
A basic over view of what im trying to accomplish is go thru each cell starting[0][0] and check all of its adjacent neighbors, as for the first check its neighbors would be [0][1],[1][0], and [1][1]. and then if the age of the object in the index is 0, do something..
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int neighbor_x = x + i;
int neighbor_y = y + j;
if (neighbor_x < 0 || neighbor_x >= board.length) {
// Out of Grid
}
if (neighbor_y < 0 || neighbor_y >= board[neighbor_x].length) {
// Out of Grid
}
if (board[neighbor_x][neighbor_y].age == 0) {
nCount++;
if (board[x + i][y + j].getPreviousValue() == 0)
hCount++;
}
}
}
Unless you want to perform some operations, you can simply leave them out.
Out of bound exception can occur in the case where neighbor_x < 0 and neighbor_y >=0, when the second statement is being ran, the first condition is verified and the second throws an exception. You can simply use the only condition that matters
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int neighbor_x = x + i;
int neighbor_y = y + j;
if ((neighbor_x >=0 && neighbor_x < board.length) &&
(neighbor_y >= 0 && neighbor_y < board[neighbor_x].length) &&
board[neighbor_x][neighbor_y].age == 0 ) {
nCount++;
if (board[x + i][y + j].getPreviousValue() == 0)
hCount++;
}
}
}
If this ever throws an exception, then just separate the conditions comme suite
if ( neighbor_x >=0 && neighbor_x < board.length )
if(neighbor_y >= 0 && neighbor_y < board[neighbor_x].length)
if(board[neighbor_x][neighbor_y].age == 0 )

Categories

Resources