1
\$\begingroup\$

I'm trying to solve this problem https://community.topcoder.com/stat?c=problem_statement&pm=40

Given a string made up of ONLY letters and digits, determine which character is repeated the most in the string ('A' is different than 'a'). If there is a tie, the character which appears first in the string (from left to right) should be returned.

Here is my approach is Scala. I feel it's not very functional, and slow(because of a new reversed String object).

def findMaxFunctional(word: String): Char = {
 var curMaxCount, maxCharId = 0
 word.reverse.foldLeft(new Array[Int](128))((acc, ch) => {
 acc(ch) = acc(ch) + 1
 if(acc(ch) >= curMaxCount) {
 curMaxCount = acc(ch)
 maxCharId = ch
 }
 acc
 })
 maxCharId.toChar
 }
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Jun 10, 2017 at 22:05
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

Instead of reversing the input string you could foldRight over it, and instead of updating mutable variables let the fold accumulator carry the current data forward. As an Array is mutable by default there's no point in having the fold accumulator make copies in order to carry it forward.

def findMaxFunctional(word: String): Char = {
 val arr = new Array[Int](128)
 word.foldRight((' ', 0)){
 case (c, (mxChr, mxCnt)) =>
 arr(c) += 1
 if (arr(c) >= mxCnt) (c, arr(c))
 else (mxChr, mxCnt)
 }._1
}
answered Jun 13, 2017 at 20:25
\$\endgroup\$
0
\$\begingroup\$

You forgot to resolve a possible tie.

There is no need to recompute the max value within your fold-loop at each iteration. You just fill your array and at the very end get the maximum.

You are using fold as a basic for-loop since your accumulator is actually the same array at each iteration.

Your code is not quite functional in the sense that you use mutable state instead of immutable state.

And why not just string.groupBy(identity).mapValues(_.size)? You can have multiple values with the maximal size, and then you have to do something else to resolve the ties.

answered Aug 13, 2017 at 15:24
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.