Java * Two-Dimensional Array * Plotting Points on Array [duplicate] - java

This question already has an answer here:
Java - Two-Dimensional Arrays - Plotting Points
(1 answer)
Closed 6 years ago.
I have an assignment for a JAVA class I am taking. We are discussing two-dimensional arrays, however on this particular assignment, I can not figure out how to return back specific points and set those points with a specific value. Here is the assignment:
Write a method called create2DArray that will fill, create, and return a 10 x 10 2d array with random numbers in the range of 1 to 100. Write a method called print2DArray that will print a 10 x 10 2D array in row column fashion. Write a method called createCoords that will search the 2D array looking for any value that is evenly divisible by 3. Once you have found a number you should log the row, column location. This means when your method finishes it should produce a list of coordinates that I can use to plot my graph. This method must also return the number of coordinates that are divisible by 3 so that I know how many points there are to plot. I am not particular as to how the coordinates are returned back as long as I get a list of the row, column locations. So, I will leave it to you to work out a mechanism for returning the values. To test that you have logged the coordinates create another function called fillLocations that will fill the locations in the array you have logged with -1. So, your program should flow in this order 1.create2DArray 2.print2DArray 3.createCoords 4.fillLocations 5.print2DArray
I understand and have completed create2DArray and print2DArray, but I can not figure out createCoords and fillLocations. Here is what I have so far, but it does not work and there are errors present:
public int createCoords(int row1, int col1){
int[][] coords = new int[row1][col1];
int[][] count = new int[0][0];
int co = 0;
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
if(coords[row][col] % 3 == 0)
co++;
return count[row][col];
}
}
return co;}
public int fillLocations(int[][] count){
int x = 0;
int y = 0;
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
if(count[row][col] % 3 == 0)
x = row;
y = col;
break;
}
}
return (x, y);}

I'm not going to write the code, but pretty much how I would go about doing this is:
I would have a separate 2d boolean array the same size as the 2d int array, auto filled with false. This would go in createCoords.
use nested for loop to cycle through all addresses of the 2d int array, and when i find a number that's divisible by three, i mark the corresponding point on the boolean array as 'true'. This would also go in createCoords.
after the for loops finish, I then look at the original 2d int array and boolean array. i would use the nested for loops again, and when i find a true value on the boolean array, i would mark the corresponding location on the int array as -1. This would go in fillLocations. You should also pass the 2d boolean array to fillLocation along with the 2d int array.
Good luck!
EDIT: this is assuming that the FillLocation function REPLACES values in the 10x10 int array with -1. That's what I interpreted your question to be. Please correct me if i'm wrong. I also added a short description at the end of each paragraph where each segment of code would go.

There are couple of problems with your code. Firstly, for the fillLocations method, you are expected to return the NUMBER of cells ([row][column]) where the value is divisible by 3. This means that for each value that passes the test:
if(coords[row][col] %3 === 0)
Then you should increment the counter by 1.
So for this part, your code would look like:
int [][] your2DArray = new int[10][10];
...
private int getNumberOfValuesDivisibleByThree(){
int numberOfValuesDivisibleByThree = 0;
for (int row=0; row < your2DArray.length; row++){
for(int col = 0; col < your2DArray[0].length; col++){
if(your2DArray[row][col] % 3 === 0){
//value at this coordinate or in this cell is divisible by 3
//here you can 'log' the coordinates as required -
System.out.println(row+","+col);
//increment the count
numberOfValuesDivisibleByThree +=1;
}
}
}
//return the final count
return numberOfValuesDivisibleByThree;
}
Please see how to create and manipulate a 2D array in Java. Syntax for creating a two-dimensional array

Related

2D array being reset to it's original values

