2D Tiled Game - Using new bad data - java

In my 2D Tiled game, I have a problem, when I update all the Object from a 2D array in a for loop inside another (looping in the 2D array from top left to bottom right, row by row(like the code below)), If the program is looping at index (5,6) and it need data from the Object under itself, It'll use the new data that he have executed when the loop is at (5,5) but I want to use the all data before the start of the double for loop...
A basical example:
int[][] map = new int[10][10];
for(int x = 0; x < 10; x++)
{
for(int y = 0; y < 10; y++)
{
update(x, y, map);
}
}
// I remember you that it is an example
void update(int x, int y, int[][] m)
{
m[x][y] = 0
if(y > 9) { return; }
m[x][y + 1] = 1
}
It will put instantly the data "1" at (x, 10), without considering that it generate errors...(ArrayOutOfBoundsException...)
How I can make it use the data of the array when he don't started the double loop yet?
I know that it generata ArrayOutOfBoundExecption, and with a single if I can correct it like I done up here
int Water = 1;
int Air = 0;
int[][] map = new int[20][20];
void update()
{
for(int x = 0; x < 10; x++)
{
for(int y = 0; y < 10; y++)
{
tick(x, y, map);
}
}
}
void tick(int x, int y, int[][] m)
{
if(y > m.lenght - 1) { return; }
m[x][y] = Air;
m[x][y + 1] = Water;
}

You are saying that you are iterating your map row by row when you are actually doing it by columns. Try looping first for y and then for x.
Your update method is also wrong. y+1 when y = 9 will try to access map[x][10] which will throw an ArrayOutOfBoundsException. Remember than an array declared as new int[10] has 10 items starting from 0 and ending at position 9.

int Water = 1;
int Air = 0;
int[][] map = new int[20][20];
void update()
{
for(int x = 0; x < 10; x++)
{
for(int y = 9; y >= 0; y--)
{
tick(x, y, map);
}
}
}
void tick(int x, int y, int[][] m)
{
if (y < m[0].length - 1)
m[x][y+1] = m[x][y];
}
Of course, you'll need to make some cells water to begin with, but that should go in the constructor.

Related

What is the Best way to find AND-Product of all the possible pairs of large array?

The given array is too big contains 10^6 elements approx.
Already know traditional way of traversing each possible pair, but i want some more efficient way/trick.
int prod = 0, arr[]= {1,4};
for(int x = 0; x<arr.length;x++) {
for(int y = x;y<arr.length; y++) {
prod += arr[x] & arr[y];
}
}
System.out.println(prod);
// Count the occurrences of each bit
int[] bitcounts = new int[32];
for (int x=0; x<arr.length; ++x) {
int val = arr[x];
for (int bit=0; bit<32; ++bit) {
if ((val & (1<<bit)) != 0) {
bitcounts[bit]++;
}
}
}
// If a bit appears in n entries, then it appears in n(n+1)/2 pairs
// (counting the pair of each item with itself)
int result = 0;
for (int bit=0; bit<32; ++bit) {
long pairs = ((long)bitcounts[bit]) * (bitcounts[bit]+1) / 2;
result += ((int)pairs) * (1<<bit);
}
return result;
If arr[x]=0, you can skip the whole inner loop for that value of x (since 0&y=0 no matter what y is.
The diagonal is an identity.
prod = 0;
for(int x = 0; x < arr.length; x++) {
int ax = arr[x];
for(int y = x + 1; y <arr.length; y++) {
prod += ax & arr[y];
}
prod += arr[x];
}

how to move an element in an array in java?

Hi I'm learning java an I was wondering how I could move an element in an array from Position X to position Y. irrespective of where X and Y are in the array. Also i would like to close the hole in the array left by moving the element.
Thanks.
This solution makes two assumptions: 1) that both X and Y are less than the length of the array, and 2) the "hole" is only the one value/slot that is moved.
int a[] = new int[];
int x;
int y;
// Populate a, x, and y
int b[] = new int[a.length - 1];
int j = 0;
for (int i = 0; i < a.length; i++)
{
if (i == x)
continue;
else if (i == y)
b[j] = a[x];
j++;
}

How to remove an unnecessary int allocation when converting a two dimensional into a one dimensional array?

Whenever I want to convert an int[][] into an int[] array, I follow the procedure shown underneath.
final int[][] source = new int[3][3];
final int[] array = new int[9];
// I allocate an int that represents the current index of the int[] array.
int index = 0;
// Afterwards I iterate over the `int[][]` array.
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
array[++index] = source[x][y];
}
}
The code does the job, but I want to know if there is a better solution for my problem that effectively eliminates the index variable and even enhances the efficiency of my code.
You can do this with a single loop:
for (int x = 0; x < width; x++) {
System.arraycopy(twoDimensionalArray[x], 0, oneDimensionalArray, x*height, height);
}
We can just directly calculate it
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
oneDimensionalArray[x*height+y] = twoDimensionalArray[x][y];
}
}

Putting random numbers randomly into 2d array

