0

I want to access elements of a list within one list and check whether the elements are greater than a minimum value. Example: List[([1,2],0.3), ([1.5,6],0.35), ([4,10],0.25), ([7,15],0.1)]
Let the minimum value: 1
The result should be: List[([1,6],0.65), ([4,10],0.25), ([7,15],0.1)]
As 1.5-1 is less than minimum value 1, it will merge the elements [1,2],0.3) and ([1.5,6],0.35) as [1, 6], 0.65, meaning it will take the 1st element of the inside list and last element of the 2nd element of the outside list and the 2nd element of the outside list will be added (0.3+0.35). This will be done for all elements of the outside list. The code I tried is written below:

def reduce (d1:List[(Interval, Rational)]): List[(Interval, Rational)] =
{
    var z = new ListBuffer[(Interval, Rational)]()
    def recurse (list: List[(Interval, Rational)]): Unit = list match { 
        case List(x, y, _*) if ((y._1_1 - x._1_1) < min_val) => 
           val i = x._1_1; y._1_2 
           val w = x._2 + y._2
           z += (i,w)
          else
           z += x
           recurse(list.tail)
        case Nil =>
   }
   z.toList
}  

But this is not working. Please help me to fix this.

5
  • it's not really clear what you're trying to filter; in your desired result where does ([1,6],0.65) come from? it's not present in the original list... Commented Sep 21, 2016 at 7:36
  • Please read about MCV code examples. Commented Sep 21, 2016 at 7:36
  • I have edited the question. Commented Sep 21, 2016 at 7:43
  • If you have a list of elements a,b,c,d, and elements a and b pass the test and get combined into element ab, what is the next test? Do you test ab with c or do you skip ab and test c against d? Commented Sep 21, 2016 at 7:49
  • I do test ab with c. Commented Sep 21, 2016 at 7:59

1 Answer 1

2

OK, what you've written really isn't Scala code, and I had to make a few modifications just to get a compilable example, but see if this works for you.

type Interval = (Double,Double)
type Rational = Double
def reduce (lir:List[(Interval, Rational)]): List[(Interval, Rational)] = {
  val minVal = 1.0
  lir.foldLeft(List.empty[(Interval, Rational)]){
    case (a, b) if a.isEmpty => List(b)
    case (acc, ((i2a, i2b), r2)) => 
      val ((i1a, _), r1) = acc.head
      if (i2a - i1a < minVal) ((i1a, i2b), r1 + r2) :: acc.tail
      else ((i2a, i2b), r2) :: acc
  }.reverse
}

Test case:

reduce(List( ((1.0,2.0),0.3), ((1.5,6.0),0.35), ((4.0,10.0),0.25), ((7.0,15.0),0.1) ))
// result: List[(Interval, Rational)] = List(((1.0,6.0),0.6499999999999999), ((4.0,10.0),0.25), ((7.0,15.0),0.1))
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.