Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that an array contains a particular value in Scala 2.8?

Tags:

arrays

scala

I've got an array A of D unique (int, int) tuples.

I need to know if the array contains (X, Y) value.

Am I to implement a search algorithm myself or there is a standard function for this in Scala 2.8? I've looked at documentation but couldn't find anything of such there.

like image 850
Ivan Avatar asked Oct 07 '10 00:10

Ivan


People also ask

How do you check if an array contains a specific value?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

How do you check if an element is in a list Scala?

contains() function in Scala is used to check if a list contains the specific element sent as a parameter. list. contains() returns true if the list contains that element.

How do you select a value in an array?

You select a value from an array by referring to the index of its element. Array elements (the things inside your array), are numbered/indexed from 0 to length-1 of your array.


2 Answers

That seems easy (unless I'm missing something):

scala> val A = Array((1,2),(3,4)) A: Array[(Int, Int)] = Array((1,2), (3,4))  scala> A contains (1,2) res0: Boolean = true  scala> A contains (5,6) res1: Boolean = false 

I think the api calls you're looking for is in ArrayLike.

like image 71
huynhjl Avatar answered Sep 24 '22 18:09

huynhjl


I found this nice way of doing

scala> var personArray = Array(("Alice", 1), ("Bob", 2), ("Carol", 3)) personArray: Array[(String, Int)] = Array((Alice,1), (Bob,2), (Carol,3))  scala> personArray.find(_ == ("Alice", 1)) res25: Option[(String, Int)] = Some((Alice,1))  scala> personArray.find(_ == ("Alic", 1)) res26: Option[(String, Int)] = None  scala> personArray.find(_ == ("Alic", 1)).getOrElse(("David", 1)) res27: (String, Int) = (David,1) 
like image 41
Suganthan Madhavan Pillai Avatar answered Sep 25 '22 18:09

Suganthan Madhavan Pillai