I have a 2d array, and I've set all the cells to a enum type State.SAFE. Now I want to place, lets say 5, of those cells, randomly to State.HIT. So I have:
Random objrandom = new Random();
State[][] playField = new State[5][5];
int w;
for (w = 0; w < 5; w++) { // set all states to SAFE first
int h = 0;
playField[w][h] = State.SAFE;
for (h = 0; h < 5; h++) {
playField[w][h] = State.SAFE;
}
}
for (int i = 0; i < 5; i++) { // try and set 5 states, randomly, to HIT
playField[objrandom.nextInt(5)][objrandom.nextInt(5)] = State.HIT;
}
The problem is every time I run it, all the cells are either still in SAFE state or the Hit states are distributed non randomly, i.e the first row of every column or there are more than 5 HIT states.
If you need exactly 5 cells to be set to HIT you can't use random like that because you may get the same number more than once. This is how I would do it:
public static void main(String[] args) {
State[][] playField = new State[5][5];
setStateToSafe(playField);
List<Integer> hits = getRandomIndices(5);
applyHitStateToIndices(hits, playField);
System.out.println(Arrays.deepToString(playField));
}
private static void setStateToSafe(State[][] playField) {
for (int w = 0; w < playField.length; w++) {
Arrays.fill(playField[w], State.SAFE);
}
}
private static List<Integer> getRandomIndices(int n) {
List<Integer> hits = new ArrayList<>();
for (int i = 0; i < n * n; i++) hits.add(i);
Collections.shuffle(hits);
return hits.subList(0, n);
}
private static void applyHitStateToIndices(List<Integer> hits, State[][] playField) {
for (int i = 0; i < hits.size(); i++) {
int hitIndex = hits.get(i);
int row = hitIndex / playField.length;
int column = hitIndex % playField.length;
playField[row][column] = State.HIT;
}
}
There's a problem with your solution, since the line playField[objrandom.nextInt(5)][objrandom.nextInt(5)]=... might result in the same cell being references twice. I can't be sure if this is the cause of your problem, but it might be at least part of it.
If you wanted to fix that, you'd have to check each random number against the history of already changed cells, and request for a different random in case of double hits.
What I suggest is a completely different approach. Instead of requesting the indices of the row and column of the cell in which to change the value, the random should represent the probability that the values will change.
In other words:
Go over all the cells in the array, generate a random value between 0 and 1 (using nextDouble())
If the value is below the probability that this cell should change (5 cells out of 25 means 5/25 = 0.2 probability = 20%), if so, set the value to State.HIT, otherwise set it to State.SAFE
The code should look something like this:
Random objrandom = new Random();
State[][] playField = new State[5][5];
for (int w = 0; w < 5; w++) {
for (int h = 0; h < 5; h++) {
playField[w][h] = (objrandom.nextDouble() < 0.2d) ? State.HIT : State.SAFE;
}
}
If the small overhead doesn't cause much trouble, then you could do something like this:
Create a class for representing a point on your field.
final class Point {
public final int x;
public final int y;
public Point(final int x, final int y) {
this.x = x;
this.y = y;
}
}
Fill a list with all the possible points, and shuffle it.
List<Point> points = new ArrayList<>();
for (int x = 0; x < 5; x++) {
for (int y = 0; y < 5; y++) {
points.add(new Point(x, y));
}
}
Collections.shuffle(points);
Now the first N (5 in your case) points will be randomized, and 100% not the same.
for (int i = 0; i < 5; i++) {
Point p = points.get(i);
playField[p.x][p.y] = State.HIT;
}

Problems getting matrix to display

this is my 1st time asking for help for programming. Anywho, I need to write a program which find the determinant of a matrix (The determinant code will be made on a later date). Problem being is that I am having trouble getting my matrix to display. It seems that I have the array written correctly, but the output would skip the for loops to write the matrix. Would there be any changes that needs to be done or if theres a certain way that I need to set my array to determine determinants?
public class DetProg {
public static void main(String[] args) {
Scanner a = new Scanner (System.in);
Random mNum = new Random();
System.out.print("Enter matrix size: ");
int num = a.nextInt();
int numX = num;
int numY = num;
int [][] matNN = new int [numX] [numY];
int det = 0;// 0 is the placeholder until det method is inputted.
int n = mNum.nextInt(100)+1;
if (num >= 2)
{
for(int x = 0; x >= numX; x++)
{
for(int y = 0; y >= numY; y++)
{
matNN [x][y] = n;
System.out.println(matNN[x][y] + " ");
}
}
System.out.println("\n");
System.out.println("Determinant of a matrix is " + det);
}
else
System.out.println("Incorrect matrix size. Exiting...");
}
}
In your loops, you are making mistake in placing condition. you wrote x >= numX and y >= numY which will not be satisfied to even start the loop, because your x and y are equal to 0 in the start. it should be as:
for(int x = 0; x <= numX; x++)
{
for(int y = 0; y <= numY; y++)
{
Firstly you need to change your loop conditions.
for (int x = 0; x < numX; x++) {
for (int y = 0; y < numY; y++) {
this will result in proper assignment of values in an array and after this you can proceed further for your code of Determinant of a matrix.

Categories

Resources