Trouble with randomly generated arrays - java

So I am working on a assignment that deals with randomly generated arrays. Here is the assignment:
Write the following function that tests whether a two-dimensional list has four consecutive numbers of the same value, either horizontally, vertically, or diagonally. public static boolean isConsecutiveFour(int[][] values) Write a test program that prompts the user to enter the number of rows and columns of a two-dimensional list and then use a random number generator to fill the array and print it out. Display True if the list contains four consecutive numbers with the same value. Otherwise, display False.
I got everything else done, and it seems to work, but I am stuck on the randomly generating the array part. What is supposed to happen is the user is supposed to enter in the amount of rows and columns for an array, then it is generated. Then, the array is tested to find out whether or not four consecutive numbers exist. When I come to test the problem, it does not actually display the numbers. I am at a loss, and really confused ( Can anyone help me or give me a hint? It would be greatly appreciated. Thank You!
import java.util.Random;
import java.util.Scanner;
public class ConsecutiveFour {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random r = new Random();
System.out.print("Enter number of rows: ");
int rows = input.nextInt();
input.nextLine();
System.out.print("Enter number of columns: ");
int columns = input.nextInt();
input.nextLine();
int[][] matrix = new int[rows][columns];
// generate some random boolean values
boolean[] booleans = new boolean[10];
for (int i = 0; i < booleans.length; i++) {
booleans[i] = r.nextBoolean();
}
for (boolean b : booleans) {
System.out.print(b + ", ");
}
System.out.println("");
}
public static boolean isConsecutiveFour(int[][] values) {
boolean cons = false;
int
//tests horizontally
for (int r=0; r < rows; r++) {
for (int c=0; c < columns - 3; c++){
if (values[c][r] == values[c+1][r] &&
values[c][r] == values[c+2][r] &&
values[c][r] == values[c+3][r]) {
cons = true;
}
}
}
//tests vertically
for (int r=0; r < rows - 3; r++) {
for (int c=0; c < columns; c++){
if (values[c][r] == values[c][r+1] &&
values[c][r] == values[c][r+2] &&
values[c][r] == values[c][r+3]) {
cons = true;
}
}
}
//tests diagonally (going down and to the right)
for (int r=3; r < rows; r++) {
for (int c=0; c < columns - 3; c++) {
if (values[c][r] == values[c+1][r-1] &&
values[c][r] == values[c+2][r-2] &&
values[c][r] == values[c+3][r-3]) {
cons = true;
}
}
}
//tests diagonally (going down and to the left)
for (int r=0; r < rows - 3; r++) {
for (int c=0; c < columns - 3; c++) {
if (values[c][r] == values[c+1][r+1] &&
values[c][r] == values[c+2][r+2] &&
values[c][r] == values[c+3][r+3]) {
cons = true;
}
}
}
return cons;
}
}

To start both of the input.nextLine(); lines are unnecessary. Your input.nextInt(); will be enough to bring in the two values that you need.
It might be easier for you to generate the exact number of random numbers that you need. Seeing how this is an assignment i'll throw you some pseudo code to work through.
for (int i = 0; i < rows; i++) {
for (int k = 0; i < columns; k++) {
int ranNum // Generate random number
// Place random number in matrix[i][k]
}
}
// Send array through checks
Is this the problem you are having or am I misunderstanding your confusion?

Related

check if two rows or columns of a matrix are equal

