Comma Separated sequence in a single line using Scala - scala

for(i <- 10 to 28) {
if(i % 7 == 0 && i % 5 != 0) {
println(s"$i")
}
}
Output will be :
14
21
28
Need output like: 14,21,28.....
can anyone help us writing the code in Scala.

You can do this w/o foreach as below
val result = (10 to 28).filter(i => (i % 7 == 0 && i % 5 != 0 ) ).mkString(",")
println(result)

Related

Scala: Problem with foldLeft with negative numbers in list

I am writing a Scala function that returns the sum of even elements in a list, minus sum of odd elements in a list. I cannot use mutables, recursion or for/while loops for my solution. The code below passes 2/3 tests, but I can't seem to figure out why it can't compute the last test correctly.
def sumOfEvenMinusOdd(l: List[Int]) : Int = {
if (l.length == 0) return 0
val evens = l.filter(_%2==0)
val odds = l.filter(_%2==1)
val evenSum = evens.foldLeft(0)(_+_)
val oddSum = odds.foldLeft(0)(_+_)
evenSum-oddSum
}
//BEGIN TESTS
val i1 = sumOfEvenMinusOdd(List(1,3,5,4,5,2,1,0)) //answer: -9
val i2 = sumOfEvenMinusOdd(List(2,4,5,6,7,8,10)) //answer: 18
val i3 = sumOfEvenMinusOdd(List(109, 19, 12, 1, -5, -120, -15, 30,-33,-13, 12, 19, 3, 18, 1, -1)) //answer -133
My code is outputting this:
defined function sumOfEvenMinusOdd
i1: Int = -9
i2: Int = 18
i3: Int = -200
I am extremely confused why these negative numbers are tripping up the rest of my code. I saw a post explaining the order of operations with foldLeft foldRight, but even changing to foldRight still yields i3: Int = -200. Is there a detail I'm missing? Any guidance / help would be greatly appreciated.
The problem isn't foldLeft or foldRight, the problem is the way you filter out odd values:
val odds = l.filter(_ % 2 == 1)
Should be:
val odds = l.filter(_ % 2 != 0)
The predicate _ % 2 == 1 will only yield true for positive elements. For example, the expression -15 % 2 is equal to -1, and not 1.
As as side note, we can also make this a bit more efficient:
def sumOfEvenMinusOdd(l: List[Int]): Int = {
val (evenSum, oddSum) = l.foldLeft((0, 0)) {
case ((even, odd), element) =>
if (element % 2 == 0) (even + element, odd) else (even, odd + element)
}
evenSum - oddSum
}
Or even better by accumulating the difference only:
def sumOfEvenMinusOdd(l: List[Int]): Int = {
l.foldLeft(0) {
case (diff, element) =>
diff + element * (if (element % 2 == 0) 1 else -1)
}
}
The problem is on the filter condition that you apply on list to find odd numbers.
the odd condition that you doesn't work for negative odd number because mod 2 return -1 for this kind of number.
number % 2 == 0 if number is even
number % 2 != 0 if number is odd
so if you change the filter conditions all works as expected.
Another suggestion:
Why you want use foldleft function for a simple sum operation when you can use directly the sum functions?
test("Test sum Of even minus odd") {
def sumOfEvenMinusOdd(l: List[Int]) : Int = {
val evensSum = l.filter(_%2 == 0).sum
val oddsSum = l.filter(_%2 != 0).sum
evensSum-oddsSum
}
assert(sumOfEvenMinusOdd(List.empty[Int]) == 0)
assert(sumOfEvenMinusOdd(List(1,3,5,4,5,2,1,0)) == -9) //answer: -9
assert(sumOfEvenMinusOdd(List(2,4,5,6,7,8,10)) == 18) //answer: 18
assert(sumOfEvenMinusOdd(List(109, 19, 12, 1, -5, -120, -15, 30,-33,-13, 12, 19, 3, 18, 1, -1)) == -133)
}
With this solution your function is more clear and you can remove the if on the funciton

