0

Arrays may be reverse.

for example:

Int[] a = {1,2,3,4,5};
Int[] b = {9,8,7,6,5};
Int[] c = {3,0,9};

Int[] output = {1,2,3,4,5,6,7,8,9,0,3};

I can use nested loop to achieve it. But is there an easier Algorithm?

  • 1
    Hello. To be honest I don't understand what the merging rules should be. Neither the order seem to be preserved in your output array nor there's a rule that allows/prevents duplicates ("3" is repeated, but "5" or "9" is not). Maybe you could clarify what the rules for the output array should be. – Sebastian Brudzinski May 01 '20 at 12:05

3 Answers3

0

In java i have tried with

int[] array1and2 = new int[array1.length + array2.length];
System.arraycopy(array1, 0, array1and2, 0, array1.length);
System.arraycopy(array2, 0, array1and2, array1.length, array2.length);

Follow this Link. It may help you

Flying Dutchman
  • 365
  • 6
  • 13
0

In kotlin you can achieve this in the following way:

val a = arrayOf(1,2,3,4,5)
val b = arrayOf(9,8,7,6,5)
val c = arrayOf(3,0,9)

val combined = ((a + b.reversed()).distinct()) + ((b + c.reversed()).distinct() - b)
Dennis
  • 818
  • 2
  • 10
  • 23
0

Not sure I got what your requirements are, but here are my assumptions:

  • you can combine two arrays if the last element of the first array is the same as the first element of the second array or the last element of the second array – in the latter case you also need to reverse the second array;
  • when two arrays are combined, the first element of the second array should be skipped (after reversing the array, if needed according to the previous point)
  • if two arrays can't be combined, an empty array is returned

According to those assumptions, here's a possible implementation:

fun combineArrays(a: IntArray, b: IntArray): IntArray =
        when {
            a.last() == b.first() -> a + b.takeLast(b.size - 1)
            a.last() == b.last() -> a + b.reversed().takeLast(b.size - 1)
            else -> intArrayOf()
        }

val a = intArrayOf(1, 2, 3, 4, 5)
val b = intArrayOf(9, 8, 7, 6, 5)
val c = intArrayOf(3, 0, 9)

val result = combineArrays(combineArrays(a, b), c)
println(result.joinToString())

This prints 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 3.

user2340612
  • 10,053
  • 4
  • 41
  • 66