Creating a changing number grid in Java - java

I'll preface this with the fact that this is for homework, so I am just looking for help in which direction to go for solving this problem.
Essentially, I'm supposed to use for-loops to create a number grid that iterates until a max is reached, then wraps around.
Ex:
012345
123450
234501
345012
450123
501234
I don't know why, but I can't figure this out for the life of me. I'm not allowed to use things like if-statements, so I'm really confused.
My code so far is just the for-loops that iterate but they don't iterate the way they're supposed to:
public static void square(int min, int max) {
for(int i = min; i <= max; i++){
System.out.print(i);
for(int j = min + 1; j <= max; j++){
System.out.print(j);
}
System.out.println();
}
}
Current Output:
012345
112345
212345
312345
412345
512345
I understand that my code isn't setting the grid up to iterate the way I want it to, I'm just not sure of what direction to go down to fix it. I'm probably overthinking this, but I'm lost. Any ideas?

Related

Sorting an ArrayList object populated with custom objects with two data fields each

stuck on a problem with sorting ArrayLists. I'm sure the answer is really easy and something I just keep overlooking, but I've been working on this for the past many hours straight and just need someone else's eyes.
It's a lab project that required us to make 3 custom classes; Applications.java, Rectangle.java, and RectangleList.java and I have to sort an ArratList that contains Rectangle objects with length and width data fields.
The order is (W1, L1) > (W2, L2) if and only if [(W1 > W2) or (W1 = W2 and L1 > L2)
I'm not sure what bits of code would be necessary to look at for help, but I know I'm supposed to use for loops and no outside pre-made methods for sorting. I'm supposed to run a for loop through each index and compare that index to each other index and then switch values. My current bit of code either doesn't do anything (no sorting happens) or it throws up duplicates. Just lots of stuff going on and I've erased everything and started over many times. Not sure where to go from here, and I no longer know how to think of the problem.
Thanks, just let me know what you need to see and I'll try posting it.
Edit note: We aren't allowed to use comparator or comparable or any other compare method I don't know about yet.
/////////////////////////////////////////////////////////////////////////////
I figured it out!
for(int index = 0; index < (list.boxes.size()-1); index++){
minIndex = index;
for(int index2 = index+1; index2 < list.boxes.size(); index2++){
if((list.boxes.get(minIndex).getLength() > list.boxes.get(index2).getLength()) || (list.boxes.get(minIndex).getLength() == list.boxes.get(index2).getLength() && list.boxes.get(minIndex).getWidth() > list.boxes.get(index2).getWidth())){
minIndex = index2;
}
}
list.boxes.set(index, list.boxes.set(minIndex, list.boxes.get(index)));
}
I think the comparator could help you :
Collections.sort(rectList, new Comparator<Rectangle>() {
#Override
public int compare(Rectangle rect1, Rectangle rect2) {
if(rect1.width > rect2.width)
return -1;
else if(rect1.width == rect2.width && rect1.length > rect2.length)
return -1;
else if(rect1.width == rect2.width && rect1.length == rect2.length)
return 0;
else
return 1;
}
});
If you are using Java8 then Lambda expression can be used to make the code smaller.

Trouble understanding dynamic programming

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.

N amount of boxes within boxes being drawn

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

Knapsack Dynamic Programming

this is a typical Knapsack problem requiring dynamic programming and there is no constraint on the supply of items. I've been working on this for my class and I tried to play around with the algorithm for hours and I'm still not getting there.
public static int fitBackPack(int[] W, int[] V, int T){
int[] Opt = new int[T+1];
Opt[0]=0;
for (int i=1; i<=T; i++){
int localMax=0;
int globalMax=0;
for (int j=0; j<W.length; j++){
if (W[j]<=i){
localMax = (T%W[j]<=W[j]) ? V[j] : V[j]+Opt[T-W[j]];
globalMax = (localMax>=globalMax) ? localMax : globalMax;
}
}
Opt[i]=globalMax;
}
//debugging purposes
for (int k=0; k<Opt.length; k++){
System.out.println("Opt["+k+"] = "+Opt[k]);
}
return Opt[T];
}
This method is supposed to take a sorted array of W and V, containing the weight and the value of the item respectively, and an integer T representing the max weight. For my output, everything up until T=21 works, however, after that it just seems to be working like a greedy algorithm, which is completely not what I was hoping for. Any hints will be appreciated, thanks!
Hints:
(x % y <= y) == true
Every now and then a truth table through your conditions with test cases will help you find these.
Better still set up some automated tests for general usage and edge cases.
Since your algorithm is acting like a greedy one, you problem is probably on the calculation of localMax (since greedy algorithms look for the highest local value). By looking at your code, you seem to be getting localMax in the wrong way. Hint, see Math.max() function.

Printing a square of stars in Java

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("");
}
}

Categories