0

I have the below Array with me.

scala> var a1 =Array(1.1,2.4,3.6)
a1: Array[Double] = Array(1.1, 2.4, 3.6)

I need to get the index from this array based on the input value as below.Basically, I need two index for a three element array.

For ex- all the input between 1.1 and 2.4 should be in first bucket. and all the input between 2.5 and 3.6 should be in second bucket.

> 1.1 -> 0
> 1.5 -> 0
> 2.4 -> 1
> 3.5 -> 1
> 3.6 -> 1

I was trying this using a1.indexWhere(x <= _). But this will result in the last item ie, 3.6 will fall in 3rd index.

Is there any simple way to achieve this ?

8
  • I do not understand the logic of the expected output. Can you clarify how that index is computed? Commented May 21, 2020 at 13:05
  • 1
    If I understand correctly given x you want the index of the value that is <= x? What happens if x is < the first element in the array or larger than the last element? Commented May 21, 2020 at 13:25
  • I have edited the question. Commented May 21, 2020 at 13:28
  • For ex- all the input between 1.1 and 2.4 should be in first bucket. and all the input between 2.5 and 3.6 should be in second bucket. Commented May 21, 2020 at 13:30
  • @Terry then it should fall in first and last bucket respectively. Thats what I am trying to get here. Commented May 21, 2020 at 13:32

2 Answers 2

1

Scala doesn't have a function for that behavior exclusively. Try this simple solution:

val tempIndex = a1.indexWhere(x <= _)
if (tempIndex == a1.length - 1) tempIndex - 1 else tempIndex

Test it here

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

Comments

1

Try something like this. For anything not in a bucket you will get -1.

a1.zip(a.tail).indexWhere{ case (min, max) => x > min && x <= max}

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.