I am working on a sudoku game and I am using the method of creating a solved puzzle and then "digging holes" to get the puzzle that is displayed to the user. For some reason, the testingPuzzle array is being reset to the numbers array every time it goes through the loop. It is true that the testingPuzzle array should be set to the numbers array originally, but it should be edited one spot at a time every time it goes through the loop and have a bunch of zeroes in it after a few iterations. Here is the loop itself:
do{
x = Math.abs(rand.nextInt() % 9);
y = Math.abs(rand.nextInt() % 9);
takeaway_num = testingPuzzle[x][y];
testingPuzzle[x][y] = 0;
} while (arraysEqual(solvePuzzle(testingPuzzle), numbers));
SolvePuzzle is a method that solves the given puzzle as parameters and returns that solved puzzle. So basically arraysEqual(solvePuzzle(testingPuzzle), numbers)checks to see if testingPuzzle is solvable
I am setting the testingPuzzle array equal to the numbers array before the do while loop. It looks like this:
int[][] testingPuzzle = new int[9][9];
for(int y = 0; y < 9; y++){
for(int x = 0; x < 9; x++){
testingPuzzle[x][y] = numbers[x][y];
}
}
Just so you know numbers is the sodoku answer that was generated in a previous method.
I am using my own method for testing if the arrays are equal, called "arraysEqual because I thought .equals() was the problem originally. Here is the method I am using for this:
private static boolean arraysEqual(int[][] a, int[][] b){
for(int y = 0; y < 9; y++){
for(int x = 0; x < 9; x++){
if(a[x][y] != b[x][y]){
return false;
}
}
}
return true;
}
I'm not really sure why the testingPuzzle Array is being set to the same as the numbers array at the end of each loop. I think it could have something to do with passing the actual array vs. a copy of it to a method that takes in an array but I'm not sure how that works in java.

Java - Two-Dimensional Arrays - Plotting Points

I have an assignment for a JAVA class I am taking. We are discussing two-dimensional arrays, however on this particular assignment, I can not figure out how to return back specific points and set those points with a specific value. Here is the assignment:
Write a method called create2DArray that will fill, create, and return
a 10 x 10 2d array with random numbers in the range of 1 to 100. Write
a method called print2DArray that will print a 10 x 10 2D array in row
column fashion. Write a method called createCoords that will search
the 2D array looking for any value that is evenly divisible by 3.
Once you have found a number you should log the row, column location.
This means when your method finishes it should produce a list of
coordinates that I can use to plot my graph. This method must also
return the number of coordinates that are divisible by 3 so that I
know how many points there are to plot. I am not particular as to how
the coordinates are returned back as long as I get a list of the row,
column locations. So, I will leave it to you to work out a mechanism
for returning the values. To test that you have logged the
coordinates create another function called fillLocations that will
fill the locations in the array you have logged with
-1. So, your program should flow in this order
create2DArray
print2DArray
createCoords
fillLocations
print2DArray
I understand and have completed create2DArray and print2DArray, but I can not figure out createCoords and fillLocations. Here is what I have so far, but it does not work and there are errors present:
public int createCoords(int row1, int col1){
int[][] coords = new int[row1][col1];
int[][] count = new int[0][0];
int co = 0;
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
if(coords[row][col] % 3 == 0)
co++;
return count[row][col];
}
}
return co;}
public int fillLocations(int[][] count){
int x = 0;
int y = 0;
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
if(count[row][col] % 3 == 0)
x = row;
y = col;
break;
}
}
return (x, y);}
As a programmer you'll nearly always need to research for doing different things. This research will be easier when you divide your problem to smaller problems.
For example you need to generate random numbers? So search on google that and you'll find this: How do I generate random integers within a specific range in Java?.
You need to create and return a 2D array? Google and see Syntax for creating a two-dimensional array
And with your art, put the pieces of the puzzle together in a way that gives your desired result.
public int[][] create2DArray() {
int[][] newArray = new int[10][10];
Random random = new Random();
int range = 100;
for(int i = 0; i < 10; i++)
{
for(int j = 0;j<arr[0].length;j++)
{
newArray[i][j]= (random.nextInt(range) + 1);
}
}
return newArray;
}
This method, creates and returns a 10*10 2D array filled with random generated numbers between 1-100. I'm sure you can write the rest of your program and enjoy from it by yourself.

Counting the number of times an element occurs in a given column for a 2D array?

