I am trying to find 73 decimal numbers which binary representations are palindromes. I also need to get the sum of these numbers. I am totally new to Scala, so I've been trying to create this function which defines palindromes and sums them up. The issue is that I do not really know how to combine it into one function and include that there should be 73 numbers.
I already have a simple function which defines palindromes:
def isPalindrome(someNumber: String): Boolean = someNumber.length > 1 && someNumber.reverse.mkString == someNumber
And I have made some kind of a blueprint for my main function. I try to write all the found palindromic numbers into the list (so I could use some filters later):
def findPalindromes(list: List[Int]): Int = {
for(i <- 0 to 100){
if(isPalindrome(Integer.toBinaryString(i))) {
(xs: List[Int]) => i :: xs
}
sum(list)
}
}
I know some collections functions, but I don't have much experience using them. So I will be grateful if you could explain to me which collections and functions can be used in this case. I would be very grateful for any kind of help!
filter
and take
could be used here instead of looping.
filter
will add an element to a new collection that is returned based on the predicate you pass it. In your case it is isPalindrome
take
can be used get n
elements from a collection. i.e. the first 73 elements from the ones that passed the filter.
So, if you chain these together you get:
def findPalindromes(list: List[Int]): Int = {
list.filter(x => isPalindrome(Integer.toBinaryString(x))).take(73).sum
}
You could pass in something like Range(1, 10000).toList
. Another improvement could be to make this stop when it finds 73 palindromes instead of finding all of them and taking the first 73. A simple counter could be used for that or a Stream
The Stream
version is rather elegant:
def findPalindromes(n: Int) = Stream.from(1).filter(x => isPalindrome(Integer.toBinaryString(x))).take(n)
Force the evaluation of the Stream
with sum
:
scala> findPalindromes(73).sum
res10: Int = 35619