Tuesday 15 September 2015

scala - Method that add and remove an element from a List -



scala - Method that add and remove an element from a List -

i'm writing method take list: list[(string, int)] , x:(string, int) , n: int parameters , homecoming list[(string, int)] list parameter represents input list, x element represents element add together list, n represents maximum dimension of list.

the method has next behavior:

first of check if list has n elements. if list has less n elements, method add together x elements list. otherwise if list contain elements less x, method remove minimum element list, , add together x element list.

i've implemented method following:

def method(list: list[(string, int)], x: (string, int), n: int) = { if(list.size < n) list :+ x else { var index = -1 var min = 10000000//some big number for(el <- 0 list.size) { if(list(el)._2 < x._2 && list(el)._2 < min) { min = list(el)._2 index = el } } if(index != -1) { val newlist = list.drop(index) newlist :+ x } else list } }

exist way express behavior in more clean way??

first, corrected version of posted (but appears, not intended)

def method(list: list[(string, int)], x: (string, int), n: int) = { if(list.size < n) list :+ x else { var index = -1 for(i <- 0 until list.size) { val el = list(i) if(el._2 < x._2) index = } if(index != -1) { val (before, after) = list.splitat(index) val newlist = before ++ after.tail newlist :+ x } else list } }

and tests

val l1 = list(("one", 1)) val l2 = method(l1, ("three", 3), 2) //> l2 : list[(string, int)] = list((one,1), (three,3)) val l3 = method(l2, ("four", 4), 2) //> l3 : list[(string, int)] = list((one,1), (four,4)) val l4 = method(l2, ("zero", 0), 2) //> l4 : list[(string, int)] = list((one,1), (three,3))

neater version (but still not meeting spec mentioned in comment op)

def method(list: list[(string, int)], x: (string, int), n: int) = { if (list.size < n) list :+ x else { val (before, after) = list.span(_._2 >= x._2) if (after.isempty) list else before ++ after.tail :+ x } }

another version removes minimum, if that's less x.

def method(list: list[(string, int)], x: (string, int), n: int) = { if (list.size < n) list :+ x else { val smallest = list.minby(_._2) if (smallest._2 < x._2) { val (before, after) = list.span(_ != smallest) before ++ after.tail :+ x } else list } }

and test results

val l1 = list(("one", 1)) val l2 = method(l1, ("three", 3), 2) //> l2 : list[(string, int)] = list((one,1), (three,3)) val l3 = method(l2, ("four", 4), 2) //> l3 : list[(string, int)] = list((three,3), (four,4)) val l4 = method(l2, ("zero", 0), 2) //> l4 : list[(string, int)] = list((one,1), (three,3))

but in comment, improve utilize method processes whole sequence of xs , returns top n.

list scala collections

No comments:

Post a Comment