I have a question. Can anyone help me with finding duplicates in submatrices?
I have a code which finds submatrices in 2d matrix, but I can't find duplicates. I thought to push the values onto the Stack (because in assignment I should use Stack), find all duplicates in each submatrix, and then compare them, but I don't really know how to do it. I'll be very gratefull, if anyone help me to finish this program.
My code:
public static void main(String[] args) throws Exception {
int[][] data = new int[3][3];
Random random = new Random();
for(int i=0; i<data.length;i++)
{
for(int j=0; j<data.length; j++)
{
data[i][j] = random.nextInt(10);
}
}
printSubMatrix(data);
}
private static void printSubMatrix(int[][] mat) {
int rows=mat.length;
int cols=mat[0].length;
Stack _stack = new Stack();
//prints all submatrix greater than or equal to 2x2
for (int subRow = rows; subRow >= 2; subRow--) {
int rowLimit = rows - subRow + 1;
for (int subCol = cols; subCol >= 2; subCol--) {
int colLimit = cols - subCol + 1;
for (int startRow = 0; startRow < rowLimit; startRow++) {
for (int startCol = 0; startCol < colLimit; startCol++) {
for (int i = 0; i < subRow; i++) {
for (int j = 0; j < subCol; j++) {
System.out.print(mat[i + startRow][j + startCol] + " ");
_stack.push(mat[i+startRow][j+startCol]);
}
System.out.print("\n");
}
System.out.print("\n");
}
}
}
}
System.out.printf(_stack.toString().replaceAll("\\[", "").replaceAll("]", ""));
}
I have to create a Java program for Conway's Game Of Life in procedural manner and I'm only one step away from finishing - all I have left to do is figure out how to make the output change itself(something like a GIF). Instead, my program outputs all the results one by one. I'm figuring it should be some kind of a loop, but I'm not sure. Here's the code:
import java.util.Random;
import java.util.Scanner;
class gameOfLife {
public static void main(String[] args) {
//User input
Scanner in = new Scanner(System.in);
System.out.println("How many rows?");
int rows = in.nextInt();
System.out.println("How many columns?");
int cols = in.nextInt();
//Declaring variables and grids
int[][] grid = new int[rows][cols];
int[][] nextGrid = new int[rows][cols];
int[][] temp = new int [rows][cols];
//Initializing first generation
initiateGrid(grid);
printGameBoard(grid);
//Looping through 10 generations
for (int x = 0; x < 20; x++) {
applyTheRules(grid, rows, cols, nextGrid);
temp = nextGrid;
nextGrid = grid;
grid = temp;
printGameBoard(grid);
}
}
//Initiating first generation grid randomly
static void initiateGrid(int[][] grid) {
Random r = new Random();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = r.nextInt(2);
}
}
}
//Printing out the game board
static void printGameBoard(int[][] grid) {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 0)
System.out.print(" . ");
else
System.out.print(" ■ ");
}
System.out.println();
}
System.out.println();
}
//Applying the rules of the game
static void applyTheRules(int [][] grid, int rows, int cols, int [][] nextGrid) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int count = 0;
if(i-1>=0 && i+1<grid.length && j-1>=0 && j+1<grid[i].length) {
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
count += grid[i + x][j + y];
}
}
count -= grid[i][j];
} else{
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
count += 0;
}
}
}
//Alive cell becomes dead, if there are more than
//3 or less than 2 neighbouring cells
if((grid[i][j]==1)&&(count<2)||(count>3))
nextGrid[i][j]=0;
//Dead cell becomes alive if there are exactly 3 neighbouring cells
else if((grid[i][j]==0)&&(count==3))
nextGrid[i][j]=1;
//State stays the same
else
nextGrid[i][j]=grid[i][j];
}
}
}
}
Every few runs of my program it gives me the error
at outlab6.Battleship.setShips(Battleship.java:75)
at outlab6.Battleship.setBoard(Battleship.java:35)
But I thought that I was already setting the code up so that those shouldn't happen. Can someone tell me what I did wrong and why it's not ignoring the possibilities that make that possible?
package outlab6;
import java.util.Scanner;
public class Battleship {
private int rows;
private int cols;
private Spot spot[][];
Scanner input = new Scanner(System.in);
public Battleship(int rows, int cols){
this.rows = rows;
this.cols = cols;
}
public void setBoard(){
spot = new Spot[rows][cols];
for(int i = 0; i < rows; i++){
for( int j = 0; j < cols; j++){
spot[i][j] = new Spot();
}
}
//setup board to be completely empty
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
spot[i][j].setShip(0);
}
}
// //test code
// for(int i = 0; i < rows; i++){
// for(int j = 0; j < cols; j++){
// System.out.print(spot[i][j].getShip());
// }
// System.out.println();
// }
setShips();
}
public void printBoard(boolean active){
}
public boolean over() {
return false;
}
public void makeGuess() {
input.nextInt();
}
public void printStatistics() {
}
public void setShips(){
//this method creates and places the ships
//start with carrier and move on down
for(int i = 5; i > 1; i--){
int col;
int row;
boolean valid = false;
//set a direction
int direction = (int)(Math.random()*2)+1;
//System.out.println(direction);
//get a valid spot
while(!valid){
//generate a location
int chosenRow = (int)(Math.random()* rows)+1;
int chosenCol = (int)(Math.random()* cols)+1;
System.out.println("Row:" + chosenRow);
System.out.println("Col:" + chosenCol);
//check to see if spot is open
//for horizontal ships
if(chosenCol + i < cols){
for(int j = 0; j < i; j++){
if(spot[chosenRow][chosenCol + i].getShip() == 0){
valid = true;
}else{
valid = false;
}
}
}else{
//go through again
}
}
}
}
}
Your problem is probably here :
int chosenRow = (int)(Math.random()* rows)+1;
int chosenCol = (int)(Math.random()* cols)+1;
This will give you a chosenRow between 1 and rows, and a chosenCol between 1 and cols. Having chosenRow == rows will bring you out of the array bounds when you try to access spot[chosenRow][chosenCol + i].
You should change it to :
int chosenRow = (int)(Math.random()* rows);
int chosenCol = (int)(Math.random()* cols);
I working on a project called life, which is supposed to randomly display either a 1 for alive or 0 for dead. When I execute the program, the zeros and ones keep printing. I looked through the code and I couldn't find wrong.
public class Life {
//Makes the first batch of cells
public static boolean firstgen(boolean[][] a)
{
int N = 5;
double cellmaker = Math.random();
//boolean[][] b = new boolean[N][N];
for (int i = 0; i < N; i++)
{
for (int j= 0; j< N;j++)
{
if (cellmaker >0.5)
{
a[i][j]= true;
return true;
}
else
a[i][j]=false;
}
}
return false;
}
public static void main(String[] args)
{
boolean[][] b = new boolean[5][5];
//Placing the cells
for (int i =0;i < 5; i++)
{
for (int j= 0 ; j < 5;i++)
{
if (firstgen(b)== true)
{
System.out.print("1"); //1 is live cell
}
else
System.out.print("0");// 0 is dead cell
}
System.out.println();
}
}
}
In the following in your main method
for (int j= 0 ; j < 5;i++)
you should increment j instead of i.
Your random call is outside of any loop. It is therefore a constant, which will keep you in the loop. Put the random call inside the loop, and you'll be fine.
public static boolean firstgen(boolean[][] a)
{
int N = 5;
//boolean[][] b = new boolean[N][N];
for (int i = 0; i < N; i++)
{
for (int j= 0; j< N;j++)
{
double cellmaker = Math.random();
if (cellmaker >0.5)
{
a[i][j]= true;
return true;
}
else
a[i][j]=false;
}
}
return false;
}
Plus as was pointed out by Bhesh, change the i++ to a j++ here
for (int i =0;i < 5; i++)
{
for (int j= 0 ; j < 5;j++)
{
if (firstgen(b)== true)
{
System.out.print("1"); //1 is live cell
}
else
System.out.print("0");// 0 is dead cell
}
Try These
//Makes the first batch of cells
public static boolean firstgen(boolean[][] a)
{
int N = 5;
double cellmaker = Math.random();
//boolean[][] b = new boolean[N][N];
for (int i = 0; i < N; i++)
{
for (int j= 0; j< N;j++)
{
if (cellmaker >0.5)
{
a[i][j]= true;
return true;
}
else
a[i][j]=false;
}
}
return false;
}
public static void main(String[] args)
{
boolean[][] b = new boolean[5][5];
//Placing the cells
for (int i =0;i < 5; i++)
{
for (int j= 0 ; j < 5;j++)
{
if (firstgen(b))
{
System.out.print("1"); //1 is live cell
}
else
System.out.print("0");// 0 is dead cell
}
System.out.println();
}
}
I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".
The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the "1" with an "X". The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.
public void printGrid() {
System.out.println...
}
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
public static void printTwoDimensionalArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%d ", a[i][j]);
}
System.out.println();
}
}
just for int array
Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.
public void printGrid(int[][] in){
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
if(in[i][j] == 1)
System.out.print('X' + "\t");
else
System.out.print(in[i][j] + "\t");
}
System.out.print("\n");
}
}
You should loop by rows and then columns with a structure like
for ...row index...
for ...column index...
print
but I guess this is homework so just try it out yourself.
Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.
How about trying this?
public static void main (String [] args)
{
int [] [] listTwo = new int [5][5];
// 2 Dimensional array
int x = 0;
int y = 0;
while (x < 5) {
listTwo[x][y] = (int)(Math.random()*10);
while (y <5){
listTwo [x] [y] = (int)(Math.random()*10);
System.out.print(listTwo[x][y]+" | ");
y++;
}
System.out.println("");
y=0;
x++;
}
}
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
I am also a beginner and I've just managed to crack this using two nested for loops.
I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.
P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.
public static void printGrid() {
for (int i = 0; i < moleGrid.length; i++) {
for (int j = 0; j < moleGrid[0].length; j++) {
if (j == 0 || j % (moleGrid.length - 1) != 0) {
System.out.print(moleGrid[i][j]);
}
else {
System.out.println(moleGrid[i][j]);
}
}
}
}
Hope it helps!
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}