0

So far I have an array of tuples that is filled with key,value pairs (keys are ints and values are strings).

val tuple_array = new Array[(K,V)](100)

I want to find a specific key in this array. So far I have tried:

tuple_array.find()

but this requires me to enter a key,value pair. (I think). I want to just search this array and see if the key exists at all and if it does either return 1 or true.(havent decided yet). I could just loop through the array but I was going for a faster runtime.

How would I go about searching for this?

2 Answers 2

3

find requires you to pass a predicate: function returning true if condition is fulfilled. You can use it e.g. like this:

tuple_array.find { tuple =>
  tuple._1 == searched_key
}

It doesn't require you to pass a tuple.

Since this is an array, you have to go through a whole array at worse case (O(n)), there is no faster way (asymptotically) unless your array is sorted and allows usage of a binary-search (which isn't a part of the interface as you never knows if a random array is sorted). Whether you'll do this by iterating manually or through find (or collectFirst) doesn't affect the speed much.

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

Comments

1

but this requires me to enter a key,value pair. (I think).

No it doesn't, check the docs, you can just do:

tuple_array.find(_._1 == theKeyYouWant).map(_._2)

That returns an Option[V] with the value associated with the key if it was present. You then may just do an isDefined to return true if the key existed.

could just loop through the array but I was going for a faster runtime.

Well find just loops.

You may want to use a Map[K, V] instead of an Array[(K, V)] and just use contains


Also, as personal advice, it seems you are pretty new to the language; I would recommend you to pick a course or tutorial. Scala is way more than syntax.

3 Comments

I am pretty new to the language. Appreciate the tips. Will look into more tutorials.
@JohnRon for starters I would invite you to join the official discord server where you may get more interactive help from multiple folks :D
I just did - Thank you!

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.