I'm trying to check if two columns of a square matrix are equal. The function is working, but I want to reduce the complexity by using two for instead of three. It's possible? I tried a lot and I couldn't.
int a=0;
boolean equalColumns=false;
for(int k=0;k<this.getRows()-1;k++){
for(int i=k;i<this.getRows()-1;i++){
for(int j=0;j<this.getColumns();j++){
if(this.getElement(j, k)==this.getElement(j, i+1)){
a++;
}
}
if(a==this.getColumns()){
equalColumns=true;
}
}
}
Maybe I didn't understand completely your question; if you have a nXn matrix called M and you want to check if col1 and col2 are equals you can do this:
for(int row = 0; row<M.lenght;row++)
if (M[row][col1] != M[row][col2]) return false;
return true;
I would write a method to check on two columns.
this uses two loops to check each column against the others.
if any return true, the loop short circuits and displays the result.
int n = 8;
boolean result = false;
int[][] mat = new int[n][n];
outer: for (int c1 = 0; c1 < n - 1; c1++) {
for (int c2 = c1 + 1; c2 < n; c2++) {
if (result = equalColumns(mat, c1, c2)) {
break outer;
}
}
}
if (result) {
System.out.println("contains equal columns");
}
this just takes the matrix and the columns to be checked and compares them.
it also short circuits as soon as a mismatch is found.
public static boolean equalColumns(int[][] mat, int cola,
int colb) {
for (int row = 0; row < mat.length; row++) {
if (mat[row][cola] != mat[row][colb]) {
return false;
}
}
return true;
}

Java Program to Determine if there are any Duplicate Rows in the Matrix of a 2-Dimensional Array?

So, as the title says, I'm trying to put together a program that will compare the rows of a 2-dimensional array and determine if any rows are identical.
This has to be accomplished in two parts; determining whether any rows are identical and determining how many rows are identical. I'm trying to use a Boolean method to determine whether there are any identical rows and a separate method to determine how many rows are identical if the Boolean method returns true.
For example, if the array were:
1 2 3
2 3 1
1 2 3
Then the Boolean method would return true and the output would be:
The matrix has 2 identical rows.
The issue is that I don't know how I should set up the Boolean method; if I could figure that much out, the rest of the program would be simple to figure out.
How can I set up the Boolean method for this?
Here's the code I've come up with so far if anyone needs it:
public class IdenticalRows {
public static void main(String[] args) {
Scanner KBin = new Scanner(System.in);
char run;
int ROW, COL;
System.out.println("Would you like to begin? (Y/N)");
run = KBin.next().charAt(0);
do {
if(run!='y' && run!='Y' && run!='n' && run!='N') {
System.out.println("Please only type 'y' or 'Y' to begin or type 'n' or 'N' to close the program.");
System.out.println("Would you like to begin? (Y/N)");
run = KBin.next().charAt(0);
}
}while(run!='y' && run!='Y' && run!='n' && run!='N');
do {
System.out.println("Please enter the number of rows:");
ROW = KBin.nextInt();
do {
if (ROW<=0) {
System.out.println("Entry invalid; must be a positive integer greater than 0.");
System.out.println("Please enter the number of rows:");
ROW = KBin.nextInt();
}
}while(ROW<=0);
System.out.println("Please enter the number of columns:");
COL = KBin.nextInt();
do {
if (COL<=0) {
System.out.println("Entry invalid; must be a positive integer greater than 0.");
System.out.println("Please enter the number of columns:");
COL = KBin.nextInt();
}
}while(COL<=0);
int[][] testDuplicates = new int[ROW][COL];
randArray (testDuplicates, MIN, MAX);
System.out.println("Thematrix is:");
printArray(testDuplicates);
System.out.println(" ");
boolean presence = duplicates(testDuplicates);
if (presence=true) {
countDuplicates(testDuplicates);
}
else if (presence=false) {
System.out.println("There are no identical rows in this matrix.");
}
System.out.println("Would you like to run the program again? (Y/N)");
run = KBin.next().charAt(0);
}while(run=='y' || run=='Y');
}
public static void randArray(int[][] matrix, int low, int up) {//Establishes the values of the elements of the array
Random rand = new Random();
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
matrix[r][c] = rand.nextInt(up-low+1)+low;
}
}
}
public static void printArray(int[][] matrix) {//Prints the elements of the array in a square matrix
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
System.out.printf("%5d",matrix[r][c]);
}
System.out.println(" ");
}
}
public static boolean duplicates(int[][] list) {//Determines if any row(s) of elements ever repeat
for (int r=0; r<list.length; r++) {
for (int c=0; c<list[r].length; c++) {
}
}
return false;
}
public static void countDuplicates(int[][] matrix) {
for (int r=0; r<matrix.length; r++) {
for (int c=0; c<matrix[r].length; c++) {
}
}
}
public static final int MAX=3;
public static final int MIN=1;
}
Thank you in advance to anyone who can help!
First of all write the method that compares two rows:
private static boolean areIdentical(int[] a1, int[] a2) {
if(a1.length != a2.length) return false;
for(int i = 0; i < a1.length; i++) {
if(a1[i] != a2[i]) return false;
}
return true;
}
Now you can use this method to compare the rows. Just take every row from the array and compare it with every row below. Something like the next:
public static boolean duplicates(int[][] list) {
for (int j = 0; j < list.length; j++) {
if(j == list.length-1) return false; //don't need to compare last row
for (int i = j + 1; i < list.length; i++) {
if(areIdentical(list[j], list[i])) return true;
}
}
return false;
}
You can easily modify this code to count duplicates.

