Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 days ago.
Improve this question
How would i do step 2
Create a Java application with 2 players. Imagine that two young pirates came to a squared island 10x10 to find a treasure. They were dropped down in random positions. Each player can move only in four directions(N,S,W,E) but not by diagonals. Objective of the game is to find treasures and then the boat. The player who first found at least one treasure and the boat is a winner. Players should also overcome obstacles and fight with some creatures.
Create a 2D array 10x10 and fill it with zeros. (K /1)
Put randomly 2 players (1 and 2), 4 gold treasures (3), one tunnel hole(4), one boat(5)(should be close to the ocean), 2 creatures (6), 2 monsters (7), 2 adventures (8) in the array. Be sure that all of them get different positions.
How do I continue?
import java.util.*;
public class methodreviewtsk1 {
public static void main(String[] args) {
int array1[][]= new int [10][10];
int player1count = 0;
int player2count = 0;
int goldtresurecount = 0;
int tunnelcount = 0;
int creaturecount = 0;
int monstercount = 0;
int adventurescount = 0;
for (int x = 0; x < 10; x++){
for (int y = 0; y < 10; y++){
array1[x][y]= 0;
System.out.print(array1[x][y] + " ");
}
System.out.println();
}
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Problem with output from a two dimensional array, basically 8 rows and 5 columns, each row represents one athlete, the five colums represent the points they have gained in each task. I have to find out If an athlete went beyond 250 points in a single task. Firstly, I made an integer which counts the number of times the Array has been look at, If the number can be divided by 5 it means the next number is going to be the next row and thus a new athlete, next I created another loop to check all the previous numbers and if any of them goes beyond 250, I add one number to the total + break the cycle. The result I have been getting back is 0, or before I got nothing.
for (i=0; i<8; i++) {
for (j=0; j<5; j++)
if(rezultati[i][j]>0) {
skaits = skaits + 1;
}
else if(skaits % 5==0) {
for (int a=0; a<5; a++) {
if(rezultati[i-a][j-a]>250) {
daudzums = daudzums + 1;
break;
}
}
}
}
realised that the row index should be just i if(rezultati[i][j-a]>250), didnt fix the issue tho
You already have an outer loop that will move to the next row/athlete for you. Simply look at the current value and if it exceeds 250, increment your counter and move to the next athlete with break:
int daudzums = 0;
int[][] rezultati = new int[8][5];
// ... populate zezultati somehow ...
for (int i=0; i<rezultati.length; i++) {
for (int j=0; j<rezultati[i].length; j++) {
if (rezultati[i][j]>250) {
daduzums++;
break; // move to next athlete
}
}
}
System.out.println("daudzums = " + daudzums);
After the loops, daudzums will tell you how many athletes had at least one task over 250.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am having an issue with my loops in a game that I created. I have a game board that is a 10 x 10 grid. It is a 3 part challenge. The first part asked for 20 random treasures, which I worked out just fine. Then the second part was adding 20 random trolls. The loop(s) I used gave me 20 treasures and 30 trolls. I AM TERRIBLE AT LOOPS. I have to stay along these lines of code and cannot use break (I am new to Java, but these are my profs rules).
private int width = 10;
private int height = 10;
//Create an array to hold buttons in a 10 by 10 grid
private EmptyButton[] buttons = new EmptyButton[width * height];
Random random = new Random();
int counter = 0;
//Using a while loop when counter is less than number of treasures still hidden
while (counter < game.getNumberStillHidden()) {
//Declare insertion variable and set to random to place buttons randomly
int insertionIndex = random.nextInt(buttons.length);
//Using conditional if button at index is null
if (buttons[insertionIndex] == null) {
//insert a treasure button
buttons[insertionIndex] = new TreasureButton(game, this);
//Use an acumulator for the counter to move on
counter++;
}
}
while (counter < game.getNumberOfTriesLeft()) {
Random randomOne = new Random();
//Declare insertion variable and set to random to place buttons randomly
int insertionIndex = randomOne.nextInt(buttons.length);
if (buttons[insertionIndex] == null) {
//insert a treasure button
buttons[insertionIndex] = new TrollButton(game, this);
//Use an acumulator for the counter to move on
counter++;
}
}
// Loop to add EmptyButton()'s into remaining null indexes within the button array
for (int index = 0; index < buttons.length; index++) {
// if the current index is null
if (buttons[index] == null) {
//add an EmptyButton()
buttons[index] = new EmptyButton(newGame, this);
}
}
// Loop to add all of the contents of the buttonGrid into the gamePanel
for (int index = 0; index < buttons.length; index++) {
//add buttons to panel
gridPanel.add(buttons[index]);
}
When you use
while (counter < game.getNumberOfTriesLeft())
the value of counter is 20 if you have 20 treasures.
You need to reset counter to 0 or use a different one.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
This is the hourglass problem which can be found on Hackerrank website.
Here is a link to the problem : Hourglass
Here is the code that I wrote for the Hourglass problem :
public class Solution
{
public static int hourglass(int[][] a, int n)
{
int max = -999;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
int sum = 0;
boolean flag = false;
if ((i+2) < n && (j+2) < n)
{
sum += a[i][j] + a[i][j+1] + a[i][j+2] + a[i+1][j+1] + a[i+2][j] + a[i+2][j+1] + a[i+2][j+2];
flag = true;
}
if (sum > max && flag == true)
max = sum;
}
}
return max;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = 6;
int[][] a = new int[6][6];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
a[i][j] = scanner.nextInt();
int maxSum = hourglass(a, n);
System.out.println(maxSum);
}
}
My Question
Now, the above code compiled and ran successfully and even passed all the test cases. However, my code takes O(n^2) time (here the size of the matrix is 6, but if the size were n, then it would take O(n^2) time to finish.)
It takes O(n^2) time to create the array, and that I am not concerned about. What I am interested is to optimise the hourglass() method where it takes O(n^2) time to calculate the sum of the hourglass.
So, is there any way to implement the above problem with further optimisation?
Is it possible to solve the problem in O(n) time?
In fact, I tried to solve the problem in O(n) time by removing the inner loop in the hourglass() method but it did not seem to work.
P.S. I do not need a working code, all I need is some pointers to possible improvements (if any) or an algorithm at the most.
Thanks in advance!
Technically, you're solution is already O(n). You're defining "n" as though it were one side of the 2d array, but if you regarded n as a unique placement on your board, n is a combination of row * col. Redefined this way, you can't beat O(n) on this problem.
You can, however, optimize some. You're essentially laying a 3x3 tile onto a 6x6 board. If a placement were to be defined by the top left corner of your 3x3 tile, then you're trying all 36 placements. If you think about it, many of those placements would leave your tile hanging off the edge of the board. You really only need to consider the first 4x4 positions rather than all 6x6 positions. It's still an O(n) solution, but it would cut 36 iterations down to 16.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to code positions in a two-dimensional array in Java with dimension of [n][n]
we have n rows and n columns, so what i want to achieve from this perspective is
(0,0) (0,1) (0,2)
(1,0) (1,1) (1,2)
(2,0) (2,1) (2,2)
I have to get this result ( code row and col to get the result in decimal):
(0) (1) (2)
(3) (4) (5)
(6) (7) (8)
For two-dimensional indices in matrix[i][j], and a linear index in vector[index] the following relation holds.
final int n = 3; // dimension of the columns
int i = ...
int j = ...
int index = i * n + j;
i = index / n;
j = index % n;
Integer division and modulo is used.
(n * row + column) would give you those indices. Is that what you're asking?
Here is the code for it:
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
matrix[i][j] = i*n + j;
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
simple beginner Java question. I just learned how to use arrays and it's still a little confusing to me. My goal is to simply roll a number of dice a number of times and then project it as a sum, frequency, and percentage. I'm sure I'm doing something dumb, but I'm overlooking it!
import javax.swing.JOptionPane;
import java.util.Random;
public class Lab1 {
private static int N = 0;
private static int M = 0;
private static int total = 0;
private static Random rnd = new Random();
public Lab1(){
}
public static void main(String[] args) {
N = Integer.parseInt(JOptionPane.showInputDialog("How many dice would you like to roll?"));
System.out.println("Dice: "+N);
M = Integer.parseInt(JOptionPane.showInputDialog("How many times would you like to roll?"));
System.out.println("Rolls: "+M);
int total[] = new int[(6*Lab1.N)+1];
for (int i=0; i<=total.length; i++)
total[i] = 0;
for (int roll=1; roll<=M; roll++){
N = 1+rnd.nextInt(6);
total[N]++;
}
System.out.printf("%3s%12s%12s\n", "Sum","Frequency", "Percentage " );
for(int k=2; k<total.length; k++);{
int percent = total[k]/(360);
System.out.printf("%3s%12s%12s\n", k, total[k], percent);
}
}
}
From what I can see the question is how can you store the previous roles of the dice. And I believe your problem is with this method:
for (int roll=1; roll<=M; roll++){
N = 1+rnd.nextInt(6);
total[N]++;
}
I would change this to
for (int roll=1; roll<=M; roll++){
total[roll] = rnd.nextInt(6);
}
This will build up an array storing each dice roll - if that is of course what you are looking for...
Two things.
First, this loop will inevitably throw ArrayIndexOutOfBoundsException ("element" total[total.length] is out of bounds)
for (int i=0; i<=total.length; i++)
total[i] = 0;
You should use < instead of <=.
for (int i=0; i<total.length; i++)
total[i] = 0;
Second, this line here:
for(int k=2; k<total.length; k++);{
You have an empty loop here. You should remove the semicolon before the {:
for(int k=2; k<total.length; k++){
Now your code compiles, doesn't throw exceptions on the start, and prints a pretty table.
That's a start.
for(int k=2; k<total.length; k++);{
You need to remove the ; symbol from your loop as 'k' will not be resolved in the loop as you have terminated it. The format is for(x, x, x) {
The next thing to look at now is:
Dice: 1
Rolls: 1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at Lab1.main(Lab1.java:26)
Hint:
total[i] = 0; // this line is the problem.
Look at your <= in the loop.
for (int i=0; i<total.length; i++)
Simply chaging it to < results in this:
Dice: 1
Rolls: 1
Sum Frequency Percentage
2 1 0
3 0 0
4 0 0
5 0 0
6 0 0