How to declare and assign an array without the app crashing? - java

Basically, I'm implemeting a reversi app for android for my year 13 coursework and this snippet of code is meant to setup the board which is shown here as an array of the class position. However, when run, the app crashes.
Position[][] board = new Position[7][7]; //declaring the board//
for(int n = 0; n < 8; n ++){
...
for(int i = 0; i < 8; i++ ){
final ImageView button = new ImageView(this);
final int countN = n;
final int countI = i;
board[countI][countN].isPositionEmpty = true; //assigning a value//
Any help would be much appreciated!! thanks in advance!

You've only allocated a 7x7 array, but you're trying to use it as an 8x8 array.
Change to use:
Position[][] board = new Position[8][8];
Or preferably, have a constant which is used in multiple places:
private static final int BOARD_SIZE = 8;
...
Position[][] board = new Position[BOARD_SIZE][BOARD_SIZESIZE];
for (int i = 0; i < BOARD_SIZE; i++)
{
...
}
An array allocation like this:
Foo[] array = new Foo[size];
creates an array with size elements; valid indexes are in the range 0 to size - 1 inclusive.

You have to insantiate every index of your matrix too.
for(int i = 0; i < 8; i++ ){
board[countI][countN] = new Position();
board[countI][countN].isPositionEmpty = true; //assigning a value//
}

// Bad:
Position[][] board = new Position[7][7];
for(int i = 0; i < 8; i++ ){
...
// Better:
Position[][] board = new Position[8][8];
for(int i = 0; i < 8; i++ ){
...
// Best:
Position[][] board = new Position[8][8];
for(int i = 0; i < board[0].length; i++ ){
...
PS:
You not only need to initialize the array (allocate space for each row and each column of your "container"); you*also* need to initialize each element of the array (e.g. "array[i][j] = new Position()").

Your for loop goes from 0 to 7 which is actually 8 cells. So you need 8 position objects.
Position[][] board = new Position[8][8]
or if you want it to be a 7 by 7 board you need to stop at the 6th index
for (int i =0; i <7 ; i++)

Related

Creating a multi-dimensional String array from a method array parameter

I am attempting to solve a semi-difficult problem in which I am attempting to create an array and return a 3 dimensional array based on the parameter which happens to be a 2 dimensional int array. The array I'm attempting to return is a String array of 3 dimensions. So here is the code:
public class Displaydata {
static String[][][] makeArray(int[][] dimensions) {
String myArray[][][];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[][][] = new String[i][j][]; //getting error here.
}
}
return myArray;
}
static void printArray(String[][][] a) {
for (int i = 0; i < a.length; i++) {
System.out.println("\nrow_" + i);
for (int j = 0; j < a[i].length; j++) {
System.out.print( "\t");
for (int k = 0; k < a[i][j].length; k++)
System.out.print(a[i][j][k] + " ");
System.out.println();
}
}
}
public static void main(String[] args) {
int [][] dim = new int[5][];
dim[0] = new int[2];
dim[1] = new int[4];
dim[2] = new int[1];
dim[3] = new int[7];
dim[4] = new int[13];
dim[0][0] = 4;
dim[0][1] = 8;
dim[1][0] = 5;
dim[1][1] = 6;
dim[1][2] = 2;
dim[1][3] = 7;
dim[2][0] = 11;
for (int i = 0; i < dim[3].length;i++)
dim[3][i] = 2*i+1;
for (int i = 0; i < dim[4].length;i++)
dim[4][i] = 26- 2*i;
String[][][] threeDee = makeArray(dim);
printArray(threeDee);
}
}
As you can see from the source code, I'm getting an error when I try to create an instance of my 3-dimensional array which I'm attempting to return. I'm supposed to create a three dimensional array with the number of top-level rows determined by the length of dimensions and, for each top-level row i, the number of second-level rows is determined by the length of dimensions[i]. The number of columns in second-level row j of top-level row i is determined by the value of dimensions[i][j]. The value of each array element is the concatenation of its top-level row index with its second-level row index with its column index, where indices are represented by letters : ‘A’ for 0, ‘B’ for 1 etc. (Of course, this will only be true if the indices don’t exceed 25.) I don't necessarily know where I'm going wrong. Thanks!
You should not be initializing the array on every iteration of the loop. Initialize it once outside the loop and then populate it inside the loop.
static String[][][] makeArray(int[][] dimensions) {
String[][][] myArray = new String[25][25][1];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[i][j][0] = i + "," + j;
}
}
return myArray;
}
I just plugged in values for the size of the first two dimensions, you will need to calculate them based on what you put in there. The 'i' value will always be dimensions.length but the 'j' value will be the largest value returned from dimensions[0].length -> dimensions[n-1].length where 'n' is the number of elements in the second dimension.
Also you will need to set up a way to convert the numbers in 'i' and 'j' to letters, maybe use a Map.
I guess you should initialize the array as
myArray = new String[i][j][]; //getting error here.
I think
myArray[][][] = new String[i][j][]; //getting error here.
should be:
myArray[i][j] = new String[5]; // I have no idea how big you want to go.
And then you can fill in each element of you inner-most array like such:
myArray[i][j][0] = "first item";
myArray[i][j][1] = "second string";
...
I think you should just change that line to:
myArray = new String[i][j][]; //look ma! no compiler error
Also, you would need to initialize myArray to something sensible (perhaps null?)

2D Array Concatenation

I need a method that given input 2D array {{1,2},{3,4}} and (int)row=2; (int)column = 3, will produce a concatenated 2D array {{1,2,1,2,1,2}{3,4,3,4,3,4}}.
My attempt was to use a nested for loop to expand them both horizontally and and vertically, but was unsuccessful. This is what I have so far:
int row = 2;
int column = 5;
int count = 0;
int[][] list = {{12,3},{3,4}};
int [][] renewed = new int[row*list.length][column*list[0].length];
for (int l = 0; l<list.length; l++) {
for (int k = 0; k<renewed.length; k+= list.length) {
renewed[l+k] = list[l];
}
}
System.out.println(Arrays.deepToString(renewed));
}
}
^This produces list[][] expanded vertically, for the first column
int row = 2;
int column = 4;
int[][] list = {{12,3},{3,4}};
int [][] renewed = new int[row*list.length][column*list[0].length];
for (int i = 0; i<list[0].length; i++) {
for (int j = 0; j<renewed[0].length; j+=list[0].length) {
renewed[0][j+i] = list[0][i];
}
}
System.out.println(Arrays.toString(renewed[0]));
}
^This produces list[][] expanded horizontally, for the first row;
So how can I concatenate these two methods in order to produce a method that expands BOTH horizontally and vertically?
I think the easiest way is to iterate over every position in the new array and use the remainder operator % to get the right entry of the original.
int[][] list = {{1,2},{3,4}};
int row = 2;
int column = 5;
int [][] renewed = new int[row*list.length][column*list[0].length];
for (int i = 0; i < renewed.length; i++) {
for (int j = 0; j < renewed[0].length; j++) {
renewed[i][j] = list[i % list.length][j % list[0].length];
}
}
System.out.println(Arrays.deepToString(renewed));