How to print parts of an 2d array

Im not asking for the answer per say im asking necessarily what would i need to change in order to print out sections of a 2d array for example if the array has 5 rows and 5 columns how would i print out the last 3 rows and last three columns.
import java.util.Scanner;
public class multiplication {
static int a,b;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
a =input.nextInt();
b = input.nextInt();
int[][] matrix = new int[a][b];
matrix = timesTable(a,b);
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(" "+matrix[row][column] + "\t|");
}
System.out.println();
}
}
public static int[][] timesTable(int r, int c)
{
int [][] yes = new int[c][c];
for ( r = 0; r < yes.length ; r++)
{
for (c = 0; c < yes[r].length; c++)
{
yes[r][c] = (r+1)*(c+1);
}
}
return yes;
}
}
if((row = 0 && col > 1) ||( row > 1 && col != 1)) {
//print
}
This logic should work for your example. But I don't understand what you're trying to do.
Can you try explain a bit more what you want to do ?
Edit: you might wanna check this. Oracle documentation bottom of the page with arraycopy and arraymanipulation
Is the goal of this exercise to build the matrix and then print the matrix -or- do you simply need to display the desired output? I assume this is a class assignment.
Hint: Think about this .. if you enter 2 & 5, do you want a 2x5 matrix or a 4x4 matrix? It's important when you alloc your matrix size.

How to check and end a 2d array of noughts and crosses (Java)

I have made a noughts and crosses game using 2D arrays and loops (code is below).I want to end the game once the array is full. I've tried an if statement such as if (board[row][col] = '.') however i'm told this is incompatible as it can't be converted to a boolean. Another idea i have is to count the data entries and end it after 9 goes. However, im new to java and struggling to do these can anyone tell me how to end the game once the array is full?
public static void main(String[] args) {
// TODO code application logic here
Scanner scanner = new Scanner(System.in);
// declare and intitialise the board
char[][] board = new char[3][3];
// initialise all the elements to '.' we use this to indicate that a
// square is empty, because a space character would not be visible
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = '.';
}
}
//The first player is X
int placeRow;
int placeCol;
char thisPlayer = 'X';
boolean finished = false;
while (!finished) {
//Display the board
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
System.out.print(board[row][col]);
}
System.out.println();
}
// Ask the user where to place the next character
System.out.println("Character to be placed is " + thisPlayer);
System.out.print("Enter the row at which you wish to place it> ");
placeRow = scanner.nextInt();
System.out.print("Enter the column at which you wish to place it> ");
placeCol = scanner.nextInt();
if (placeRow < 0 || placeRow > 2 || placeCol < 0 || placeCol > 2 ) {
finished=true;
}
while (!finished) {
//Display the board
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
}
System.out.println();
}
board[placeRow][placeCol] = thisPlayer;
thisPlayer = (thisPlayer == 'X') ? 'O' : 'X';
break;
}
}
}
Incompatible types in an if clause
I've tried an if statement such as if (board[row][col] = '.') however i'm told this is incompatible as it can't be converted to a boolean.
You've been told that, because = is the assignment operator.
In order to check equality you should use == equal to operator:
if (board[row][col] == '.') {
/* do smth */
}
I suggest reading the following articles on operators:
Assignment, Arithmetic, and Unary Operators
Equality, Relational, and Conditional Operators
How to stop execution when the board is full
count the data entries and end it after 9 goes
You have the right idea, you just go through the board at the end of every iteration (just as you do when printing it's content), and check with != not equal operator whether the cells contain anything but dots.
// your external loop
while (!finished) {
/* Displaying the board, prompting for inputs */
// Calculating number of data entries across the board
int dataEntries = 0;
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
if (board[row][col] != '.') {
dataEntries ++;
}
}
}
// Break loop if there are 9 data entries
if (dataEntries > 8) {
System.out.println("Board is full, game over.");
break;
}
}

