How to traverse through the diagonals? [duplicate] - java

This question already has answers here:
Loop diagonally through two dimensional array
(12 answers)
Closed 1 year ago.
It's giving outOfBounds every time. I have tried every possible alteration now but it's not giving the output. The O/P should be 7-4-8-1-5-9-2-6-3
for(int g=n-1; g>=0; g--) {
for(int i=g, j=0; i>=g; i++, j++) {
System.out.print(a[i][j]);
}
System.out.println();
}
for(int g=0; g<n; g++) {
for(int i=0, j=i+g; j<n; i++,j++) {
System.out.print(a[i][j]) ;
}
System.out.println();

I think the first thing you can do is change the i>=g to a better limit.
As you are incrementing i positively, and i is already equal to g, it will keep going up past the limit of the array's bounds. Maybe i<(the limit of your bounds) should solve it.
If I was trying to iterate through a square matrix, I would use only one variable and iterate with a[i][i] to reduce confusion:
for (i=0; i > (your bounds); i++) {
System.out.println(a[i][i]);
}
This is the base logic but you seem to be trying to achieve something a little more advanced, so modify it as you see fit.

Related

Shuffling elements in a Typed Array

I have a typed array with 4 elements and I'm trying to shuffle them. How would I go about it? I'm really close but I think the only problem is I don't know the syntax with dealing with Typed Array.
Here is the code so far:
int correctIndex=0;
for(int i=0; i<4; i++){
int randomShuffle = random.nextInt(4);
if(i==correctIndex){//keep track of the correct answer (which always starts at 0)
correctIndex=randomShuffle;
}
else if(randomShuffle==correctIndex){
correctIndex=i;
}
Drawable hold= questionAnswers.getDrawable(i);
questionAnswers.getDrawable(i)=questionAnswers.getDrawable(randomShuffle);
questionAnswers.getDrawable(randomShuffle)=hold;
}
The problem is only with the last two lines. That obviously doesn't work. Is there a
typedArray.setIndex(index,value)
kind of call?

Creating a changing number grid in 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?

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

How to copy all the elements in an array list, then paste them to the array list? Example provided [duplicate]

This question already has answers here:
How to append the contents of a list at the end of the other list?
(3 answers)
Closed 8 years ago.
I want to copy all elements of ArrayList to the back of the ArrayList. For example, in my ArrayList, there are {1,2,3,4} and I want it to be like this --> {1,2,3,4,1,2,3,4}.
How do I do it?
for (int pos = 0; pos < hand.size (); pos ++)
{
hand.add (hand.get(pos));
}
This gives me an error saying out of memory...
Is there any way to make it work?
Thank you
Your loop looks roughly like:
is pos < hand.size()?
if so, add something to hand
pos++
which means that each time through the loop, pos increases, but hand.size() also increases, and so on. You get the out-of-memory error because the loop runs infinitely, and the list gets too big.
One way to do this:
int length = hand.size();
for (int pos = 0; pos < length; pos++) {
hand.add(hand.get(pos));
}
How about
hand.addAll(new ArrayList<>(hand))
Every time you add an element, the size increases, so the loop never terminates. A simple fix is to save the size in a variable before the loop:
int size = hand.size()(
for (int pos = 0; pos < size; pos ++)
{
hand.add (hand.get(pos));
}
But the simplest way to do it is:
hand.addAll(hand); // Note: It is safe to call addAll() on itself

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