Java - Two-Dimensional Arrays - Plotting Points - java

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.

Related

Create 2D array with 2 int arrays

I want to build a 2D matrix with sum of 2 input arrays(by adding row & column elements).
For example, if a is {1,3,5} and b is {4,8}, I want to build my matrix as so: [{1,3,5}, {4,7,9}, {8,11,13}].
Some more explanation here: [{1,3,5} (this is a), {4,7,9} (4 from b, 7=3+4) (9= 5+4), {8,11,13}]. (8 from b again, then 11= 3+8) (13=5+8). If you draw the first row with a, then draw b as the column aligned with a[0], you could add row element with column element to get the sum matrix.
Is there a more efficient way to do so? I tried to write 2 for-loops which gives a large time and space complexity.
public void BuildMatrix (int[] a, int[] b) {
int rows = b.length+1;
int columns = a.length;
int[][] matrix = new int[b.length+1][a.length];
for (int i = 0; i < columns-1; i++) {
matrix[0][i] = a[i];
for (int j = 1; j < rows; j++) {
matrix[j][0] = b[j-1];
matrix[j][i+1] = b[j-1] + a[i+1];
}
} }
Are input arrays to be of any possible size? If you know size ahead of time you can optimize that.
You are computing rows and columns twice:
int rows = b.length+1;
int columns = a.length;
int[][] matrix = new int[b.length+1][a.length];
so why not:
int rows = b.length+1;
int columns = a.length;
int[][] matrix = new int[rows][columns];
likewise you can factor out b[j-1] here (but compiler likely does the same anyway):
matrix[j][0] = b[j-1];
matrix[j][i+1] = b[j-1] + a[i+1];
Those are extremely minor bits though.
You should look into the broader picture and try parallelizing BuildMatrix calls if it's called a lot. You would then prepare a set of inputs for multiple BuildMatrix calls, and run them all on multiple processor cores (in parallel).

What is the quickest way to arrange numbers to 3 dimensional array?

I need to arrange numbers of a given size (provided by user at runtime), to 3 dimensional array to represent these numbers in real 3D space.
For example if user enters 7 then I need to create an array of size 2,2,2 and arrange the first 7 numbers given by user into the array starting from position 0,0,0 .
The cube should always be smallest possible for example cube of size 2 can contain 2*2*2 = 8 values. And need a function that can take input numbers and return 3D integer array with values inserted from input array (input[0] will become result[0][0][0] and so on).
int input[7] ;
int[][][] result = bestFunction(int[] input) {...}
I have implemented with 3 nested for loops by checking each value at a time.
Is there a better or faster approach to implement it?
Do a Math.floor(Math.cbrt(val)) to get the dimension size.
I think we can reduce it to level 1 nesting, or using two loops, using a string input for the z-axis values.
for(int i = 0; i<size; i++)
for(int j = 0;j<size;j++)
arr[i][j]= Arrays.stream(sc.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
where Scanner sc = new Scanner(System.in); if you're taking in user input.
Three for loops would be O(n) as long as you break right after the last element of the input is put in.
int[][][] func(int[] input) {
int size = (int) Math.ceil(Math.cbrt(input.length));
int[][][] result = new int[size][size][size];
int x = 0;
loop: for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
for (int k = 0; k < size; k++) {
result[i][j][k] = input[x++];
if (x == input.length)
break loop; //Finish processing
}
}
}
return result;
}

2D Array with variable internal array length JAVA

Im currently writing some code that print Pascal's Triangle. I need to use a 2D array for each row but don't know how to get the internal array to have a variable length, as it will also always changed based on what row it is int, for example:
public int[][] pascalTriangle(int n) {
int[][] array = new int[n + 1][]
}
As you can see I know how to get the outer array to have the size of Pascal's Triangle that I need, but I don't know how to get a variable length for the row that corresponds with the line it is currently on.
Also how would I print this 2D array?
Essentially what you want to happen is get the size of each row.
for(int i=0; i<array.size;i++){//this loops through the first part of array
for(int j=0;j<array[i].size;j++){//this loops through the now row
//do something
}
}
You should be able to use this example to also print the triangle now.
This is my first answer on StackOverFlow. I am a freshman and have just studied Java as part of my degree.
To make every step clear, I will put different codes in different methods.
Say n tells us how many rows that we are going to print for the triangle.
public static int[][] createPascalTriangle(int n){
//We first declare a 2D array, we know the number of rows
int[][] triangle = new int[n][];
//Then we specify each row with different lengths
for(int i = 0; i < n; i++){
triangle[i] = new int[i+1]; //Be careful with i+1 here.
}
//Finally we fill each row with numbers
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
triangle[i][j] = calculateNumber(i, j);
}
}
return triangle;
}
//This method is used to calculate the number of the specific location
//in pascal triangle. For example, if i=0, j=0, we refer to the first row, first number.
public static int calculateNumber(int i, int j){
if(j==0){
return 1;
}
int numerator = computeFactorial(i);
int denominator = (computeFactorial(j)*computeFactorial(i-j));
int result = numerator/denominator;
return result;
}
//This method is used to calculate Factorial of a given integer.
public static int computeFactorial(int num){
int result = 1;
for(int i = 1; i <= num; i++){
result = result * i;
}
return result;
}
Finally, in the main method, we first create a pascalTriangle and then print it out using for loop:
public static void main(String[] args) {
int[][] pascalTriangle = createPascalTriangle(6);
for(int i = 0; i < pascalTriangle.length; i++){
for(int j = 0; j < pascalTriangle[i].length; j++){
System.out.print(pascalTriangle[i][j] + " ");
}
System.out.println();
}
}
This will give an output like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

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

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

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