0

basically I want to be able to store a 2D array such as this

int [][] preferredMoves = {
            {0,0}, {0, arrLength}, {length%2, arrLength},
            {0, length%2}, {arrLength, 0}, {0, length%2}, 
            {arrLength, arrLength}, {length%2, length%2},
            {arrLength, length%2}, {length%2, 0}
    };

In a single

int [] moves; 

array.

I'm sure this is possible since I'm just storing a list..., but I can't seem to find information on this anywhere... or maybe its not possible?

EDIT I am dealing with matrices. I want to store the list in a single array to then return that array to use it elsewhere.

So then every time I call it, all I have to do is something like this...

int row = Computer.moves()[0];
    int col = Computer.moves()[1];

I also need to loop through that single array, which contains the 2D array multiple times..

2
  • What keeps you from using an ArrayList<int[][]>? Commented Oct 2, 2015 at 22:17
  • you actually gave me an idea @Hips Commented Oct 2, 2015 at 22:42

2 Answers 2

3

Not sure if this is what you meant, but you could drop the internal { ... } to convert this to a one-dimensional array:

int [] moves = {
        0, 0, 0, arrLength, length % 2, arrLength,
        0, length % 2, arrLength, 0, 0, length % 2, 
        arrLength, arrLength, length % 2, length % 2,
        arrLength, length % 2, length % 2, 0
};

And you can translate 2D indexes (i, j) to 1D index k using the formula:

k = i * 2 + j;
Sign up to request clarification or add additional context in comments.

3 Comments

I don't quite understand this, would you mind explaining a little?
I don't quite understand your question. Can you please add more examples of your desired behavior?
Well I wanted to add that List to another List in order to loop through it as many times as I needed. I used an ArrayList<int[]> to do this. But then it got messy because I also wanted length to decrement which is impossible and I didn't realize until last minute... I had to redo my method a different way. Thanks though! @janos
0

Janos' answer is probably what you want. Alternatively you could create a class, e.g. Pair, and store it in a Pair[] array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.