Scala strings - how to change lines - string

I'm trying to create an informative report according to results.
I currently have a .foreach loop iterating over a list, and writes the report.
The code looks like:
result.foreach {
tupleResult =>
tupleResult._3 match {
case "FirstTest" =>
language1 = createReport(tupleResult)
case "SecondTest" =>
language2 = createReport(tupleResult)
case "ThirdTest" =>
language3 = createReport(tupleResult)
}
finalReport = ""
}
Each "createReport" is a method which creates a one line String into the relevant language var.
I want each iteration to add a different line in the "finalReport" string.
Example of "finalReport":
Report consists of the following:
1) language1
2) language2
3) language3
The question is how to create the different variables as different lines of the same "finalReport" string.

The more idiomatic scala way to do it would be to not do several things at once and also mutate state, but instead see it as separate operations/expressions. Something like this for example:
val sortedResults = result.sortBy(_._3 match {
case "FirstTest" => 1
case "SecondTest" => 2
case "ThirdTest" => 3
})
val reportLines = sortedResults.map(result => createReport(result._3))
val finalReport = reportLines.mkString("\n")

Associating an ordering to the test strings may prove a solution, for instance like this,
val ord = Array("FirstTest","SecondTest","ThirdTest").zipWithIndex.toMap
Then we can generate the parts of the report, and finally sort them by the defined ordering,
val finalReport = result.map { tRes => (ord.get(tRes._3), createReport(tRes)) }
.sortBy(_._1)
.map(_._2)
.mkString("\n")

Related

Scala - Executing every element until they all have finished

