Reputation: 509
I have three lists inside a list.
val l = List(List(1, 0, 0), List(1, 1, 0), List(1, 0, 1))
Now the problem is to add the values inside list with condition check, basically I need to check each element wise values and if they are equal do some calculation if not do another calculation. I tired to group same element positions using transpose, then map the result and make comparison of current element with previous element in the list, I think the last part is where I am not clear.
EDIT:
Some more explanation, let say we have list like this
List(List(i1, j1, k1), List(i2, j2, k2), List(in, jn, kn))
if i1 is equal to i2 then 1+i1+ i2*0.5 and j1 equal to j2 then 1+j1+j2*.0.5 and it goes upto kn and the second condition is if they are not equal i1 is not equal to i2 then it is a decrease, it will be i1+i2*0.5
hope this is explanation helps
Output I looking for
List[Double] = List(2.5, 0.5, 0.5)
Upvotes: 0
Views: 744
Reputation: 1099
lst.transpose.map(v=>if(v.forall(_==v.head)) v.sum*0.5+1 else v.sum*0.5))
or
lst.transpose.map(v=>if(v.exists(_!=v.head)) v.sum*0.5 else v.sum*0.5+1)
or
lst.transpose.map(v=>if(v.find(_!=v.head)!=None) v.sum*0.5 else v.sum*0.5+1)
These are in general, can be used for two different expressions
to be evaluated for the two different cases ie., all elements equal or not equal
in the lists after calling transpose
function.ie.,
lst.transpose.map(v=>if(v.exists(_!=v.head))
(Expression1 in terms of elements in v)
else (Expression2 in terms of elements in v) )
In Scala REPL:
for,
val lst = List(List(1, 0, 0), List(1, 1, 0), List(1, 0, 1))
scala> lst.transpose.map(v=>if(v.forall(_==v.head)) v.sum*0.5+1 else v.sum*0.5)
res23: List[Double] = List(2.5, 0.5, 0.5)
scala> lst.transpose.map(v=>if(v.exists(_!=v.head)) v.sum*0.5 else v.sum*0.5+1)
res24: List[Double] = List(2.5, 0.5, 0.5)
scala> lst.transpose.map(v=>if(v.find(_!=v.head)!=None) v.sum*0.5 else v.sum*0.5+1)
res25: List[Double] = List(2.5, 0.5, 0.5)
Upvotes: 1
Reputation: 1428
You can use map and pattern matching
val list = List(List(1, 0, 0), List(1, 1, 0), List(1, 0, 1))
val result = list.transpose.map {
case sublist if sublist.forall(sublist.head == _) => 1+0.5*sublist.sum
case sublist => 0.5*sublist.sum
}
Upvotes: 0
Reputation: 51271
Your description is still very confusing but I think maybe something like this is what you're after.
val lst = List(List(1, 0, 0), List(1, 1, 0), List(1, 0, 1))
lst.transpose
.map(sublst => sublst.sum*0.5 + (if (sublst.forall(_==sublst.head)) 1 else 0))
//res0: List[Double] = List(2.5, 0.5, 0.5)
If all the elements of the sub-list are the same, add 1
to the calculation, else add 0
.
Upvotes: 1