3

I have a matrix in terms of a 2D array and another 1-D array. I am taking one element from the matrix and checking whether it exists in the array. Following is the code.

val array_intrval = Array.ofDim[Int](10)
var joint_matrix = Array.ofDim[Int][Int](5)(2)
for(i <- 0 to 4) {
  for (j <- 0 to 1) {
    var a = joint_matrix(i)(j)

After this, I want to check whether a exists in array_intrval, if not add a in array_intrval and then check whether there are some elements which is less than or equal to a. If yes, also put them in array_intrval. If a does exists in array_intrval, skip a and check for next element in joint_matrix.

I am a beginner in Scala and not able perform this. Any help regarding this will be highly appreciated.

7
  • "I am a beginner in Scala and not able perform this." So you need to learn some stuff. Where exactly are you stuck here? Look at find (to locate a) and filter (to return other elements less than a). There are some ambiguities in your description - if an element is added from a previous iteration but also matches on this iteration, do you add it again? If there are more than one element matching a do you add a multiple times? Note if you do this, then array_intrval may be too small Commented Jul 13, 2017 at 9:38
  • I just modified the question. So you need to learn some stuff Obviously I am in the process. Thank you for the hint. I will check find and filter. Commented Jul 13, 2017 at 9:43
  • I assume you mean 0 to 4 and 0 to 1, as Scala has zero-based arrays. Commented Jul 13, 2017 at 9:43
  • If a does exists in array_intrval, skip a and check for next element in joint_matrix. Commented Jul 13, 2017 at 9:45
  • Yes. sorry, didn't read the question closely enough. Commented Jul 13, 2017 at 9:46

1 Answer 1

4

Take a look at the documentation of Array class. You'll find many useful methods there. For ex., a method called contains can be used to check if a certain element exists in the array or not.

scala> val array_intrval = Array.ofDim[Int](10)
array_intrval: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

scala> array_intrval(1) = 2

scala> array_intrval
res1: Array[Int] = Array(0, 2, 0, 0, 0, 0, 0, 0, 0, 0)

scala> array_intrval.contains(2)
res3: Boolean = true

scala> array_intrval.contains(0)
res4: Boolean = true

scala> array_intrval.contains(5)
res5: Boolean = false
Sign up to request clarification or add additional context in comments.

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.