3

I would like to check to see if an array contains a value from another array. For example, I would like to check if the array A contains a value from an array B.

I'm looking for any value not one specific value.

2
  • You mean if any of the values in array B appear in array A, or one specific value? Commented May 29, 2020 at 14:12
  • if any of the values in array B appear in A Commented May 29, 2020 at 14:13

6 Answers 6

2

If you're wanting to see if there is any overlap at all between two arrays, you can do this:

fun Array<*>.intersects(other: Array<*>) = any { it in other }

As mentioned in the comments below, this is O(n^2) so with large arrays, prefer:

fun Array<*>.intersects(other: Array<*>) = intersect(other.toSet()).isNotEmpty()

toSet() is only needed if the second collection is an Array rather than an Iterable like List.

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

4 Comments

What does that return? true or false?
True if there is any overlap.
this is O(n^2), if array is big (1000 elements), it will be much slower than converting an array to a hash set
@IR42, I think arrayA.intersect(array2).isNotEmpty() would be O(n). Internally intersect converts each list to a set, then uses retainAll, so it is O(3n) -> O(n).
2

Example:

val a = arrayOf(1, 2, 5, 7, 9, 15)
val b = arrayOf(15, 3, 5, 8)
val c = a intersect b.toList()
if (!c.isEmpty()) {
    println("Arrays have common elements ${c}")
} else {
    println("Arrays do not have common elements")
}

Result:

Arrays have common elements [5, 15]

Implementation intersect in Kotlin use Set:

val set = this.toMutableSet()
set.retainAll(other)
return set

and should be enough for most typical casses, for example if both array have 10 000 000 elements, this take about 8 s.

In case when arrays are very large (e.q. when set of such large number of element doesn't fit in memory), possible solution is do sort arrays, and do something like merge of sorted arrays:

fun hasIntersection(a: IntArray, b: IntArray): Boolean {
    a.sort()
    b.sort()
    var i = 0
    var j = 0
    while (i < a.size && j < b.size) {
        if (a[i] < b[j]) {
            i++
        } else if (a[i] > b[j]) {
            j++
        } else {
            return true
        }
    }
    return false
}

Comments

1

Make sure your array A and B are the same type. then try like the following.

for (i in 0..arrayB.size-1) { 
    arrayA.contains(arrayB[i]); 
} 

1 Comment

I'm looking for any value not one specific value.
1

You can use any and contains methods to check if there is a common element.

val a = arrayOf(1, 2, 5, 7, 9, 15)
val b = arrayOf(15, 3, 5, 8)

println(a.any(b::contains))
// true

Please note: This method is not very efficient. It has a worst case complexity of n^2. One way to improve performance is to convert the array on which look up is done (b in this eg) to a Set

Comments

0

Return true if any value matches

  private fun ArrayList<Int>.isAnyValueMatched(list2:ArrayList<Int> ):Boolean{
        this.forEach { value1->
            list2.forEach {
                value2->
                if (value1==value2) return true
            }
        }
        return false
    }

Or use intersect( Returns a set containing all elements that are contained by both this array and the specified collection)

private fun ArrayList<Int>.isAnyValueMatched(list2:ArrayList<Int> ):Boolean{
        return (this intersect list2).isNotEmpty()
 }

Comments

0
    val arrayOne = arrayOf("a","b")
    val arrayTwo = arrayOf("b", "c")
    val intersectionArray = mutableListOf<String>()

    arrayOne.forEach {
        if (arrayTwo.contains(it)) intersectionArray.add(it)
    }

    //true or false, if the two arrays have any intersect or not
    val arrayOneAndArrayTwoHaveIntersect = intersectionArray.size > 0
    println("Array One contains an element of Array two: $arrayOneAndArrayTwoHaveIntersect")

    //show the actual values that can be found in the two arrays
    if (arrayOneAndArrayTwoHaveIntersect){
        println("\n\nThe element(s) that can be found in the two arrays are as follows: \n")
        intersectionArray.forEach {
            println(it)
        }
    }

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.