Traversing 2D array and showing the path taken - java

I am trying to traverse a 2D array, first printing out a random array of 0s and 1s and then looping through that same array to change the 0s to 2s showing the path that is being taken to get from the top to the bottom. It compiles, but I can't quite figure out to get it to change the variables without forgetting about the random array. I tried using another set of for loops, which probably isn't the right way to do it...
Here is what I have come up with.
import java.util.*;
public class SearchMaze{
//Variables to set the values of the 2 arrays
private static int n = 8;
private static int m = 7;
private static int[][] maze = new int[n][m];
private static int i = 0;
private static int j = 0;
public static void main(String [] args){
//Randomly select 0s and 1s for the array
Random rand = new Random();
System.out.print(n + "\t" + m);
System.out.println("");
//creates the random array of 0s and 1s
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
maze[i][j] = rand.nextInt(2);
System.out.print(maze[i][j]);
}System.out.println("");
}
//here I was trying to loop through the array again while changing the 0s to 1s
//to show if a "path" from the top to the bottom exists
//but in doing this I am really just creating a different array of random 0s and 1s..
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
maze[i][j] = rand.nextInt(2);
while(i < n - 1 && j < m - 1){
if(maze[i+1][j] == 0)
{
maze[i+1][j] = 2;
i++;
}
else if(maze[i-1][j] == 0)
{
maze[i-1][j] = 2;
i++;
}
else if(maze[i][j+1] == 0)
{
maze[i][j+1] = 2;
j++;
}
else if(maze[i][j-1] == 0)
{
maze[i][j-1] = 2;
j++;
}
else
{
maze[i][j] = 1;
}
System.out.print(maze[i][j]);
}System.out.println();
}//end second for loop
}//end first for loop
}//end main method
}//end searchmaze
It will either change a few of the numbers at the bottom to 2s, just throw an error or generate an enormous amount of 1s without stopping.
Some of the errors I have come across...
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at SearchMaze.main(SearchMaze.java:52)
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: -1
at SearchMaze.main(SearchMaze.java:42)

I think this is what you need.
import java.util.*;
public class SearchMaze{
//Variables to set the values of the 2 arrays
private static int n = 8;
private static int m = 7;
private static int[][] maze = new int[n][m];
private static int i = 0;
private static int j = 0;
/*
* This function is used for searching a way from top to bottom exist or not.
*/
public static boolean searchMaze(int maze[][], int i, int j, int n, int m) {
if(i == n-1 && j > 0 && j < m && maze[i][j] == 0) {
// This is the condition when there is a way to the bottom.
return true;
} else if(i < 0 || i > m-1 || j < 0 || j > m-1 || maze[i][j] == 1) {
// This is the condition when path is end in some where in middle.
return false;
} else {
// There is three way to go bottom
return searchMaze(maze, i+1, j-1, n, m) || searchMaze(maze, i+1, j, n, m) || searchMaze(maze, i+1, j+1, n, m);
}
}
public static void main(String [] args){
//Randomly select 0s and 1s for the array
Random rand = new Random();
System.out.print(n + "\t" + m);
System.out.println("");
//creates the random array of 0s and 1s
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
maze[i][j] = rand.nextInt(2);
System.out.print(maze[i][j]);
}
System.out.println("");
}
//here I was trying to loop through the array again while changing the 0s to 1s
//to show if a "path" from the top to the bottom exists
//but in doing this I am really just creating a different array of random 0s and 1s..
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
// This is used to search a path from i,j to the bottom.
if(searchMaze(maze, i, j, n, m)) {
System.out.println("There is a way from "+i+" & "+j);
}
}//end second for loop
}//end first for loop
}//end main method
}//end searchmaze

Related

Generating primes using nested loops (java). Problem with loops

I already generated primes using the Sieve of Eratosthenes algorithm (I asked about it here Sieve of Eratosthenes, generating primes. Problem with loops)
But now I have to do it using only an array and nested loops.
I tried to apply this approch https://examples.javacodegeeks.com/java-basics/for-loop/generate-prime-numbers-with-for-loop/, but I can't get why it doesn't work correctly for me
I just want to check if a number is prime and add it to my array
Could u help me pls?
public class Part6 {
public static int[] primeSequence(int n) {
int[] primes = new int[n];
for (int i = 2; i < n; i++) {
boolean isPrimeNumber = true;
for (int j = i + 1; j < i; j++) {
if(j % i == 0)
isPrimeNumber = false;
break;
}
if (isPrimeNumber)
primes[i] = i;
}
return primes;
}
public static void main(String[] args) {
for (int number : primeSequence(Integer.parseInt(args[0]))) {
System.out.print(number);
}
}
}
You are missing braces in your inner loop, your inner loop doesn't get executed (int j = i + 1; j < i!), the order of operands in the modulo operation is wrong and the inner loop should probably start at 2.
for (int j = 2; j < i; j++) {
if(i % j) == 0){
isPrimeNumber = false;
break;
}
}
If we start the second loop from j=i+1 then we will miss many numbers which might be a divisor of the number i. So, to check if i is a prime or not we should start with j=2 for every i-th iteration.
Also, inside every nested loop we are checking if i is Prime or not so, we should whether i % j == 0 or not.
Here is a modified version:
public static int[] primeSequence(int n)
{
int k = 0;
int[] primes = new int[n];
for (int i = 1; i < n; i++)
{
boolean isPrimeNumber = true;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
isPrimeNumber = false;
break;
}
}
if (isPrimeNumber)
primes[k++] = i;
}
return primes;
}