Using Recursion in java

I'm working on the Conway's game of life program. I have the first two generations of cells printed out, but I can not get anymore printed. So I decided to use recursion so multiple batches of cells can be printed. My NewCells method creates the second generation. I thought that If I were to repeat said method by returning NewCells(c) instead of c, It would print out different results, but it prints out the same batch of cells over and over again.
public class Life {
public static boolean[][] NewCells(boolean[][] c)
{
int N = 5;
int o=0;
int p=0;
int livecnt = 0; //keeps track of the alive cells surrounding cell
int store = 0; //amount of surrounding cells for each individual cell
int livestore[] = new int[N*N];
System.out.println("Next Generation");
// Checks for the amount of "*" surrounding (o,p)
for (o=0; o < N; o++)
{
for (p=0; p<N; p++)
{
for (int k=(o-1); k <= o+1; k++)
{
for (int l =(p-1); l <=p+1; l++)
{
if ( k >= 0 && k < N && l >= 0 && l < N) //for the border indexes.
{
if (!(k== o && l==p)) //so livecnt won't include the index being checked.
{
if (c[k][l] == true)
{
livecnt++;
}
}
}
}
}
livestore[store]= livecnt;
livecnt = 0;
store++;
}
}
//Prints the next batch of cells
int counter= 0;
for (int i2 = 0; i2 <N; i2++)
{
for (int j2 = 0; j2 < N; j2++)
{
if (c[i2][j2] == false)
{
if (livestore[counter] ==3)
{
c[i2][j2]=true;
System.out.print("* ");
}
else
System.out.print("- ");
}
else if (c[i2][j2] == true)
{
if (livestore[counter] ==1)
{
c[i2][j2]= false;
System.out.print("- ");
}
else if (livestore[counter] >3)
{
c[i2][j2]= false;
System.out.print("- ");
}
else
System.out.print("* ");
}
counter++;
}
System.out.println();
}
return NewCell(c);
}
/*************************************************************************************************************************************************/
public static void main(String[] args)
{
int N = 5;
boolean[][] b = new boolean[N][N];
double cellmaker = Math.random();
int i = 0;
int j = 0;
int o=0;
int p=0;
int livecnt = 0; //keeps track of the alive cells surrounding cell
int store = 0; //amount of surrounding cells for each individual cell
int livestore[] = new int[N*N];
System.out.println("First Generation:");
// Makes the first batch of cells
for ( i = 0; i < N ; i++)
{
for ( j = 0; j< N; j++)
{
cellmaker = Math.random();
if (cellmaker > 0.5) // * = alive; - = dead
{
b[i][j]=true;
System.out.print( "* ");
}
if (cellmaker < 0.5)
{ b[i][j] = false;
System.out.print("- ");
}
}
System.out.println();
}
boolean[][] newcells = new boolean[N][N];
newcells = NewCells(b);
}
}
I do not think recursion is a good idea for this application. It leads to a StackOverflowError because each generation pushes another call stack frame. Recursion, as this program uses it, has no advantage over iteration.
Instead, put the main method call to NewCells in a loop. That way, you can run as many iterations as you like, regardless of stack size.
You are not calling NewCell from within NewCell, which is how recursion works.
I'm assuming it's not a typo in your question, but rather a lack of understanding of what it is and how it works, I recommend some reading on recursion in Java.
After you understand the basics, come back here for more help!

Categories