0

say I have a 1D array like

int[] array1d = {1,2,3}

I would like to convert it into 2D array2d[3][2] which holding 2 int that are different. E.g.:

1  2
1  3
2  3

currently I made this

int[] array1d = new int[3];
        array1d[0] = 1;
        array1d[1] = 2;
        array1d[2] = 3;

int[][] array2d = new int[3][2];

for (int i=0; i<3; i++) {
            for (int j=0; j<2; j++) {
                array2d[i][j] = array1d[j];
            }
        }

but it gives me only 1,2.

2
  • Have you thought about what kind of algorithm you want to use? Also, what if your array is 1,1,2? What if it's 1,2,3,4? Commented Feb 25, 2016 at 18:42
  • the 1d arrays I use and want to covert into 2d array contain int that are different as the second one you write 1,2,3,4 and if it like that I want the output to be 1,2 1,3 1,4 2,3 2,4 3,4 I am new to this and I can't make it Commented Feb 25, 2016 at 18:46

2 Answers 2

1

Generally speaking, what you want is called combinations (in your example, of size 2 taken from a 3-sized array). So, order does not matter (e.g. [1, 2] equals [2, 1]).

As already specified in the comments, you should consider a more general solution and one can be found here. Besides the actual code, you will also find a code reviews from Codereview community.

Sign up to request clarification or add additional context in comments.

Comments

0

i have done this using random numbers.try this code

` import java.util.Random;

     public final class RandomInteger {

   public static void main(String... aArgs){

    Random randomGenerator = new Random();  
    int[] array1d = new int[3];
    array1d[0] = 1;
    array1d[1] = 2;
    array1d[2] = 3;
    int[] array2d = new int[3][2];
    int randomInt;
    for (int i=0; i<3; i++) {
          for (int j=0; j<2; j++) {
              randomInt = randomGenerator.nextInt(3);
              array2d[i][j] = array1d[randomInt];
                                   }
                            }

                                              }
                                    }    

`

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.