Need help optimizing Java program for Goldbach Conjecture

I need to print all prime numbers from 1 to 1,000,000 and print all even numbers from 4 to 10,000 and two prime numbers that sum to it.
I have a sieve method that changes all non-prime numbers in an array to a 0 (the problem specifically asks for this to be done), and I need to use a goldbach method that passes this array and displays all even numbers from 4 to 10,000 and two primes that sum up to that number.
The point of the goldbach portion of the problem is to print the numbers efficiently, and I am pretty sure my solution uses a polynomial time search when the correct solution is to be done with a linear time search. Any clue on how I might optimize this?
import java.lang.Math;
public class sieveAndGoldbach {
public static void sieve(int[] a) {
int n = a.length;
a[0] = 0;
for (int i = 1; i <= Math.sqrt(n); i++) {
if (a[i] != 0) {
for (int j = a[i]*a[i]; j <= n; j+=a[i]) {
a[j-1] = 0;
}
}
}
}
public static void goldbach(int[] a) {
int max = 10000;
for (int i = 4; i <= max; i += 2) {
int count = 0;
for (int j = 0; j < i/2; j++) {
if (a[j] != 0) {
int difference = i-a[j];
for (int k = 0; k < max; k++) {
if (a[k] == difference && count == 0) {
System.out.println(i + " = " + a[j] + " + " + (difference));
count++;
}
}
}
}
}
}
public static void main(String[] args) {
//initialize and fill array from 1 to n
int n = 1000000; //initially one million GOLDBACH METHOD WILL NOT WORK FOR n < 10,000
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = i + 1;
}
//Call sieve method on array a, then print all primes, not the zeros
sieve(a);
for (int i = 0; i < n; i++) {
if (a[i] != 0) {
System.out.print(a[i]);
System.out.print(" ");
}
}
System.out.print("\n");
//Call goldbach method on array a
goldbach(a);
}
}
You currently seem to be iterating through the array of primes for each prime looking for one that sums to your target. That's not necessary; you just need to check whether the difference is a prime:
int[] primes;
int target;
for (int i = 2; i < target / 2; i++) {
if (primes[i] != 0 && primes[target - i] != 0)
...
}
Beyond that I can't see a lot of obvious optimisation but there may well be some numerical analysis that allows you to target likely primes first.

Specific cell test understanding the game of life Function