Getting indexes from two-dimensional array

How can I get int a = 400; int b = 100; from 2-dimensional array 1000 x 1000 in Java, for example, mass[400][100] (row 400, column 100)? I found element in array and need numbers of his row/line and column. How can I get this numbers? Thanks.
Are you asking how to get the dimensions of an array?
If a is new int[400][100]; then you can get 400 by doing a.length and 100 by doing a[0].length.
If you need to find the position in the array based on the value, you have no other option but to brute-force loop through the whole array, breaking out when you find the first match:
int[][] massiveArray = new int[1000][1000];
final int valueTofind = 27;
// assign the value to find at position (400, 100)
massiveArray[400][100] = valueTofind;
int i_value = -1;
int j_value = -1;
// find the first occurrance of valueTofind by looping through the array
outer: for (int i = 0; i < massiveArray.length; i++) {
for (int j = 0; j < massiveArray[0].length; j++) {
if (massiveArray[i][j] == valueTofind) {
i_value = i;
j_value = j;
break outer;
}
}
}
System.out.println(String.format("First position for %d is at (%d, %d)",
valueTofind, i_value, j_value));
you can Work Around this .. To get a value in 2d array one way to do is
int[][] a = ...;
for (int r=0; r < a.length; r++) {
for (int c=0; c < a[r].length; c++) {
int value= a[r][c];
}
}

