Reverse Integer in Scala [closed] - scala

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I've been trying to figure out a way to reverse an integer in scala (e.g. 1932 -> 2391) without converting to string and in a purely functional way. My goal is to reverse the Int by converting to List then just using List().reverse then converting back to Int.
def reverseIntList(x: Int) : List[Int] = {
if (!(x <= 0))
if ((x > 0) && (x < 10))
x
else
(x % 10) :: reverseIntList(x / 10) :: Nil
else
List()
}
However, I only get this error code:
recursive method reverseIntList needs result type

First unfold() it, then fold() it back up. No .reverse needed.
def reverseInt(x: Int): Int =
List.unfold(x)(n => Option.when(n > 0)((n%10,n/10)))
.fold(0)(_ * 10 + _)

You are returning an Int instead of List[Int] for the first condition.
Also, some enhancement to apply to your code.
No need in this case for the ":: Nil" to construct your list.
No need for "(x > 0)" condition, as it’s already verified by your first if.
It should look like this.
def reverseIntList(x: Int): List[Int] = {
if (!(x <= 0))
if ((x < 10))
List(x)
else
x % 10 :: reverseIntList(x / 10)
else
List()
}

Related

Factorial with Scala [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am new to Scala and tying to understand recursion and tail recursion. When I write the program in single line, it's always giving me StackOverflow error, even for n=1 -
object Recursion extends App {
def factorial(n: Int): Int = //if (n<=1) 1
n * factorial( n - 1 )
println( factorial( 1 ) )
}
vs
object Recursion extends App {
def factorial(n: Int): Int = (
if (n <= 1) 1
else n * factorial( n - 1 )
)
println( factorial( 8 ) )
}
Gives correct value - 40320
Got it, without if (n<=1), it's going to infinite loop. That's why it never comes out and give this error.
In problems solved via recursion, you must have a "branch/condition" that breaks the recursion and returns the accumulated value (aka pops the stack), or else the problem would never stop in theory; in practise all the calls to the function eventually overloads the memory allocated for the stack (i.e. StackOverflow error)
Notice also, that your function is recursive, but it is not tail recursive. For it to be tail recursive, the recursive call must the very last step.
To make it tail recursive you would have to do something like:
def factorial(n: Int): Int = {
#tailrec
def helper(n: Int, acc: Int): Int = {
if (n == 1) acc
else helper(n-1, n*acc)
}
helper(n, 1)
}
In your case, the last step is the multiplication n*factorial(n-1). In my case, it is truly a call to itself.
Just to make things clear, in my example, factorial is not recursive (tail or otherwise), but the inner function helper is tail recursive.

Finding strings which contain the most 'a' letters [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I've got a question if I can somehow shorten my code - I need to find what strings in my List contain the most 'a' letters. I made it as below, but I'm almost sure that I could do it shorter, but I don't know how.
So first of all I map my list to tuple, where I have (el, num) where the num is how many the 'a' contains (using foldLeft).
Then I use maxBy so I take an element that have the most 'a' letters and then I filter all elements where the num == res2._2 (because there could be more than one element having the same number of 'a' letters, so I can't stop at maxBy
My code:
def mostA(l: List[String]): List[String] = {
val res = l.map( string => (string, string.foldLeft(0)((acc,b) => if (b == 'a') acc + 1 else acc)))
val res2 = res.maxBy(x => x._2)
val res3 = res.filter(x => x._2 == res2._2).map{case (str, num) => str}
res3
}
With a bit of an effort, you can do it in one go:
l.foldLeft(List[String] -> 0) { case ((strs, max), s) =>
val n = s.count(_ == letter)
if (n == max) (s::strs, max) else if (n > max) (s::Nil, n) else (strs, max)
}._1.reverse
Your code is already pretty small and concise. However, there is a couple of improvements we can do:
def mostLetter(letter: Char)(data: List[String]): List[String] = {
val counts = data.map(s => s -> s.count(_ == letter))
val max = counts.maxBy(_._2)._2
counts.collect {
case (str, `max`) => str
}
}
Namely, we replaced the foldLeft in the String with count and we fused together the filter + map in a single collect
Also, remember the last expression is the return thus it is unnecessary to assign it to a variable to later just return it.

Finding all pairs of two collections that match a predicate using functional style in Scala [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am currently learning Scala and I am looking for good ways to get the most out of functional programming style.
I am trying to do the following:
Given two collections, I want to list every possible combination of two entries that match a predicate.
Now I could solve it using two loops and saving every result in a new collection, but is there a more elegant scala-ey solution?
You can start with
val col1: List[Int]
val col2: List[Int]
col1.map { i =>
col2.map { j =>
(i -> j)
}.filter { case (i, j) =>
// condition
}
}.flatten
map and flatten should be the easiest to understand in the beginning. Play a bit with the idea to look a the types.
Then you might try to replace map(f).flatten with flatMap(f):
col1.flatMap { i =>
col2.map { j =>
(i -> j)
}.filter { case (i, j) =>
// condition
}
}
This is almost identical to this for comprehension:
for {
i <- col1
j <- col2
ij = (i, j)
if condition(ij)
} yield ij
which might be easier to read as
for {
i <- col1
j <- col2
if condition(i, j)
} yield (i, j)
https://scalafiddle.io/sf/mhFZMjt/0

Scala Style: pattern matching with all branches being wildcards with pattern guard [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to convince my colleagues that
if (totalSize < X) value1
else if (totalSize > Y) value2
else if (totalSize > Z) value3
else func(totalSize)
is preferable to
totalSize match {
case _ if totalSize < X => value1
case _ if totalSize > Y => value2
case _ if totalSize > Z => value3
case _ => func(totalSize)
}
But I'm having trouble doing that. Counter-argument is that "case-matching is created to eliminate the need for if-else constructs".
Can anyone point me to style guide that has pointers on such usage of pattern matching? I searched but I couldn't find any examples what is considered anti-pattern in such situation.
"case-matching is created to eliminate the need for if-else
constructs"
IMHO, pattern matching is not created to eliminate if-else expression. They are both first-class constructs in the language, and it is a value call which one to employ for a particular problem.
Since totalSize has no real structure to it, I personally do not see much value in pattern matching it in this particular scenario. Pattern matching tour states
Scala’s pattern matching statement is most useful for matching on
algebraic types expressed via case classes.
Here is an example scenario where, IMO, pattern matching is indeed better suited to eliminate an if-else expression
if (jf() != null) {
// proceed with computation
} else {
// handle error
}
Option(jf()) match {
case Some(v) => // proceed with computation
case None => // handle error
}
Here is example of if-else chaining from Scala repo
def compareVersions(s: String, v: String, depth: Int): Int = {
if (depth >= 3) 0
else {
val (sn, srest) = versionOf(s, depth)
val (vn, vrest) = versionOf(v, depth)
if (vn < 0) -2
else if (sn < vn) -1
else if (sn > vn) 1
else compareVersions(srest, vrest, depth + 1)
}
}

write the code higher order function instead of usual loops/iterators [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Can anyone tell me how to write this below code using higher order functions.
var x = 10
while (x < =10)
{
if (x <= 5)
print(x)
x = x+1
}
Or using the "sugar" to create Range:
(0 to 10)
.filter(_ <= 5)
.foreach(println)
Let's assume the piece of code you provided looked something like this:
var x = 0
while (x <= 10) {
if (x <= 5) println(x)
x = x + 1
}
Then, using higher order functions (I would just call it functional programming), it could look something like this:
List.range(0, 10)
.filter(_ <= 5)
.foreach(println)
Of course this combination of .range() and .filter() could be simplified to .range(0, 5).
Try it out!
I hope that helps.