Home > Software design >  Filling in desired lines in Scala
Filling in desired lines in Scala

Time:11-07

I currently have a value of result that is a string which represents cycles in a graph

> scala result
String =
0:0->52->22;
5:5->70->77;
8:8->66->24;8->42->32;
. //
. // trimmed to get by point across
. //
71:71->40->45;
77:77->34->28;77->5->70;
84:84->22->29

However, I want to have the output have the numbers in between be included and up to a certain value included. The example code would have value = 90

0:0->52->22;
1:
2:
3:
4:
5:5->70->77;
6:
7:
8:8->66->24;8->42->32;
. //
. // trimmed
. //
83:
84:84->22->29;
85:
86:
87:
88:
89:
90:

If it helps or makes any difference, this value is changed to a list for later purposes, such like

list_result = result.split("\n").toList
List[String] = List(0:0->52->22;, 5:5->70->77;, 8:8->66->24;8->42->32;, 11:11->26->66;11->17->66;

My initial thought was to insert the missing numbers into the list and then sort it, but I had trouble with the sorting so I instead look here for a better method.

CodePudding user response:

Turn your list_result into a Map with default values. Then walk through the desired number range, exchanging each for its Map value.

val map_result: Map[String,List[String]] =
  list_result.groupBy("\\d :".r.findFirstIn(_).getOrElse("bad"))
             .withDefault(List(_))

val full_result: String =
  (0 to 90).flatMap(n => map_result(s"$n:")).mkString("\n")

Here's a Scastie session to see it in action.

CodePudding user response:

One option would be to use a Map as an intermediate data structure:


val l: List[String] = List("0:0->52->22;", "5:5->70->77;", "8:8->66->24;8->42->32;", "11:11->26->66;11->17->66;")
val byKey: List[Array[String]] = l.map(_.split(":"))

val stop = 90
val mapOfValues = (1 to stop).map(_->"").toMap

val output = byKey.foldLeft(mapOfValues)((acc, nxt) => acc   (nxt.head.toInt -> nxt.tail.head))
output.toList.sorted.map {case (key, value) => println(s"$key, $value")}

This will give you the output you are after. It breaks your input strings into pseudo key-value pairs, creates a map to hold the results, inserts the elements of byKey into the map, then returns a sorted list of the results.

Note: If you are using this in anything like production code you'd need to properly check that each Array in byKey does have two elements to prevent any nullPointerExceptions with the later calls to head and tail.head.

  • Related