How to track and update a value in a Java 2D array? - java

I need to develop a program that randomly creates an array (10x10) of int values (either 1 or 0; 1 = wall; 0 = no wall) and have a loop that requires the user to navigate the array in a maze-like fashion. This loop must also test if the user has reached the bottom of the array. At the end, the program must print the array with the user's path, basically any value the user touches is a different number than 1 or 0.
I can create and print the array no problem, and set it to only values of 1 or 0 my confusion is:
How to lower the odds of getting a 1.
How to create a loop to navigate/track the maze and the user's path.
How to change the array's values that the user touches, and print the newly changed array correctly. (preferably using nodes).
Let's say this is a randomly generated 5x5 array:
0 1 0 0 1
0 1 1 1 0
1 0 1 1 0
0 1 0 0 1
1 1 0 1 1
This is what the output window would look like using this array:
Where do you want to go (up, down, left, right):
down
Where do you want to go (up, down, left, right):
right
You hit a wall! Game over!
5 1 0 0 1
5 7 1 1 0
1 0 1 1 0
0 1 0 0 1
1 1 0 1 1
The 0's are open paths that allow the user to pass through them, the 1's are walls that end the game if the user runs into them. 5 represents the path of the user, 7 is the spot the user hit a wall at.
In my situation, the array would be 10x10 and only be printed once, at the end of the program. The user would not see the original array.
I'm not asking anyone to program it for me, just a little push in the right direction. I can't seem to figure it out in my head, logically. Again I'm very new to Java programming and would appreciate any help anyone is willing to offer.
I apologize for the very long question, I just want as much clarity as possible, given that my situation requires context to understand fully. If more info is required, I will respond within a day. I have also added photos of my code, if my explanation makes no sense.
I greatly appreciate any and all help given, Thank you very much! :D
Pic 1 of code
Pic 2 of code

For lower odds of getting 1 see this link.
Keep the current location of the played in an object/variable/class ex:
public static class Location {
public static int x = 0;
public static int y = 0;
}
Every time user moves for example down:
Increase Location.x++.
Check if the new location is a wall or not ex: if(Grid[Location.x][Location.y] == 1) /* do stuff */.
Change the value of the grid cell: Grid[Location.x][Location.y] = '{your value}'.

Use Random instead of secure random, you can get the next random with
Random r = new Random();
iWallChance = r.nextInt(100);
2 and 3. Ali Sharabiani has a good answer for that.

Related

Getting a Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException error, and am stuck trying to figure out a solution

I'm writing a bit of code for a school project. However, I'm getting a:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5
at TicTacToe.main(TicTacToe.java:25)
(This is the board[3-w1[i][0]][(w1[i][1])]='O'; bit)
This is a sample input:
5 (size of array)
1 0 0 (the number of black pieces to be placed on the board, followed by B pairs and the row and column of B black pieces)
1 4 4 (the number of white pieces to be placed on the board, followed by W pairs and the row and column of W white pieces)
4 0 0 1 1 1 1 2 2 2 2 3 1 3 1 4 0 (the number of moves, followed by 4 integers: Row 1 Column 1 Row 2 Column 2 which is the row and column of the start and end position of a move. I.e., the piece at R1 C1 is moved to R2 C2)
import java.util.Scanner;
public class TicTacToe {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// Write your code here
int i,j;
int n=in.nextInt();
char board[][]=new char[n][n];
int b=in.nextInt();
int b1[][]=new int[b][2];
for(i=0;i<b;i++){
b1[i][0]=in.nextInt();
b1[i][1]=in.nextInt();
board[3-b1[i][0]][b1[i][1]]='*';
}
int w=in.nextInt();
int w1[][]=new int[w][2];
for(i=0;i<w;i++){
w1[i][0]=in.nextInt();
w1[i][1]=in.nextInt();
board[3-w1[i][0]][(w1[i][1])]='O';
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(board[i][j]!='*' && board[i][j]!='O')
board[i][j]='.';
}
}
int moves=in.nextInt();
char tag;
int m[][]=new int[moves*2][2];
for(i=0;i<(moves*2);i++){
m[i][0]=in.nextInt();
m[i][1]=in.nextInt();
}
for(i=0;i<(moves*2);i++){
tag=' ';
tag=board[3-m[i][0]][m[i][1]];
board[3-m[i][0]][m[i][1]]='.';
i++;
board[3-m[i][0]][m[i][1]]=tag;
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
System.out.print(board[i][j]+"");
}
System.out.println();
}
}
}
Is there a way to fix the error?
Debug this code.
Debugging basically means: Go through the code by 'hand', and figure out in your head what it should be doing. Use pen and paper if you have to.
Then, run the actual code and observe what it actually does. Normally one would use a debugger, but if that feels like a daunting task somehow, hey, there's always the option of litterring a ton of System.out.println statements around. One way or another, you must get insights into what the system is doing.
Then, where the program runs differently than what you thought would happen, guess what? You found one! There may be more, but that's definitely a problem. Investigate, fix, rerun, keep going until the app works.
So, let's get to this specific case: That error means that you are writing arr[i] where arr is an array of size 5, and i is -1, and java has no idea what -1 might mean. Given that it's the board[3-w1[i][0]][(w1[i][1])]='O'; line, that means i is -1, or, w1[i][0] is 4 (resulting in 3-4, which is -1), or w1[i][1] is -1. That's a lot of options which is exactly why you need to debug: Clearly you think this code is such that none of these things could ever be -1, yet, they are. So, print all that stuff. If you can't figure out why something you print is what it is, then find out where that variable is set and print every time you tweak it. Eventually you'll figure out where the problem lies and fix it.
The alternative is that you order a Crystal Ball from amazing voodoo magic coders Ltd, which is how professional coders work: They just gaze into it and divine where errors are, writing perfect code, which is why software you use daily is 100% bug free. Alas. If only. No such thing as crystal balls, I'm afraid. That's what we all do - debug our code.