I have game of life exercise, I wrote the whole game only remains for me to write the function that checks the cell and decides whether he lives or dies.
the code:
public class lifeGame1 {
public static void main(String[]args){
gameOfLife(4, 5, 0.3);
}
public static void gameOfLife(int n, int m, double p){
int[][] matrix = new int[n][n];
// Random each matrix[i][j]
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(Math.random() < p)
matrix[i][j] = 1;
else
matrix[i][j] = 0;
} // for j
} // for i
System.out.println("The board is: ");
printMatrix(matrix);
int steps = 0;
while(steps < m){
int[][] newMatrix = new int[n][n];
for(int i = 0; i < newMatrix.length; i++){
for(int j = 0; j < newMatrix[i].length; j++){
newMatrix[i][j] = checkTheNewValueOfCell(matrix, i, j);
}
}
matrix = newMatrix;
System.out.println("The new board: ");
printMatrix(matrix);
steps++;
} // while
}
public static void printMatrix(int[][] matrix){
// Random each matrix[i][j]
for(int i = 0; i < matrix.length; i++){ // for each row
for(int j = 0; j < matrix[i].length; j++){ // print one row
System.out.print(matrix[i][j] + " ");
} // for j
System.out.println();
} // for i
}
}
Cell can make the dead or make a life according to the following rules:
1. Live cell can become dead as a result of:
A. If it has a density of more than three live neighbors.
B. Solitude if it has fewer than two live neighbors.
Hence the cell life continues to be my life if and only if it has two or three live neighbors.
2 dead cell can turn the cheek if it has exactly three live neighbors.
While the volume chamber has five neighbors) if Angular three (but also for work the same rules.
Code that checks the cell:
private static int checkTheNewValueOfCell(int[][] matrix, int i, int j) {
// check how much active neighbors
int countActiveNeighbors = 0;
for(int k = i-1; k <= i+1; k++){
for(int m = j-1; m <= j+1; m++){
if(k >= 0 && k < matrix.length && m >= 0 && m < matrix[0].length){ // אם בתחום
if(k != i || m != j)
if(matrix[k][m] == 1)
countActiveNeighbors++;
} // if
} // for m
} // for k
if(matrix[i][j] == 1){ // pail
if(countActiveNeighbors == 2 || countActiveNeighbors == 3)
return 1;
else
return 0;
}else{ // savil
if(countActiveNeighbors == 3)
return 1;
else
return 0;
}
}
I was helped by a lecturer who register their function and indeed work, but I did not realize it until the end and it's really important for me to understand it.
I do not understand the loop Four run from i-1 to i + 1 and the loop Four which run from j-1 to j + 1.
If I am in the first cell so I should get an error that the i-1 is equal to -1 and it is beyond the scope of the array does not it?
Can help writing a simple function so we can understand it better?
thank's
You get an ArrayIndexOutOfBoundsException only when you try to ACCESS an non-valid array index. But in the nested for loops, you have the following if statements:
if(k >= 0 && k < matrix.length && m >= 0 && m < matrix[0].length){ // אם בתחום
if(k != i || m != j)
if(matrix[k][m] == 1)
countActiveNeighbors++;
} // if
the top if tests that k and m are within the matrix (they are both positive and less than the length/width of the matrix). The bottom if then actually accesses the array at index k,m. Since you check for valid indices before you access, you won't get an Exception
I've commented the function to try and make it clearer. Paired with my comment hopefully it helps you understand!
private static int checkTheNewValueOfCell(int[][] matrix, int i, int j) {
// check how much active neighbors
int countActiveNeighbors = 0; // Neighbor count starts at 0
for(int k = i-1; k <= i+1; k++){ // Loop from 1 before the cell to 1 after the cell
for(int m = j-1; m <= j+1; m++){ // Loop from 1 above the cell to 1 below it
if(k >= 0 && k < matrix.length && m >= 0 && m < matrix[0].length){ // אם בתחום // This if statement skips out of bounds in case we are on an edge cell
if(k != i || m != j) // This if statement skips the current cell we are looking at
if(matrix[k][m] == 1)
countActiveNeighbors++; // Finally we increment if we find a neighbor cell
} // if
} // for m
} // for k

How does this code that fills an array with 10 distinct random numbers work?

Can someone please explain the thought process behind this code? I am kind of confused on how it works. This is the question that the code is addressing:
Write code (using one or more loops) to fill an array "a" with 10 different random numbers between 1 and 10.
Thank you so much for any help!
public static void main(String[] args){
//R8.8
int a[] = new int[10];
Random randomGenerator = new Random();
for (int i = 0; i < a.length; i++){
a[i] = 1 + randomGenerator.nextInt(100);
}
for (int i = 0; i < a.length; i++) {
int number = 1 + randomGenerator.nextInt(100);
int count = 0;
for (int j = 0; j < i; j++) {
if (a[j] == number) {
count += 1;
}
}
if (count > 0) i -= 1;
else a[i] = number;
}
}
}
See my comments in the code itself:
public static void main(String[] args){
//make a new array of 10 integers
int a[] = new int[10];
//declare an object which we can use to generate random numbers
//this object probably uses the system time to generate numbers that appear random
//but at the end of the day, java does it for us so
//we don't really need to know or care how it generates random numbers
Random randomGenerator = new Random();
//loop over each element in our array
for (int i = 0; i < a.length; i++){
//for each element, set that element to a random between 1 and 100 inclusive
//nextInt(x) gets a number between 0 (inclusive) and x (not inclusive)
//so to translate that to 1 to x inclusive, we need to add 1 to the result
a[i] = 1 + randomGenerator.nextInt(100);
}
//everything below here does literally nothing to solve the problem
//everything you need to fill the array with random numbers is above
for (int i = 0; i < a.length; i++) {
int number = 1 + randomGenerator.nextInt(100);
int count = 0;
for (int j = 0; j < i; j++) {
if (a[j] == number) {
count += 1;
}
}
if (count > 0) i -= 1;
else a[i] = number;
}
}
}
Please note that you should use 1 + randomGenerator.nextInt(10); to fill the array with numbers between 1 and 10, not 1 + randomGenerator.nextInt(100);.

Infinite loop when printing an N x N table

Consider the following Java program:
public class RelativelyPrime {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // Dimensions of grid
int i, j;
int r; // Remainder when i is divided by j
for (i = 1; i <= N; i++) {
for (j = 1; j <= N; j++) {
do { // Using Euclidean algorithm
r = i % j;
i = j;
j = r;
} while (r > 0);
if (i == 1) System.out.print("*");
else System.out.print(" ");
}
System.out.println();
}
}
}
This program prints an N x N table (or matrix, if you like) where N is a command-line argument.
The (i, j)-entry is a * if i and j are relatively prime, or a single whitespace if they are not relatively prime. When I run the program by entering, for instance, java RelativelyPrime 3 it endlessly prints *. Why is this happening?
You changed i and j in the while loop.
for (i = 1; i <= N; i++) {
for (j = 1; j <= N; j++) {
int ii = i, jj = j;
do { // Using Euclidean algorithm
r = ii % jj;
ii = jj;
jj = r;
} while (r > 0);
if (ii == 1) System.out.print("*");
else System.out.print(" ");
}
System.out.println();
}
This is where using the debugger would have helped you solve the problem.
Inside your loops, you alter both i and j which means they never reach N and thus you have an infinite loop.
I suggest you not alter these variables but instead use two new variables, ideally with meaningful names.

Categories