This is a method for a Sudoku game.
Could someone explain their thought processes for this? :( I'm having a lot of difficulty figuring this out. I know for the first method, we're supposed to use a for loop or something.
I know my iteration for my method is wrong...Sorry :(
private int countOccurrencesInCol(int col, int d){
for (int i = 0; i < grid.length; i++;){
for(int j = col; j = col; j++;){
if (grid[i][j] == d){
count++;
}
}
}
return count;
}
This method returns the number of times a digit occurs in a given column in a 9 X 9 matrix.
private int countPossiblePlacementsInCol (int col, int d){
This method is supposed to determine the number of spots in a given column where a given digit can be placed, and returns the number of spots where a digit can be placed in a spot for a given column. If the digit already occurs, then the method returns 0.
Here is some code with explainations to help you understand the approach required:
private int countOccurrencesInCol(int col, int d) {
// counter variable to count the number of occurrences
int counter = 0;
// matrix is the 2D array, the first index is the row, second is the column
// loop through each index of the given column, checking for the digit, d
for(int row = 0; row < matrix.length; row++) {
// if a match is found...
if(matrix[row][col] == d) {
// increment the counter by one
counter++;
}
}
// return the final count
return counter;
}
The next method is a bit trickier, because I am not clear on what is required. Is this method supposed to just return the number of empty cells in the given column? Or should it take into account all the rules of sudoku and check if those empty cells are valid moves for that digit? If it is the former, then the solution is simple:
private int countPossiblePlacementsInCol(int col, int d) {
// I am assuming an empty cell is indicated by 0. In that case,
// we can reuse the previous method to find the number of occurrences of d,
// and the occurences of 0
// first, find out if the digit already occurs in the row, return 0
// if it does:
if(countOccurrencesInCol(col, d) > 0) {
return 0;
}
// next, return the number of times 0 occurs (the number of empty cells):
return countOccurrencesInCol(col, 0);
}
However, if you must count only VALID moves, this gets a lot trickier. The last line in the previous method would turn into something more like this:
private int countPossiblePlacementsInCol(int col, int d) {
//start the same as the previous method:
if(countOccurrencesInCol(col, d) > 0) {
return 0;
}
int counter = 0;
// this time, for each cell in the column, you must check that it is a valid move:
for(int row = 0; row < matrix.length; row++) {
if(countOccurrencesInRow(row, d) == 0 &&
countOccurencesInSquare(row, col, d) == 0) {
counter++
}
}
}
The two methods I used this time, countOccurrencesInRow and countOccurencesInSquare are going to do something similar to countOccurrencesInCol. The Row one is basically the same as the Col one, but it checks a row instead of a column. The Square one is a bit trickier. Assuming you know the rules of sudoku, you should know that a square is a 3x3 section of the 9x9 game board (in which there are 9 3x3 sections). The Square method will use the row and col to figure out which square the given cell is in, and then loop through the rows and columns of just that square, counting occurrences of the given digit. For this, you will need to use two for loops, one nested inside the other. If you have trouble understanding how to properly use for loops, and loop through arrays, then I suggest you talk to your teacher/professor for additional help on the topic.
I hope these explanations and examples help. Good luck.
You do not need a second for loop.
Count of occurrence of number in a column can be found by
private int countOccurrencesInCol(int col, int d){
for (int i = 0; i < grid.length; i++){
if (grid[i][col] == d){
count++;
}
}
return count;
}
Hope this helps!
Good luck!

Sqrt, and Math in Arrays

I'm having difficulty understand how to write this array. I need it to out-print 10x5 (50 elements total), and have the first 25 elements equal to the sqrt of the index that it is in, and the last 25 to equal 3 * the index. Yes, this is homework but I'm not asking for you to do it for me, I just need help! I'm getting errors when using Math saying that I cant use double and the double array together. Here is what I have so far:
public class snhu4 {
public static void main(String args[]) {
double alpha[][] = new double[10][5];
double[] sum, sum2;
for (int count=0; count<=25;count++) {
alpha[count]= Math.sqrt(count);
}
for (int count=26; count<=50;count++) {
alpha[count]= count *3;
}
for (int count=0; count<=50;count++) {
System.out.print(alpha[count]);
}
}
}
Because alpha is a multidimensional array, you can't refer to its elements like a normal array.
int myarray[][] = new int[2][2];
In the above example, the array myarray is multidimensional. If I wanted to access the second element in the first array, I would access it like this:
int myint = myarray[0][1];
You are trying to access a multidimensional array by using the access for a normal array. Change
alpha[count]
to
alpha[0][count]
or similar.
Read here for more information on multidimensional arrays.
you defined alpha as a 2D array with lets say 10 items in the first dimension and 5 in the second, and 5x10 is 50 elements.
When using your array to assign values to these elements, u must call upon the array using 2 indices, one for each dimension:
alpha[i][j] = /*double value*/; //with 0<=i<=9 and 0<=j<=4
So the first 25 elements going from left to right in dimension order is going to be:
[0to9][0] and [0to9][1] and [0to4][2]
the next 25 will be
[4to9][2] and [0to9][3] and [0to9][4]
from then on i cannot give you the answers to your homework, but the loops should look like this:
int j;
for(int i = 0; i<25; i++)
{
j=i/10; //integer division will return 0 for i<10, 1 for 10<i<20, etc..
alpha[i%10][j] = Math.sqrt(i);
}
and you can figure out the rest
The 10x5 appears to be an output constraint, not a design constraint.
You are using Java, so use Java constructs, not C-language constructs;
specifically store the values in a List not an array.
Here are some hints:
List<Integer> valuesList = new ArrayList<Integer>();
for (int index = 0; index < 25; ++index)
Integer currentValue = Math.sqrt(index);
valuesList.add(currentValue);
for (int index = 25; index < 50; ++index)
Integer currentValue = index * 3;
valuesList.add(currentValue)
int count = 1;
for (Integer current : valuesList)
if ((count % 5) == 0) // write a newline.
System.out.print(current);
++count

Logic Solving Algorithm for Sudoku (Java)

I decided to write a logic solving algorithm for my Sudoku application. What I wrote works for a limited amount of grid values, but then the recursion stops way too soon.
What my methods do:
addToThirdDimension(): A three dimensional array stores any possible values that can be put into the grid value at logicGrid[x][y]. This method refreshes the three dimensional array. It does this by testing values 1-9 in every grid index, and if it's valid, it adds that number to the array. If not, it sets that value to zero.
checkValues(): Checks how many possibilities are left in the three dimensional grid. It goes through the logicGrid and returns the number of non-zero values are in the grid.
checkSingleValue(int row, int col): Checks logicGrid[row][col] to see if there is one and only one value left in there (If there is one value left, it is the only possibility for the grid element at [row, col]). It returns the amount of non-zero values that are in that grid location.
getSingleValue(int row, int col): Returns the single number that's left in logicGrid[row][col]
immutableValues: A two dimensional boolean array that stores whether or not a specific grid element is immutable or not. If it is immutable, the solve method should not touch it.
public boolean solveWithLogic(){
addToThirdDimension();
if(checkValues() == 0){
return true;
}
for(int row = 0; row < 9; row++){
for(int col = 0; col < 9; col++){
if(!immutableValues[row][col]){
if(checkSingleValue(row, col) == 1){
sGrid[row][col] = getSingleValue(row, col);
setValues[row][col] = true;
addToThirdDimension();
}
}
}
}
if(checkValues() != 0){
solveWithLogic();
} else{
return true;
}
return false;
}
I cannot see where I am going wrong. After a certain number of tries, checkValues returns 0 even though there should be more possibilities. Here is the code for addToThirdDimension() as I am sure that if something is wrong, it is here.
sGrid is the main two-dimensional integer array that stores the values for the puzzle.
public void addToThirdDimension(){
logicGrid = new int[9][9][9];
for(int x = 0; x < 9; x++){
for(int y = 0; y < 9; y++){
for(int z = 0; z < 9; z++){
logicGrid[x][y][z] = z + 1;
}
}
}
int[][] temp1 = sGrid;
for(int row = 0; row < 9; row++){
for(int col = 0; col < 9; col++){
if(setValues[row][col]){
for(int i = 0; i < 9; i++){
logicGrid[row][col][i] = 0;
}
} else{
for(int i = 1; i <= 9; i++){
temp1[row][col] = i;
if(!isColumnValid(col, temp1) && !isRowValid(row, temp1) &&
!isQuadrantValid(row, col, temp1){
logicGrid[row][col][i-1] = 0;
}
}
}
temp1[row][col] = sGrid[row][col];
}
}
}
The code isn't too efficient at the moment. I want to get it working before I start minimizing solve times.
The first thing I would do is create a SudukoCell object that stores your possible values in it. Then create a SudukoBoard with a 2d array of SudukoCells. Also give it an array of SudukoAreas. One area for rows, one area for cols, and one area for blocks.
Add your suduko cells appropriately.
This will help you consolidate your legwork and prevent silly mistakes.
then every time you solve a number, you can go to the cells in each of its areas and remove the number you solved from them.

Categories