Shuffle the order of a 2D array in java

I'm creating my own memory game. Everything is going well so far. Just to let you know I'm using processing for Java. I have created a 2 dim PImage array. This is the code for filling the 2D array:
int g = 0;
for(int i = 0; i < 4; i++) {
for (int j = 0; j < 6; j++) {
if (j % 2 == 0) {
kaart[i][j] = loadImage( g + ".jpg" );
kaart[i][j].resize(vlakGrootte - 1, vlakGrootte - 1);
g++;
} else if (j % 2 == 1) {
kaart[i][j] = kaart[i][j-1];
}
}
}
I want the items in this array to be shuffled. It seems like java collections does not support to shuffle a 2D PImage array? Please correct me if im wrong.
Thanks to you all for helping me out.
1).Shuffle per-outter index :
YourType [][] kaart = new YourType [..][..];
List <YourType[]> list = (List<YourType[]> ) Arrays.asList(kaart);
Collections.shuffle(list);
kaart = (YourType[][]) list.toArray(new YourType[0][]);//convert back to a array
// just for checking
for(YourType[] k:kaart ){System.out.println(Arrays.toString(k));}
Replace YourType with the type of kaart.
2). Shuffle per-Outter+Inner index :
YourType[][] kaart = new YourType[..][..];
List<YourType[]> temp = new ArrayList<>();
for(YourType[] k:kaart ){
List <YourType> list = (List<YourType> ) Arrays.asList(k);
Collections.shuffle(list);//shuffle
YourType[] tempArray = (YourType[]) list.toArray();
temp.add(tempArray);
}
Collections.shuffle(temp);
kaart= (YourType[][]) temp.toArray(new YourType[0][]);//convert back to a array
// just for checking
for(YourType[] k:kaart ){System.out.println(Arrays.toString(k)); }
Replace YourType with the type of kaart.
3). Shuffle in The easiest way:
Just put all elements into a single List then call Collections.shuffle()
I would do this the same way you would deal those cards in real world. First you shuffle the deck:
ArrayList<Integer> pieces = new ArrayList<Integer>();
for (int i = 0; i < 4 * 6 / 2; i++) {
for (int j = 0; j < 2; j++) {
pieces.add(i);
}
}
Collections.shuffle(pieces);
Then you deal cards out of shuffled deck:
for(int i = 0; i < 4; i++) {
for (int j = 0; j < 6; j++) {
int g = pieces.remove(pieces.size()-1);
kaart[i][j] = loadImage( g + ".jpg" );
kaart[i][j].resize(vlakGrootte - 1, vlakGrootte - 1);
}
}

Create a 2D array and initialize every element to be the value of i * j where i and j are the 2 indices (for instance, element [5][3] is 5 * 3 = 15)

I am truly stuck here on how to do this. I got as far as creating the 10x10 array and making variables i and j - not far at all. I thought about the use of loops to initialize every element, but I just don't know how to go about doing it. Any help is appreciated, thanks.
public class arrays {
public static void main(String[] args) {
int[][] array = new int[10][10];
int i = 0, j = 0;
}
}
I was thinking of using a do while loop or for loop.
Psuedo-code:
for i = 0 to 9
for j = 0 to 9
array[i][j] = i*j
Converting this to Java should be a snap.
Create two nested for loops, one for i, and one for j, looping over all valid indices. In the body of the inner for loop, assign the computed product to the 2D array element.
You will need two for loops inside each other:
int[][] array = new int[10][10];
for (int x = 0; x < array.length; ++x)
{
for (int y = 0; y < array[y].length; ++y)
{
int product = x * y;
// put the value at the right place
}
}
You can read this as:
For each x value, iterate over the ten y values and do...
int [][] array = new int[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
//initialize every element
array[i][j] = i + j;
}
}

Categories