newbee
newbee

Reputation: 33

JAVA array concatenation from two different arrays

How to concatenate each and every number from 2 arrays and then give the output individually of the new no. formed?

Example:

arr1[1,2,3] 
arr2[2,3,5] 
output: [12,13,15,22,23,25,32,33,33,35]

Upvotes: 1

Views: 89

Answers (3)

RaffleBuffle
RaffleBuffle

Reputation: 5455

Here's another way of doing it that doesn't involve using String.

public static void main(String[] args)
{
    int[] arr1 = { 1, 2, 3 };
    int[] arr2 = { 2, 3, 5 };
    int[] arr = concat(arr1, arr2);     
    System.out.println(Arrays.toString(arr));
}

static int[] concat(int[] arr1, int[] arr2)
{
    int i = 0;
    int[] arr = new int[arr1.length * arr2.length];
    for (int n2 : arr2)
    {
        int pow10 = (int) Math.pow(10, nDigits(n2));
        for (int n1 : arr1)
        {
            arr[i++] = n1 * pow10 + n2;
        }
    }
    return arr;
}

static int nDigits(int n)
{
    return (n == 0) ? 1 : 1 + (int) Math.log10(n);
}

Output:

[12, 22, 32, 13, 23, 33, 15, 25, 35]

Upvotes: 3

K_holla
K_holla

Reputation: 134

If you just want to display the contents of the two array in the form you have given above you can always try doing this instead of concatinating it.

public class ArrayQuestion {
public static void main(String[] args) {
    int arr1[] = {1,2,3};
    int arr2[] = {2,3,5};
    for(int i=0;i<arr1.length;i++) {
        for(int j=0;j<arr2.length;j++) {
            System.out.print(arr1[i]);
            System.out.print(arr2[j]);
            System.out.println();
        }
    }

}

}

Output : 12 13 15 22 23 25 32 33 35

Upvotes: 2

Stardust
Stardust

Reputation: 1029

Use a for loop inside of a for loop. Then concatenate the item from arr and the item from arr2. I used an ArrayList but you could use a normal array if you know the resultant length of the array.

    String[] arr = new String[]{"1", "2", "3"};
    String[] arr2 = new String[]{"2", "3", "5"};
    List<String> res = new ArrayList<>();

    for (int i = 0; i < arr.length; i++){
        for (int j = 0; j < arr2.length; j++) {
            res.add(arr[i] + arr2[j]);
        }
    }

    System.out.println(res.toString());

The result is:

[12, 13, 15, 22, 23, 25, 32, 33, 35]

Upvotes: 2

Related Questions