I cannot figure out why my function invokeAll does not give out the correct output/work properly. Any solutions? (No futures or parallel collections allowed and the return type needs to be Seq[Int])
def invokeAll(work: Seq[() => Int]): Seq[Int] = {
//this is what we should return as an output "return res.toSeq"
//res cannot be changed!
val res = new Array[Int](work.length)
var list = mutable.Set[Int]()
var n = res.size
val procedure = (0 until n).map(work =>
new Runnable {
def run {
//add the finished element/Int to list
list += work
}
}
)
val threads = procedure.map(new Thread(_))
threads.foreach(x => x.start())
threads.foreach (x => (x.join()))
res ++ list
//this should be the final output ("return res.toSeq")
return res.toSeq
}
OMG, I know a java programmer, when I see one :)
Don't do this, it's not java!
val results: Future[Seq[Int]] = Future.traverse(work)
This is how you do it in scala.
This gives you a Future with the results of all executions, that will be satisfied when all work is finished. You can use .map, .flatMap etc. to access and transform those results. For example
val sumOfAll: Future[Int] = results.map(_.sum)
Or (in the worst case, when you want to just give the result back to imperative code), you could block and wait on the future to get ahold of the actual result (don't do this unless you are absolutely desperate): Await.result(results, 1 year)
If you want the results as array, results.map(_.toArray) will do that ... but you really should not: arrays aren't really a good choice for the vast majority of use cases in scala. Just stick with Seq.
The main problem in your code is that you are using fixed size array and trying to add some elements using ++ (concatenate) operator: res ++ list. It produces new Seq but you don't store it in some val.
You could remove last line return res.toSeq and see that res ++ lest will be return value. It will be your work.length array of zeros res with some list sequence at the end. Try read more about scala collections most of them immutable and there is a good practice to use immutable data structures. In scala Arrays doesn't accumulate values using ++ operator in left operand. Array's in scala are fixed size.

how to get this below list using spark rdd?

List(1,2,3,4..100)==> List((1,2),(2,3),(3,4)...(100,101))==>List(3,5,7,....201)
scala> x.map(x=>x,x+1).map(x=>x._1+x._2)
:26: error: too many arguments (2) for method map: (f: Int => B)(implicit bf: scala.collection.generic.CanBuildFrom[List[Int],B,That])That
x.map(x=>x,x+1).map(x=>x._1+x._2)
am trying to transform the 1 to 100 values but am getting the above error.Is there any issue with any the code?
your map function's return is incorrect.
try this:
input.map(x => (x,x+1)).map(x => x._1 + x._2)
Although, I don't see the need for two map functions when you can do it in one like this:
input.map(x => x + x + 1)
the above expression will also give you the same result.

takeRightWhile() method in scala

I might be missing something but recently I came across a task to get last symbols according to some condition. For example I have a string: "this_is_separated_values_5". Now I want to extract 5 as Int.
Note: number of parts separated by _ is not defined.
If I would have a method takeRightWhile(f: Char => Boolean) on a string it would be trivial: takeRightWhile(ch => ch != '_'). Moreover it would be efficient: a straightforward implementation would actually involve finding the last index of _ and taking a substring while the use of this method would save first step and provide better average time complexity.
UPDATE: Guys, all the variations of str.reverse.takeWhile(_!='_').reverse are quite inefficient as you actually use additional O(n) space. If you want to implement method takeRightWhile efficiently you could iterate starting from the right, accumulating result in string builder of whatever else, and returning the result. I am asking about this kind of method, not implementation which was already described and declined in the question itself.
Question: Does this kind of method exist in scala standard library? If no, is there method combination from the standard library to achieve the same in minimum amount of lines?
Thanks in advance.
Possible solution:
str.reverse.takeWhile(_!='_').reverse
Update
You can go from right to left with following expression using foldRight:
str.toList.foldRight(List.empty[Char]) {
case (item, acc) => item::acc
}
Here you need to check condition and stop adding items after condition met. For this you can pass a flag to accumulated value:
val (_, list) = str.toList.foldRight((false, List.empty[Char])) {
case (item, (false, list)) if item!='_' => (false, item::list)
case (_, (_, list)) => (true, list)
}
val res = list.mkString.toInt
This solution is even more inefficient then solution with double reverse:
Implementation of foldRight uses combination of List reverse and foldLeft
You cannot break foldRight execution, so you need flag to skip all items after condition met
I'd go with this:
val s = "string_with_following_number_42"
s.split("_").reverse.head
// res:String = 42
This is a naive attempt and by no means optimized. What it does is splitting the String into an Array of Strings, reverses it and takes the first element. Note that, because the reversing happens after the splitting, the order of the characters is correct.
I am not exactly sure about the problem you are facing. My understanding is that you want have a string of format xxx_xxx_xx_...._xxx_123 and you want to extract the part at the end as Int.
import scala.util.Try
val yourStr = "xxx_xxx_xxx_xx...x_xxxxx_123"
val yourInt = yourStr.split('_').last.toInt
// But remember that the above is unsafe so you may want to take it as Option
val yourIntOpt = Try(yourStr.split('_').last.toInt).toOption
Or... lets say your requirement is to collect a right-suffix till some boolean condition remains true.
import scala.util.Try
val yourStr = "xxx_xxx_xxx_xx...x_xxxxx_123"
val rightSuffix = yourStr.reverse.takeWhile(c => c != '_').reverse
val yourInt = rightSuffix.toInt
// but above is unsafe so
val yourIntOpt = Try(righSuffix.toInt).toOption
Comment if your requirement is different from this.
You can use StringBuilder and lastIndexWhere.
val str = "this_is_separated_values_5"
val sb = new StringBuilder(str)
val lastIdx = sb.lastIndexWhere(ch => ch != '_')
val lastCh = str.charAt(lastIdx)

String method to change particular element in Scala

I need to write a method in Scala that overrides the toString method. I wrote it but I also have to check that if there is an element that is '1' I will change it to 'a', else write the list as it is with the string method. Any suggestions how this can be done?
What error are you getting? seems to work for me
val l = List(1, 2, 3)
println(this)
override def toString(): String = {
val t = l.map({
case 1 => "a"
case x => x
})
t.toString
}
getting List(a, 2, 3) printed out
I see from the comments on your question that list is a List[List[Int]].
Look at the beginning of your code:
list.map { case 1 => 'a'; case x => x}
map expects a function that takes an element of list as a parameter - a List[Int], in your case. But your code works directly on Int.
With this information, it appears that the error you get is entirely correct: you declared a method that expects an Int, but you pass a List[Int] to it, which is indeed a type mismatch.
Try this:
list.map {_.map { case 1 => 'a'; case x => x}}
This way, the function you defined to transform 1 to a and leave everything else alone is applied to list's sublists, and this type-checks: you're applying a function that expects an Int to an Int.

Scala check if element is present in a list

I need to check if a string is present in a list, and call a function which accepts a boolean accordingly.
Is it possible to achieve this with a one liner?
The code below is the best I could get:
val strings = List("a", "b", "c")
val myString = "a"
strings.find(x=>x == myString) match {
case Some(_) => myFunction(true)
case None => myFunction(false)
}
I'm sure it's possible to do this with less coding, but I don't know how!
Just use contains
myFunction(strings.contains(myString))
And if you didn't want to use strict equality, you could use exists:
myFunction(strings.exists { x => customPredicate(x) })
Even easier!
strings contains myString
this should work also with different predicate
myFunction(strings.find( _ == mystring ).isDefined)
In your case I would consider using Set and not List, to ensure you have unique values only. unless you need sometimes to include duplicates.
In this case, you don't need to add any wrapper functions around lists.
You can also implement a contains method with foldLeft, it's pretty awesome. I just love foldLeft algorithms.
For example:
object ContainsWithFoldLeft extends App {
val list = (0 to 10).toList
println(contains(list, 10)) //true
println(contains(list, 11)) //false
def contains[A](list: List[A], item: A): Boolean = {
list.foldLeft(false)((r, c) => c.equals(item) || r)
}
}

Resources