How to Make Prime Generator Code More Efficient

As a beginner in Scala, I got a problem in SPOJ:
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
`
Warning: large Input/Output data, be careful with certain languages (though most should be OK if the algorithm is well designed)
Run environment and requirement:
Added by: Adam Dzedzej
Date: 2004-05-01
Time limit: 6s
Source limit: 50000B
Memory limit: 1536MB
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All except: NODEJS PERL 6 SCM chicken
My code is here:
import math.sqrt
object Pro_2 {
def main(args: Array[String]) {
// judge whether a Long is a prime or not
def isPrime(num: Long): Boolean = {
num match {
case num if (num < 2) => false
case _ => {
2 to (sqrt(num) toInt) forall (num % _ != 0)
}
}
}
// if a Long is a prime print it in console
def printIfIsPrime(num: Long) = {
if (isPrime(num))
println(num)
}
// get range
def getInput(times: Int) = {
for (input <- 0 until times) yield {
val range = readLine().split(" ")
(range(0) toLong, range(1) toLong)
}
}
val ranges = getInput(readInt())
for (time <- 0 until ranges.length) {
(ranges(time)._1 to ranges(time)._2).foreach(printIfIsPrime(_))
if (time != ranges.length - 1)
println()
}
}
}
When I run my code in SPOJ, I got a result: time limit exceeded
I need make my code more efficient, could you please help me?
Any help would be greatly appreciated.
isPrime could be written in a lower level style. Also you can increase the speed of the println method.
def main(args: Array[String]) {
val out = new java.io.PrintWriter(System.out, false)
def isPrime(n: Long): Boolean = {
if(n <= 3) return n > 1
else if(n%2 == 0 || n%3 == 0) return false
else {
var i = 5
while(i*i <= n) {
if(n%i == 0 || n%(i+2) == 0) return false
i += 6
}
return true
}
}
def printIfIsPrime(num: Long) = {
if (isPrime(num)) {
out.println(num)
}
}
...
val ranges = getInput(readInt())
for (time <- 0 until ranges.length) {
(ranges(time)._1 to ranges(time)._2).foreach(printIfIsPrime(_))
if (time != ranges.length - 1)
out.println()
}
out.flush()
}

Basic Scala for loop Issue

I am trying to learn scala, here I am using basic for loop, but I am getting errors while compiling.
object App {
def main(args: Array[String]) {
for (i <- 1 to 10; i % 2 == 0)
Console.println("Counting " + i)
}
}
Errors while compiling :
fortest.scala:5: error: '<-' expected but ')' found.
for (i <- 1 to 10; i % 2 == 0)
^
fortest.scala:7: error: illegal start of simple expression
}
^
two errors found
I am using scala version 2.9.1
Any idea what is the problem..............?
for (i <- 1 to 10 if i % 2 == 0)
println("Counting " + i)
Scala is not Java, thus you cannot use a regular Java syntax. Instead you have to do:
for{
i <- 1 to 10
if(i % 2 == 0)
}{println("Counting " + i)}
or with ; delimeters, inside the (,) parentheses:
for(i <- 1 to 10;if(i % 2 == 0)){
println("Counting " + i)
}
Also, note that Scala's for expressions, have some pretty nifty capabilities.
you can use a for expression with multiple "loop iterators" and conditions.
For instance, instead of writing:
for(i <- 1 to n; if(someCondition(i)){
for(j <- 1 to m; if(otherCondition(j)){
//Do something
}
}
You can simply write:
for{
i <- 1 to n
if(someCondition(i))
j <- 1 to m
if(otherCondition(j))
}{
//Do something
}
SIDE NOTE:
When you extend App (there's a trait of that name in Predef), you don't need to define a main method. You can simply write your code between the curly braces of object:
object MyClazz extends App {
for(i <- 1 to 10;if(i % 2 == 0)){
println("Counting " + i)
}
}
Take a look at the "by" method of the Range class to count by 2
object App {
def main(args: Array[String]) {
for (i <- 2 to 10 by 2)
Console.println("Counting " + i)
}
}
Or, like others have already stated you can fix your loop by doing
object App {
def main(args: Array[String]) {
for {
i <- 1 to 10
if i % 2 == 0
}
Console.println("Counting " + i)
}
}
Or another way:
object App {
def main(args: Array[String]) {
val evenNumbers = for {
i <- 1 to 10
if i % 2 == 0
} yield i
Console.println(evenNumbers.mkString("\n"))
}
}
The modulo 2 condition can be moved to an if clause.
object App {
def main(args: Array[String]) {
for (i <- 1 to 10)
if(i % 2 == 0)
Console.println("Counting " + i)
}
}
Here is the simply example;
for (i <- List(1, 2, 3) if i < 2) println(i)
The best way to exam your code is to use scala shell.
Basically, you are trying to use for-loop + iterator gaurd. Please find below syntax
for ( i <- 1 to 10 if (i%2==0) ) yield i

Scala List.filter with two conditions, applied only once

Don't know if this is possible, but I have some code like this:
val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
val evens = list.filter { e => e % 2 == 0 }
if(someCondition) {
val result = evens.filter { e => e % 3 == 0 }
} else {
val result = evens.filter { e => e % 5 == 0 }
}
But I don't want to iterate over all elements twice, so is there a way that I can create a "generic pick-all-the-evens numbers on this collection" and apply some other function, so that it would only iterate once?
If you turn list into a lazy collection, such as an Iterator, then you can apply all the filter operations (or other things like map etc) in one pass:
val list = (1 to 12).toList
val doubleFiltered: List[Int] =
list.iterator
.filter(_ % 2 == 0)
.filter(_ % 3 == 0)
.toList
println(doubleFiltered)
When you convert the collection to an Iterator with .iterator, Scala will keep track of the operations to be performed (here, two filters), but will wait to perform them until the result is actually accessed (here, via the call to .toList).
So I might rewrite your code like this:
val list = (1 to 12).toList
val evens = list.iterator.filter(_ % 2 == 0)
val result =
if(someCondition)
evens.filter(_ % 3 == 0)
else
evens.filter(_ % 5 == 0)
result foreach println
Depending on exactly what you want to do, you might want an Iterator, a Stream, or a View. They are all lazily computed (so the one-pass aspect will apply), but they differ on things like whether they can be iterated over multiple times (Stream and View) or whether they keep the computed value around for later access (Stream).
To really see these different lazy behaviors, try running this bit of code and set <OPERATION> to either toList, iterator, view, or toStream:
val result =
(1 to 12).<OPERATION>
.filter { e => println("filter 1: " + e); e % 2 == 0 }
.filter { e => println("filter 2: " + e); e % 3 == 0 }
result foreach println
result foreach println
Here's the behavior you will see:
List (or any other non-lazy collection): Each filter is requires a separate iteration through the collection. The resulting filtered collection is stored in memory so that each foreach can just display it.
Iterator: Both filters and the first foreach are done in a single iteration. The second foreach does nothing since the Iterator has been consumed. Results are not stored in memory.
View: Both foreach calls result in their own single-pass iteration over the collection to perform the filters. Results are not stored in memory.
Stream: Both filters and the first foreach are done in a single iteration. The resulting filtered collection is stored in memory so that each foreach can just display it.
You could use function composition. someCondition here is only called once, when deciding which function to compose with:
def modN(n: Int)(xs: List[Int]) = xs filter (_ % n == 0)
val f = modN(2) _ andThen (if (someCondition) modN(3) else modN(5))
val result = f(list)
(This doesn't do what you want - it still traverses the list twice)
Just do this:
val f: Int => Boolean = if (someCondition) { _ % 3 == 0 } else { _ % 5 == 0 }
val result = list filter (x => x % 2 == 0 && f(x))
or maybe better:
val n = if (someCondition) 3 else 5
val result = list filter (x => x % 2 == 0 && x % n == 0)
Wouldn't this work:
list.filter{e => e % 2 == 0 && (if (someCondition) e % 3 == 0 else e % 5 == 0)}
also FYI e % 2 == 0 is going to give you all the even numbers, unless you're naming the val odds for another reason.
You just write two conditions in the filter:
val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
var result = List(0)
val someCondition = true
result = if (someCondition) list.filter { e => e % 2 == 0 && e % 3 == 0 }
else list.filter { e => e % 2 == 0 && e % 5 == 0 }

Swapping array values with for and yield scala

I am trying to swap every pair of values in my array using for and yield and so far I am very unsuccessful. What I have tried is as follows:
val a = Array(1,2,3,4,5) //What I want is Array(2,1,4,3,5)
for(i<-0 until (a.length-1,2),r<- Array(i+1,i)) yield r
The above given snippet returns the vector 2,1,4,3(and the 5 is omitted)
Can somebody point out what I am doing wrong here and how to get the correct reversal using for and yields?
Thanks
a.grouped(2).flatMap(_.reverse).toArray
or if you need for/yield (much less concise in this case, and in fact expands to the same code):
(for {b <- a.grouped(2); c <- b.reverse} yield c).toArray
It would be easier if you didin't use for/yield:
a.grouped(2)
.flatMap{
case Array(x,y) => Array(y,x)
case Array(x) => Array(x)
}.toArray // Array(2, 1, 4, 3, 5)
I don't know if the OP is reading Scala for the Impatient, but this was exercise 3.3 .
I like the map solution, but we're not on that chapter yet, so this is my ugly implementation using the required for/yield. You can probably move some yield logic into a guard/definition.
for( i <- 0 until(a.length,2); j <- (i+1).to(i,-1) if(j<a.length) ) yield a(j)
I'm a Java guy, so I've no confirmation of this assertion, but I'm curious what the overhead of the maps/grouping and iterators are. I suspect it all compiles down to the same Java byte code.
Another simple, for-yield solution:
def swapAdjacent(array: ArrayBuffer[Int]) = {
for (i <- 0 until array.length) yield (
if (i % 2 == 0)
if (i == array.length - 1) array(i) else array(i + 1)
else array(i - 1)
)
}
Here is my solution
def swapAdjacent(a: Array[Int]):Array[Int] =
(for(i <- 0 until a.length) yield
if (i%2==0 && (i+1)==a.length) a(i) //last element for odd length
else if (i%2==0) a(i+1)
else a(i-1)
).toArray
https://github.com/BasileDuPlessis/scala-for-the-impatient/blob/master/src/main/scala/com/basile/scala/ch03/Ex03.scala
If you are doing exercises 3.2 and 3.3 in Scala for the Impatient here are both my answers. They are the same with the logic moved around.
/** Excercise 3.2 */
for (i <- 0 until a.length if i % 2 == 1) {val t = a(i); a(i) = a(i-1); a(i-1) = t }
/** Excercise 3.3 */
for (i <- 0 until a.length) yield { if (i % 2 == 1) a(i-1) else if (i+1 <= a.length-1) a(i+1) else a(i) }
for (i <- 0 until arr.length-1 by 2) { val tmp = arr(i); arr(i) = arr(i+1); arr(i+1) = tmp }
I have started to learn Scala recently and all solutions from the book Scala for the Impatient (1st edition) are available at my github:
Chapter 2
https://gist.github.com/carloscaldas/51c01ccad9d86da8d96f1f40f7fecba7
Chapter 3
https://gist.github.com/carloscaldas/3361321306faf82e76c967559b5cea33
I have my solution, but without yield. Maybe someone will found it usefull.
def swap(x: Array[Int]): Array[Int] = {
for (i <- 0 until x.length-1 by 2){
var left = x(i)
x(i) = x(i+1)
x(i+1) = left
}
x
}
Assuming array is not empty, here you go:
val swapResult = for (ind <- arr1.indices) yield {
if (ind % 2 != 0) arr1(ind - 1)
else if (arr1(ind) == arr1.last) arr1(ind)
else if (ind % 2 == 0) arr1(ind + 1)
}