Here's what I am trying to replicate:
Currently, my code is as follows:
public void boxes() {
setLocation(20,20);
for(int j =0; j < 5; j = j+1) {
setLocation(20+50*j,20+50*j);
for (int i= 0; i<4; i= i+1) {
move(600-(50*j));
turn(90);
}
}
}
and the result is:
PLEASE do not write me any code, I'd highly prefer just a general explanation as to how I can make it so that the boxes being drawn do not end at the same point. I've been trying to figure it out for the past two hours with no luck and what I currently have is so far the best I've gotten. Thank you!
This is based on http://www.greenfoot.org/scenarios/3535
the problem is with the value you pass to the move() function, it should be:
move(600-(50*j*2));
the reason is that the length of each edge of the square should be shorter by twice the offset from the previous square, as it starts offset units deeper and ends offset units sooner (offset=50 in this case).
The j selects a next square.
Ask yourself:
nice to know: end point of drawing is identical with begin point
you start by (50, 50) more inside. How do you come there from the prior end point
the new length to draw is how much smaller
Related
I will try my best to explain the issue. So basically I have come to the point in my snake game which I feared the most - the array. So I what I have done is an ArrayList full of Rectangles.
I then add a Rectangle each time I eat the food and I am now at the "looping" part where I have to loop the different rectangles.
I succeded with adding one rectangle to the snake - I just took the old head.x location and the head.y location and but it into the snakeParts.get(0).setLocation.
The problem I am having is drawing the rest of the array (which would be index nr 1 to infinity).
I can't seem to get the rest of the ArrayLists's old positions. For example: I want snakeParts.get(1) to get snakeParts.get(0)'s old position but I can't seem to figure out how to do that logic. I wonder if any of you could give me a hand?
Here is the part of the code that is affected:
repaint();
//Test
for(int z = 0; z < snakeParts.size(); z++) {
System.out.println(z); //Test printing
if(z == 0) {
snakeParts.get(z).setLocation(head.x, head.y); //Printing index 0
}
else {
snakeParts.get(z).setLocation(snakeParts.get(z - 1).getLocation());
//Takes all the indexes and puts them where the snakeParts.get(0) is. I want them to get longer - like the Snake game
}
//Loop different might solve the issue?
}
head.x += speedx;
head.y += speedy;
I am doing this in JPanel and my ArrayList is an array of the Rectangle class which can be found here: Rectangle Class
If you want the entire code - please ask! I thought it would be easier to just show you guys this code sample because it's the only part that affects what I am trying to achieve.
Thanks in advance!
Start from the end and go towards the head, get last part, set its position to where last-1 is.
Then go, for last-1, set its position to where last-2 is.
Repeat that until you reach second part, once you set its position to head, then move your head.
Edit.
Here is how does forward vs backward loop look like:
for(int z = 0; z < snakeParts.size(); z++) {}
for(int z = snakeParts.size() - 1; z >= 0; z--){}
First one starts at 0, goes to size of snake parts by increases of 1.
Second one starts at size of snakeparts - 1 (we decrease by 1 because snakeParts are counted from 0, not from 1), works as long as z is greater-equal to 0, and at each step it reduces z by 1.
Hope that helps :)
In your code you should make sure you are not trying to access indices smaller or larger than the array.
I am new in this page, it hope get to some help, basically I am doing a minesweeper game on Java but it have a problem with a function: discover the region with no mines and no numbers like in the game on windows, when you click in one place and all withe cells appear. I tried make recursive but I can't, some help?
Sorry for the code, the original is in spanish but i tried make a pseudocode:
Matriz = multidimensional Array (the minesweeper)
min and max returns the index min and max to iterate (8 sorroud cells)
private void discoverWitheCell(int x, int y) {
if(matriz[x][y].getdiscovered() == false){
matriz[x][y].setDiscovered(true);
}
else{
if(matriz[x][y].getNumberOfMinesArround() == 0){
for(int i=min(x);i<max(x);i++)
for(int j=min(y);j<max(y);j++)
discoverWhiteCell(i,j);
}
}
}
There's not a lot of code here but I feel like you're coming at it backwards.
Sorry, I'm not a Java speaker so I'm guessing at some of the syntax. Note that this can go out of bounds--personally, I would add a layer of empty cells around my map so I never need to concern myself with bounds checking.
private void ClickSquare(int x, int y)
{
// Did the user click an already exposed square? If so, ignore
if (matriz[x][y].getDiscovered()) return;
matriz[x][y].SetDiscovered(true);
if (matriz[x][y].getNumberOfMinesAround != 0) return;
// If empty, click all the neighbors
for (int xloop = x - 1; xloop <= x + 1; xloop++)
for (int yloop = y - 1; yloop <= y + 1; yloop++)
ClickSquare(xloop, yloop);
}
I believe you have the discovered test messed up and your version appears to be able to go into infinite (until the stack overflows) recursion as if the neighbor is also zero it will come back to the original cell. My version stops this recursion by only processing a cell if it hasn't already been processed.
I came across this problem. Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
This is an example of dynamic programming. But a very difficult or confusing concept for me when i come an exercise. I have watched videos and read tutorials online and it seems pretty easy at first but when i approach a problem then i'm totally lost.
So i found a solution online and that uses a bottom approach:
public init minmumTotal(ArrayList<ArrayList<Integer>> triangle) {
if (triangle.size() == 0 || triangle == null)
return 0;
int[] dp = new int[triangle.size()+1]; // store each index’s total
for (int i = triangle.size()-1; i >=0; i--) {
for (int j = 0; j < triangle.get(i).size(); j++) {
// first round: dp[j], dp[j+1] are both 0
dp[j] = Math.min(dp[j], dp[j+1]) + triangle.get(i).get(j);
}
}
return dp[0];
}
Seems easy after going through the solution. But can this be done using a top down approach? And could someone explain why the bottom approach is better than the top down approach? Also when is it appropriate to use either top down or bottom up? And also since the question mentioned that each "Each step you may move to adjacent numbers on the row below." Does that mean for each row iterate the whole column before i step into the next row?
I'm not sure if this solution counts as dynamic programming, but I think it is very efficient.
You can start at the bottom of the triangle, and then collapse it by moving upwards in the triangle. For each number in the next row, add the lowest number of the two numbers below it. When you get to the top, you will only have one number, which would be your result. So you would get this:
Start:
2
3 4
6 5 7
4 1 8 3
Step 1:
2
3 4
7 6 10
Step 2:
2
9 10
Step 3:
11
A little off topic but the first if-statement in that solution needs to be turned around if you really want to handle NullPointerExceptions the right way.
So I tried myself at a top down approach and there are a couple of problems.
First, like marstran already said, you have more numbers in the end and need to do a minimum search.
Second, the bottom up approach used an additional array field to make sure it wouldn't run into IndexOutOfBound Exceptions. I didn't really find a good way to do that in top down (the bottom up approach has the advantage that you always know you have two numbers to look at (left child and right child) with the top down approach a lot of nodes don't have a right or left parent). So there's a couple of additional if-statements.
public static int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
if (triangle == null || triangle.isEmpty()) return 0;
int[] results = new int[triangle.size()];
for (int i = 0; i < triangle.size(); i++) {
ArrayList<Integer> line = triangle.get(i);
for (int j = line.size() - 1; j >= 0; j--) {
if (j == 0) results[j] = line.get(j) + results[j];
else if (j >= i) results[j] = line.get(j) + results[j - 1];
else results[j] = line.get(j) + Math.min(results[j], results[j - 1]);
}
}
int minimum = results[0];
for (int i = 1; i < results.length; i++) {
if (results[i] < minimum) {
minimum = results[i];
}
}
return minimum;
}
Anyway this is as close to the given solution as I could get with a top down approach.
Keep in mind though that nobody is forcing you to only use a 1d array for your results. If that concept is too difficult to just come up with, you could simply use a 2d array. It will increase the amount of code you need to write, but maybe be a little easier to come up with.
I am not familiar with coordinate systems or much of the math dealing with these things at all. What I am trying to do is take a Point (x,y), and find its position in a 1 dimensional array such that it follows this:
(0,2)->0 (1,2)->1 (2,2)->2
(0,1)->4 (1,1)->5 (2,1)->6
(0,0)->8 (1,0)->9 (2,0)->10
where the arrows are showing what value the coordinates should map to. Notice that an index is skipped after each row. I'm think it'll end up being a fairly trivial solution, but I can't find any questions similar to this and I haven't had any luck coming up with ideas myself. I do know the width and height of the 2 dimensional array. Thank you for any help!
My question is perhaps ambiguous or using the wrong terminology, my apologies.
I know that the coordinate (0,0) will be the bottom left position. I also know that the top left coordinate should be placed at index 0. Each new row skips an index by 1. The size of the coordinate system varies, but I know the number of rows and number of columns.
First step, flip the values upside down, keep points in tact:
(0,2)->8 (1,2)->9 (2,2)->10
(0,1)->4 (1,1)->5 (2,1)->6
(0,0)->0 (1,0)->1 (2,0)->2
You'll notice that y affects the output by a factor of 4 and x by a factor of 1.
Thus we get a very simple 4y + x.
Now to get back to the original, you'll notice the transformation is (x,y) <- (x,2-y) (that is, if we transform each point above with this transformation, we get the original required mapping).
So, substituting it into the equation, we get (2-y)*4 + x.
Now this is specific to 3x3, but I'm sure you'll be able to generalize it by replacing 2 and 4 by variables.
If you want to reduce the dimension and avoid overlapping you need a space-filling-curve, for example a morton curve. Your example looks like a peano curve because it's a 3x3 matrix. These curves is difficult to calculate but have some nice things. But if you just look for self-avoiding curves you can create your own? Read here: http://www.fractalcurves.com/Root4Square.html.
I was beaten to the formula, here is the bruteforce using a Map.
public class MapPointToIndex {
private Map<Point, Integer> map;
private int index, rowcount;
public MapPointToIndex(int rows, int columns) {
map = new HashMap<Point, Integer>();
for (int i = rows - 1; i >= 0; i--) {
index += rowcount;
for (int j = 0; j < columns; j++) {
Point p = new Point(j, i);
map.put(p, index);
index++;
}
rowcount = 1;
}
}
public int getIndex(Point point){
return map.get(point);
}
public static void main(String[] args) {
MapPointToIndex one = new MapPointToIndex(3, 3);
System.out.println(one.map);
}
}
Out:
{java.awt.Point[x=0,y=0]=8, java.awt.Point[x=2,y=2]=2, java.awt.Point[x=1,y=2]=1, java.awt.Point[x=2,y=1]=6, java.awt.Point[x=1,y=1]=5, java.awt.Point[x=2,y=0]=10, java.awt.Point[x=0,y=2]=0, java.awt.Point[x=1,y=0]=9, java.awt.Point[x=0,y=1]=4}
Hi I have been given a task for my course and it is to create an algorithm to make a 5 by 5 square like below:
*****
*****
*****
*****
*****
I've spent hours attempting to do it and read tutorials and books. It's so frustrating as I know it must be so easy if you know what you are doing. Can anyone give me any guidance as to where to start?
You probably know and understand how to create a "Hello World" style program in Java.
Now think - how would you go about having that same program print 5 times "Hello World"?
After that, think about how you would make it write N times "Hello World".
After that, think about how you would output a series of N stars.
Good luck!
Seems like you should have a variable x equal to the dimension (5). A for loop i that loops from 1-x. In it a for loop j that loops from 1-x. The j loops outputs *, or appends * to a string. After the j loop, the i loop does a new line.
This solution will allow for a square grid of any size.
int size = input;
for (i=0; i<size; i++){
for (j=0; j<size; j++){
// output a single "*" here
}
// output a new line here
}
If I got you right, then it's about a NxN square with a given N. Your question is just about N := 5, but your comments let me assume that you've to program a more general solution.
Split the work that have to be done into more basic and smaller problems:
create a String that contains * N times.
call System.out.println() with the generated String N times
This will work for you as well, but the professor will frown that you found the answer online and did not think of it yourself.
System.out.println("*****\n*****\n*****\n*****\n*****");
Here's how I did it:
class Main {
public static void main(String[] args) {
int size = 25;
int pos = 0;
for(int i = 0; i<size; i++){
if(pos % 5 == 0){
System.out.println();
}
System.out.print("*");
pos++;
}
}
}
If I understood correctly, what you need is a console output with 5 lines of stars.
You can outpt text to console with System.out.print() or System.out.println() with the second option making a line break.
As you have to repeat the output, it is advisable to do enclose the output statement in a loop. Better in a nested loop to separate the x and the y axis.
In order to make the output modifiable - for the case you will need to output a 6x6 or 12x15 square tomorrow without any code modification, I would make the limits of the loop parametrized.
All in all, something like this :
public void printStartSquare(int width, int height){
for(int i = 0; i < height;i++){
for(int j = 0; j < width;j++){
System.out.print("*");
}
System.out.println("");
}
}