How to code an adjacency matrix from a file of a weighted graph

I just started learning about graphs and adjacency matrixes, and I have to create an adjacency matrix from a text file of a weighted graph. The text file will look something like this:
0 4 5 0 6
4 0 0 3 6
5 0 0 0 8
0 3 0 0 0
6 6 8 0 0
(We can assume the matrix will always be symmetrical)
From that, we have to create a method to do a breadth first search and a depth first search. I understand the theory of graphs and the searches, but I'm having trouble coding it. Also, if you could do sudo code instead of actual code so I can still learn/ do it myself that would be great! Thank you so much!
For the depth first search I would use a function recursively and pass the int of current node and a list of nodes already visited in it and recur this until all nodes are visited and go back up the recursion to get to the next one along when all have been visited
check node(currentNode, ListOfVisited)
check=0
while(check!=n)//where n is the size of the array
if (matrix.get(check,currentNode) is not in ListOFVisited)
add n to listOfVisted
checkNode(currentNode, ListOfVisited)
end while
//this code will be called when the function comes "back up"
check++
end while
for the bredth first search I would also do it recursively but check all neighbours first and hold them in a queue then recur through the queue after
queue is empty
checknode(node, visited)
check=0
while(check!=n)
if (matrix.get(check,currentNode) isn't in visited)
queue.add(check)
end if
check++
end while
while(queue isn't empty)
checkNode(queue.pop)
end while

Print the lower half of a 2D Array?

I'm trying to figure out one of my homework assignments. I'm not looking for anyone to give me the answers, just some guidance please.
My professor gave me a 2D array that is 5x5 and wants us to print the lower triangular half of the array.
I created the array:
Public static void main(String[] args) {
Int array1 [5][5] = {
{2,3,1,5}
{7,1,5,3,1}
{2,5,7,8,1}
{3,4,9,1,5}
};
This prints the 2D Array:
2 3 1 5 0
7 1 5 3 1
2 5 7 8 1
0 1 5 0 1
3 4 9 1 5
He wants us to print the lower triangular half though, so I believe he wants us to write a method that prints the jagged array of the 2D array, and I don't know where to start.
Can someone help me with this?
I don't know how your print method for the whole matrix works, but you probably are supposed to print the first element of the first row, the first 2 elements of the second row, etc.
Basically, here you should iterate from i = 0 to i = 4 for rows, and j = 4-i to j = 4 for columns and print out in the desired format.
To print a lower triangular half, at each row (starting from 1) it should have same number of columns.
There use two nested for loops to get the lower triangular half of the array, one loop that iterates over the row and another loop that iterates through the column printing only the desired values as output.
Although I am not sure, it seems that your array declaration has also some error.

recursive game plan function

I want to write a simple recursive function for a game plan in java.
I have 2^k teams and want an output like this (e.g. 4 teams):
(team)(day1)(day2)(day3)
1 2 3 4
2 1 4 3
3 4 1 2
4 3 2 1
My idea was to call the function recursive with half of its original size, but I can't figure out how to code it properly. If called with n/2, the output has to go into the upper left corner of the plan, the output PLUS n/2 has to go to the lower left corner and the rest is symmetric to the center.
Thanks
My code so far
public void plan(int size) {
if(size==2){}
else{}
}
make a Set for each day (unique)
then use n(max number)
itterate a loop n times and each itteration
newRandomNumber % n (fetch a random number a limit it to 0 to (n-1)
now add the (generatedValue+1) to the set
if it already exists (do check ) then increment the value till its new value then add to set
note: i dont get ur symetric requirement

Create 2 arrays - 1st has random integers, 2nd has unique random integers

I am working on a school homework problem. I need to create 2 int[] arrays. The first array int[10] is filled with random integers. The second array has the same numbers as in the first array, but without any duplicates.
For example, assume my first array is 1,2,2,3,1,5,5,7,9,9. My second array would then be 1,2,3,5,7,9.
Could someone please point me in the right direction to solving this problem.
Put the numbers into a Set. Then retrieve numbers from the Set. Simple! Duplicates will automatically be removed!
I would do the following (assuming that it is homework and you shouldn't be doing anything too complicated)...
Sort the array using java.util.Arrays.sort(myArray); - this will order the numbers, and make sure that all repeating numbers are next to each other.
Loop through the array and keep a count of the number of unique numbers (ie compare the current number to the next number - if they're different, increment the counter by 1)
Create your second int[] array to the correct size (from point 2)
Repeat the same process as point 2, but fill your new array with the unique numbers, rather than incrementing a counter.
This should be enough to get you moving in the right direction. When you have some code, if you still have questions, come back to us and ask.
I recommend using a Set , but here's a way to do it without using a Set. (Note: This will work, but don't ask me about the efficiency of this!)
Have a function like this -
public static boolean isNumberInArray(int[] array, int number)
{
for(int i=0; i<array.length; i++)
{
if(number == array[i])
return true;
}
return false;
}
Now use this function before you make an insert into the new array. I leave you to figure out that part. It's homework after all!
Hints(WATTO explains it better):
a = sorted first array
lastItem = a[0]
append lastItem into new array
for i in 1 to length(a):
if a[i] != lastItem:
append a[i] into new array
lastItem = a[i]
#WATTO Studios has a good approach. Sorting is always useful when duplicates are involved.
I will suggest an alternative method using hash tables:
Create a hashing structure with an integer as key (the number in the original array) and a counter as a value.
Go through the original array and for each number encountered increment it's corresponding counter value in the hash table.
Go through the original array again. For each number check back the hash table. If the counter associated is greater than 1, remove the value and decrement the counter.
Let's see a practical case:
4 5 6 4 1 1 3
First pass will create the following table:
1 -> 2
3 -> 1
4 -> 2
5 -> 1
6 -> 1
Second pass step by step:
4 5 6 4 1 1 3
^
4 has a counter of 2 -> remove and decrement:
1 -> 2
3 -> 1
4 -> 1
5 -> 1
6 -> 1
5 6 4 1 1 3
^
5 has a counter of 1 -> ignore
6 has a counter of 1 -> ignore
4 has a counter of 1 -> ignore
1 has a counter of 2 -> remove and decrement
1 -> 1
3 -> 1
4 -> 1
5 -> 1
6 -> 1
5 6 4 1 3
^
1 has a counter of 1 -> ignore
3 has a counter of 1 -> ignore
Final array:
5 6 4 1 3
There are, of course, more efficient ways to handle the removal (since using an array implies shifting), like inserting the items into a linked list for example. I'll let you decide that. :)
Edit: An even faster approach, requiring a single pass:
Use the same hashing structure as above.
Go through the original array. For each item check the table. If the associated counter is 0, increment it to 1. If it's already 1, remove the item.

Categories