1

I have the following list in input:

val listInput1 = 
  List(
    "itemA,CATs,2,4",
    "itemA,CATS,3,1",
    "itemB,CATQ,4,5",
    "itemB,CATQ,4,6",
    "itemC,CARC,5,10")

and I want to write a function in scala using groupBy and foldleft ( just one function) in order to sum up third and fourth colum for lines having the same title(first column here), the wanted output is :

val listOutput1 = 
      List(
         "itemA,CATS,5,5",
         "itemB,CATQ,8,11",
         "itemC,CARC,5,10"

       )


 def sumIndex (listIn:List[String]):List[String]={

 listIn.map(_.split(",")).groupBy(_(0)).map{ 
  case (title, label) => 
       "%s,%s,%d,%d".format(
         title,
         label.head.apply(1),
         label.map(_(2).toInt).sum,
         label.map(_(3).toInt).sum)}.toList

}

Kind regards

scalacode
  • 1,096
  • 1
  • 16
  • 38
  • What does the `startIndex` have to do with anything? Why are there extra spaces in your input and output? Are they required? – Bob Dalgleish May 25 '18 at 16:05
  • Hello the spaces are not required , this is rather a mistake.startIndex function calculates the finalOutput , after the sum index function concateneates the lengths for lines having the same title, There is a missing function calculating the sum of the 2 lengths for each line before calculating the sart index – scalacode May 25 '18 at 16:07
  • What's wrong with your solution? It seems to work as expected - what is it you'd like to improve about it? – Tzach Zohar May 25 '18 at 19:49

3 Answers3

0

You can solve it with a single foldLeft, iterating the input list only once. Use a Map to aggregate the result.

listInput1.map(_.split(",")).foldLeft(Map.empty[String, Int]) {
  (acc: Map[String, Int], curr: Array[String]) =>
    val label: String = curr(0)
    val oldValue: Int = acc.getOrElse(label, 0)
    val newValue: Int = oldValue + curr(2).toInt + curr(3).toInt
    acc.updated(label, newValue)
}

result: Map(itemA -> 10, itemB -> 19, itemC -> 15)

bmateusz
  • 237
  • 1
  • 7
0

If you have a list as

val listInput1 =
  List(
    "itemA,CATs,2,4",
    "itemA,CATS,3,1",
    "itemB,CATQ,4,5",
    "itemB,CATQ,4,6",
    "itemC,CARC,5,10")

Then you can write a general function that can be used with foldLeft and reduceLeft as

def accumulateLeft(x: Map[String, Tuple3[String, Int, Int]], y: Map[String, Tuple3[String, Int, Int]]): Map[String, Tuple3[String, Int, Int]] ={
  val key = y.keySet.toList(0)
  if(x.keySet.contains(key)){
    val oldTuple = x(key)
    x.updated(key, (y(key)._1, oldTuple._2+y(key)._2, oldTuple._3+y(key)._3))
  }
  else{
    x.updated(key, (y(key)._1, y(key)._2, y(key)._3))
  }
}

and you can call them as

foldLeft

listInput1
  .map(_.split(","))
  .map(array => Map(array(0) -> (array(1), array(2).toInt, array(3).toInt)))
  .foldLeft(Map.empty[String, Tuple3[String, Int, Int]])(accumulateLeft)
  .map(x => x._1+","+x._2._1+","+x._2._2+","+x._2._3)
  .toList
//res0: List[String] = List(itemA,CATS,5,5, itemB,CATQ,8,11, itemC,CARC,5,10)

reduceLeft

listInput1
  .map(_.split(","))
  .map(array => Map(array(0) -> (array(1), array(2).toInt, array(3).toInt)))
  .reduceLeft(accumulateLeft)
  .map(x => x._1+","+x._2._1+","+x._2._2+","+x._2._3)
  .toList
//res1: List[String] = List(itemA,CATS,5,5, itemB,CATQ,8,11, itemC,CARC,5,10)

Similarly you can just interchange the variables in the general function so that it can be used with foldRight and reduceRight as

def accumulateRight(y: Map[String, Tuple3[String, Int, Int]], x: Map[String, Tuple3[String, Int, Int]]): Map[String, Tuple3[String, Int, Int]] ={
  val key = y.keySet.toList(0)
  if(x.keySet.contains(key)){
    val oldTuple = x(key)
    x.updated(key, (y(key)._1, oldTuple._2+y(key)._2, oldTuple._3+y(key)._3))
  }
  else{
    x.updated(key, (y(key)._1, y(key)._2, y(key)._3))
  }
}

and calling the function would give you

foldRight

listInput1
  .map(_.split(","))
  .map(array => Map(array(0) -> (array(1), array(2).toInt, array(3).toInt)))
  .foldRight(Map.empty[String, Tuple3[String, Int, Int]])(accumulateRight)
  .map(x => x._1+","+x._2._1+","+x._2._2+","+x._2._3)
  .toList
//res2: List[String] = List(itemC,CARC,5,10, itemB,CATQ,8,11, itemA,CATs,5,5)

reduceRight

listInput1
  .map(_.split(","))
  .map(array => Map(array(0) -> (array(1), array(2).toInt, array(3).toInt)))
  .reduceRight(accumulateRight)
  .map(x => x._1+","+x._2._1+","+x._2._2+","+x._2._3)
  .toList
//res3: List[String] = List(itemC,CARC,5,10, itemB,CATQ,8,11, itemA,CATs,5,5)

So you don't really need a groupBy and can use any of the foldLeft, foldRight, reduceLeft or reduceRight functions to get your desired output.

Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97
0

The logic in your code looks sound, here it is with a case class implemented as that handles edge cases more cleanly:

// represents a 'row' in the original list
case class Item(
                 name: String,
                 category: String,
                 amount: Int,
                 price: Int
               )

// safely converts the row of strings into case class, throws exception otherwise
def stringsToItem(strings: Array[String]): Item = {
  if (strings.length != 4) {
    throw new Exception(s"Invalid row: ${strings.foreach(print)}; must contain only 4 entries!")
  } else {
    val n = strings.headOption.getOrElse("N/A")
    val cat = strings.lift(1).getOrElse("N/A")
    val amt = strings.lift(2).filter(_.matches("^[0-9]*$")).map(_.toInt).getOrElse(0)
    val p = strings.lastOption.filter(_.matches("^[0-9]*$")).map(_.toInt).getOrElse(0)

    Item(n, cat, amt, p)
  }
}

// original code with case class and method above used
listInput1.map(_.split(","))
  .map(stringsToItem)
  .groupBy(_.name)
  .map { case (name, items) =>
    Item(
      name,
      category = items.head.category,
      amount = items.map(_.amount).sum,
      price = items.map(_.price).sum
    )
  }.toList
Tanjin
  • 2,442
  • 1
  • 13
  • 20