I need to reverse the objects in a 2D Array
It starts with:
{triangle, circle, square}, {star, pentagon, donut}
And should end with:
{square, circle, triangle}, {donut, pentagon, star}
Currently it outputs:
triangle, circle, square, star, pentagon, donut
I have looked at this question but even copying and pasting working code from that question doesn't work.
Here is the current code I have:
Shape[][] myShapes = {{triangle, circle, square}, {star, pentagon, donut}};
public static void reverseShapes(Shape[][] myShapes) {
// TO DO #1: Implement your algorithm to reverse myShapes.
for(int row = 0; row < myShapes.length; row++){
for(int col = 0; col < myShapes[row].length / 2; col++) {
Shape temp = myShapes[row][col];
myShapes[row][col] = myShapes[row][myShapes[row].length - col - 1];
myShapes[row][myShapes[row].length - col - 1] = temp;
}
}
}//end of reverseShapes
This is how I'd write it:
public static void reverseShapes(Shape[][] shapes) {
for(Shape[] row : shapes) {
for(int left=0, right=row.length-1; left<right; left++, right--) {
Shape tmp = row[left];
row[left] = row[right];
row[right] = tmp;
}
}
}
I think it's much easier to understand with the enhanced for loop syntax pulling a row out at a time, and then the indexed for loop using two different variables, "left" and "right" moving inwards from the ends towards the middle without needing to calculate any indices.
Related
I'm kind of at a roadblock while trying to assign 3D grid points as vertices to Cells.
The Cells should just contain 8 points as corner vertices.
I have created the grid without any issues, but cant seem to figure out how to sort the points to their according cells.
This sketch illustrates how the points are indexed:
One cube with 8 corner points would correspond to a Cell (ex. Cell0 would include points 0,1,3,4,6,7,9,10 as corner points).
The code should be something like this:
public class Cell
{
public int[] Index =new int[8];
}
public void makeCells()
{
numCells = (xSize - 1) * (zSize - 1) * (ySize - 1);
Cells = new Cell[numCells];
for ( int i = 0, j = 0; i < numCells; i++)
{
Cells[i] = new Cell();
for ( int k = 0; k <8; k++, j ++)
{
Cells[i].Index[k] = j;
}
}
}
I can't seem to get how to increment the indices properly so that they coordinate with the correct points.
Any form of help would be appreciated!
I managed to index all of my vertices using the algorithm above. If anyone needs any further explanation please feel free to ask.
I am new to java, so, please respond with clear and direct answers. I made a 12 by 12 matrix of 0s.
000000000000
000000000000
000000000000
000000000000
000000000000
000000000000
000000000000
000000000000
000000000000
000000000000
000000000000
000000000000
I want to surround the middle area with a "fence" of 1s.
111111111111
100000000001
100000000001
100000000001
100000000001
100000000001
100000000001
100000000001
100000000001
100000000001
100000000001
111111111111
I am really new to Java so I only know how to make the 12 by 12 and print it, but now how to make the fence. I also want to know how I could randomly spawn in 10 random 1s inside of the 10 by 10 grid of 0s using a loop. Please help!!!! Here is my code:
class Main {
public static void main(String[] args){
int[][] gameboard = new int[12][12];// make gameboard
int r_length = gameboard.length;//row length
int c_length = gameboard[0].length;//column length
for (int x = 0; x < gameboard.length; x++) {
for(int y = 0; y < gameboard.length; y++){
gameboard[x][y] = x + y;
gameboard[0][y] = gameboard[1]; //replace row 1 (not working)
gameboard[11][y] = gameboard[1]; //replace row 12 (not working)
gameboard[x][0] = gameboard[1]; //replace column 1 (not working)
gameboard[x][11] = gameboard[1]; //replace column 12 (not working)
}
}
for (int[] a : gameboard) {
for (int x :a) {
System.out.print("0");
}
System.out.println();
}//gameboard printing
}
}
I have a slightly different suggestion here: don't put the border into your data.
What if you want to have "*" tomorrow instead of those 1s?! Then you are broken, because you have an array of int, not of chars?!
Meaning: you should actually separate your data and the printing format.
Sure, that makes the printing more complicated (or not, see below), but your approach does have a lot of ugly consequences. For example: what if you want to pass that matrix to some "computation" code at some point? Then that computation code will have to know where/how your "border" sits in that data, to exclude it from its computation. Or when you decide to turn your "text console" program into a GUI application? Then you will probably really draw a border line ... but you will keep carrying around your matrix that includes those "border line" chars (pun intended).
Thus, why not go:
printTopLine();
for (int[] rows : gameboard) {
printRow(row);
where
public void printTopLine() {
...println("1111...
}
and
public void printRow(int[] values) {
print("1");
for (int v : values) print(v);
print("1");
}
As you can see: this is actually very straight forward, and whenever you decide: I want to print things in a different way, you just go in and change thing were necessary, without ever worrying about the data within your 2D array!
So, long story short: you could change your code so that your 2D matrix is only about the values of your game board, and how to "display" that is completely done by other code!
A couple of things here:
Inner loop should iterate over inner length:
for(int y = 0; y < gameboard[0].length; y++)
instead of:
for(int y = 0; y < gameboard.length; y++)
You cannot assign array to int, types must match.
gameboard[0][y] = gameboard[1];
This won't do what you want: gameboard[x][y] = x + y;. It assigns a sum of indices.
Since it's a square (both lengths equal), you can iterate once:
for (int x = 0; x < gameboard.length; x++) {
gameboard[0][x] = 1;
gameboard[11][x] = 1;
gameboard[x][0] = 1;
gameboard[x][11] = 1;
}
Before that you were doing the same work gameboard.length times.
You should also print it properly:
for (int[] a : gameboard) {
for (int x :a) {
System.out.print(x);
}
System.out.println();
}
public static void main(String[] args) {
char border = '1';
char fillCharaters = '0';
int gridLength = 12;
int gridWidth = 12;
char[][] arr = new char[12][12];
Random random = new Random();
for (int j=0; j<gridWidth ; j++){
for (int i=0;i<gridLength;i++){
if(j==0||j==gridWidth-1||i==0||i==gridLength-1){
arr[j][i] = border;
} else {
arr[j][i] = fillCharaters;
}
}
//To print the random characters in the 10X10 grid
int r = random.nextInt(11);
arr[j][r] = border;
}
print2DMatrix(arr);
}
public static void print2DMatrix(char mat[][])
{
for (int i = 0; i < mat.length; i++)
{
for (int j = 0; j < mat[i].length; j++){
if(j==mat[i].length-1){
System.out.println(mat[i][j]);
} else{
System.out.print(mat[i][j]);
}
}
}
}
I am trying to finish my code for an assignment I have, but I'm stuck on the last component. I need to create "stars" (small yellow square objects) in the "sky"... a grid of 5 rows of 10 stars. I am in a beginner java class, and I am supposed to being using methods such as star.moveHorizontal() or star.moveVertical(). All of the relevant posts I've searched for have been too complex or out of my comprehension.
I think that I would need to create an array? We haven't even covered that in class... And then have each "star" be x distance (the first star) + 30 units to the right. Then t continue that trend until there are 10 stars in a row. And then get four more rows of 10 stars.
Here is the code I've create for just one star (in the upper left of my window):
Square s1 = new Square();
s1.makeVisible();
s1.changeColor("yellow");
s1.changeSize(5);
s1.moveVertical(-100);
s1.moveHorizontal(-270);
Then I tried to create an array for a square class... I honestly have no idea if that's even legal.
Square[] starArray = new Square[10];
for ( int i=0; i<starArray.length; i++) {
starArray[i] = new Square();
But then I don't understand how I can call each star and make them appear... Please help. I feel so out of my depth. I've tried to research this and try new things for over 2.5 hours now. I will answer any questions you have to the best of my ability. Thank you
If you can make a single star appear and haven't learned about arrays yet, I don't think that is the answer your teacher is looking for. The point of an array is to be a container so you can reference the objects again. If you don't need to go back to the stars in the future, just create them and set their values in a loop.
// Set defaults for spacing and start positions
int horizontalStartPosition = 10;
int horizontalSpacing = 30;
int verticalStartPosition = 10;
int verticalSpacing = 30;
// Outer loop creates the 4 rows
for (int i = 0; i < 4; i++) {
// Inner loop creates each row
for (int j = 0; j < 10; j++) {
// Create the next star in the row
Square s = new Square();
s.makeVisible();
s.changeColor("yellow");
s.changeSize(5);
// Move the star to the correct vertical position for the current row
s.moveVertical(verticalStartPosition + i * verticalSpacing);
// Move the star to the correct horizontal spacing for the next star
s.moveHorizontal(horizontalStartPosition + j * horizontalSpacing);
}
}
You're on the right track. You can use a 2D array with 5 rows and 10 columns. Try something like this:
int numColumns = 10; //the number of columns in the array
int numRows = 5; // the number of rows in the array
Square[][] starArray = new Square[numRows][numColumns]; // the array itself
final int DIST_X = 10; //the distance between columns (use final because this value should not change)
final int DIST_Y = 10; // the distance between rows (use final because this value should not change)
int y = 0; // the initial row's vertical displacement
for ( int i=0; i<numRows; i++) {
int x = 0; // the initial columns horizontal displacement
for ( int j=0; j<numColumns; j++) {
starArray[i][j] = new Square(); //define the square
starArray[i][j].moveHorizontal(x); // move it x units horizontally
starArray[i][j].moveVertical(y); // move it y units vertically
starArray[i][j].makeVisible(); //show the square
x += DIST_X; //update your horizontal displacement so the next column shows up in the correct position
}
y += DIST_Y; //update your vertical displacement so the next row shows up in the correct position
}
Based on what I understand, you would want to call a method which would basically place a star in the grid for you.
I am not fully sure of what you mean, but here is what I can offer you:
You'll want to create a method for placing a star.
private static int X_SPACING = 30;
private static int Y_SPACING = 20;
public Square placeStar(int x, int y){
// This is the same code that you had before.
Square sq = new Square();
sq.changeColor("yellow");
sq.changeSize(5);
sq.moveVertical(-y); // Where Y is the distance from the TOP LEFT.
sq.moveHorizontal(-x);
return sq;
}
public ArrayList<Square> makeRow(int columnsAmount, int y, int startX){
ArrayList<Square> squares = new ArrayList<>();
for(int i = 0; i < columnsAmount; i++)
squares.add(placeStar(startX + (X_SPACING * i), y));
return squares;
}
public ArrayList<Square> makeGrid(int rowsAmount, int columnsAmount){
ArrayList<Square> rslt = new ArrayList<>();
for(int i = 0; i < rowsAmount; i++)
rslt.addAll(makeRow(columnsAmount, (i * Y_SPACING), 0);
return rslt;
}
Basically, calling "makeRow" should create a row of [rowsAmount] stars, which are all separated by [X_SPACING] pixels.
Then, makeGrid will call makeRow multiple times adjusting [y], and this will make you a grid. Feel free to adjust any value in the code.
EDIT: I've added a makeGrid function, and changed a few variables in the makeRow as I mistyped them. I made the functions return an ArrayList, but you shouldn't need them, only if your teachers later ask to modify them later, or something.
I hope this helps, don't hesitate to ask more questions.
Sneling.
Hey I'm having trouble getting my code to compare the integers of a given row or column and block to make sure there are no duplicates within those parameters. I don't know if it would be a good idea separating the three contraints in 3 different methods or just trying to attempt to do all at once.
public static rowCheck(int[][] nsudokuBoard) {
for (int i =0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
// (nsudokuBoard)
}
}
}
this is my code im starting. before you guys bash on me for not even being able to compile this im stuck on how to compare all the values of a row of the 2d array.
You can compare all the values of the 2d array as shown in the code below:
void validate(final int[][] nsudokuBoard) {
final int width = nsudokuBoard[0].length;
final int depth = nsudokuBoard.length;
for (int i = 0; i < width; i++) {
int j = i;
int reference = nsudokuBoard[i][j];
do {
if (j < width) {
int current = nsudokuBoard[i][j];
if (current == reference) {
// invalid entry found do something
}
}
if (j < depth) {
// note reversed indexes
int current = nsudokuBoard[j][i];
if (current == reference) {
// invalid entry found do something
}
}
++j;
} while ((j >= width) || (j >= depth));
}
}
I haven't tried to compile this code, but it should give you an idea of how to accomplish your task. I would suggest that rather than passing in int[][] sudokuBoard that you should define a class which encapsulates the concept of a SudokuSquare and pass in SudokuSquare[][] , that way your validate method can return a List<SudokuSquare> containing all the offending entries.
I'll show how you might do it for one row, and then you can figure out the rest. I'm assuming your values are 1 through 9 inclusive, and that you don't have any zeroes or any "unfilled entries."
boolean isRowValid(int[][] grid, int row) {
boolean[] seen = new boolean[9];
int row; // chosen somewhere else
for (int col = 0; col < 9; col++) {
if (seen[grid[row][col] - 1]) { // if we've seen this value before in this row
return false; // there is a duplicate, and this is a bad sudoku
}
seen[grid[row][col] - 1] = true; // mark us as having seen this element
}
return true; // we're all good
}
return true; // this row is fine
make a class Cell with fields row,col,block,value; then make a class Matrix with field cells = cell[], fill matrix.
make a class checker with main method Matrix matrix = init(int[][]) and check(matrix), where init(ยท) fills the matrix.
boolean ok = check(matrix) where check(Matrix) does if(!rowcheck())return false; if(!colcheck()) return false etc;
create some methods like getrows(), getrow(r) and for(Cell cell: matrix.values()) to filter out the ones you want.
a bit tedious but i have done it and it is solid as rock.
As a note, filtering over matrix may seem stupid but computers are fast and the problem is O(1) since it is 9x9.
I'm trying to print out an indicator of coordinates on a 2D array...
There is another class that I've used to instantiate objects on the array.
I need to the store coordinates in two (local?) variables, and then display the position of those coordinates in the printed array. (that has already been instantiated with various objects)
This is a snippet of code I have so far, but I can't get the 'C' to print in the right spot on the array. The few options that I tired, either doesn't print it at all, or prints the 'C' in the top left hand corner.
This is one option that I've tired: This option doesn't print the 'C' at all.
private int cX=0;
private int cY=0;
//Randomly set coordinates on array.
for(int i=0; i<array.length; i++){
for(int j=0; j<array[i].length; j++){
int x = randGen.nextInt(9);
int y = randGen.nextInt(9);
if (array [x][y].display()=='.'){
x=cX;
y=cY;
}
}
}
// print array
private void displayArray()
{
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
if ((array [i][j].display()==cX)&&
(array [i][j].display()==cY))
System.out.print("C");
System.out.print(board [i][j].display()+"\t")
}
System.out.println("\n");
}
}
If I understood you right, you'd like to save coordinates to some kind of data structure and later display them?
Wouldn't it be suitable to create a class for this purpose? E.g.
A class called Coordinator, that holds the X & Y values.
Later create a object of the class you've made with X & Y values and put it to a ArrayList.
Code Example:
//Creating the a object holding 2 values
Coordinator cords = new Coordinator(randGen.nextInt(9), randGen.nextInt(9));
//Putting in the object to the data structure
List<Coordinator> list = new ArrayList<>();
list.add(cords);
The explanation and code example should help you solve this issue on your own hopefully.
This option doesn't print the 'C' at all.
Your current code example will indeed never print a 'C'.
for (int j = 0; j < array[i].length; j++){
if ((array [i][j].display()==cX)&&
(array [i][j].display()==cY))
This if condition will be true only if cX equals cY and both are equal to the ascii code value assigned to the array (for '.' this is the value 46). But you may just want to find the cX,cY position and print a 'C'. You should try to campare your position (cX, cY) with the current i and j values.
if ((i==cX)&&(j==cY))
prints the 'C' in the top left hand corner
You never change the content of array at the position. You set x and y which will be overwritten and are later no accessible
int x = randGen.nextInt(9);
int y = randGen.nextInt(9);
if (array [x][y].display()=='.'){
x=cX;
y=cY;
}
Do you want to find a random position for your 'C' to appear, like in a board game?
Then you need to assign your found x and y coordinate to cX and cY. The right value gets assigned to the left variable.
cX = x;
cY = y;
I hope I understood you right and this helps.
For completeness: I think I worked it out. (Well it seems to be working anyway).
Thanks for the help!
private int cX=0;
private int cY=0;
//Randomly set coordinates on the array.
for(int i=0; i<1; i++){
int x = randGen.nextInt(9);
int y = randGen.nextInt(9);
if (board [x][y].display()=='.'){
CX=x;
CY=y;
}
}
//Print array
private void displayArray(){
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board[i].length; j++){
if ((i==CX)&&(j==CY))
System.out.print("C"+"\t");
else
System.out.print(board [i][j].display()+"\t");
}
System.out.println("\n");
}
}
private double[][] mLatLng = {
{19.01062463, 73.01141475},
{19.02369039, 73.00778391},};
public void onMapReady(GoogleMap googleMap) { googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_icon);
for (int i = 0; i < mLatLng.length; i++) {
for (int j = 0; j < mLatLng[i].length; j++) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(mLatLng[i][j], mLatLng[i][j]))
.title("Location" + i).icon(bitmapDescriptorFromVector(context,R.drawable.ic_icon)));