1

I am solving trivial problems to learn Scala. Here is what I have come up with

def isUnique(str: String): Boolean = {
    if (str.length > 128) return false
    val uniqueChars = new Array[Boolean](128)

    !(str.map(c => addChar(c, uniqueChars)).find(identity).isDefined)
}

def addChar(ch: Char, uniqueChars: Array[Boolean]): Boolean = {
    if (uniqueChars(ch)) return true else {
    uniqueChars(ch) = true;
    return false
}

Is that it?

Please note that I don't care about the logic or optimization at this point. I only need to learn the Scala way of doing it.

[Edit] Let's assume we don't want to use the string distinct method. I only need to verify the functional style of Scala.

4
  • 7
    str.length == str.distinct.length Commented Jul 8, 2017 at 20:58
  • see stackoverflow.com/questions/22834018/… Commented Jul 8, 2017 at 21:00
  • Oops! This is even more direct: str == str.distinct Commented Jul 8, 2017 at 22:46
  • @jwvh Thanks... I wasn't aware of this method. Can you see my edit in the question? Lets assume we don't want to use distinct. Commented Jul 8, 2017 at 23:34

2 Answers 2

5

OK, so if you don't to want utilize the distinct library method then recursion is usually the functional way to go.

def isUnique(str: String, chrs: Set[Char] = Set()): Boolean =
  str.length == 0 ||
    !chrs(str.head) &&
      isUnique(str.tail, chrs + str.head)

isUnique("abcdexf")  // true
isUnique("abcdxxf")  // false
isUnique("fbcdexf")  // false
isUnique("abdbexf")  // false
Sign up to request clarification or add additional context in comments.

3 Comments

Pretty slick! It took a min to get my head around this though. Thanks!
Since you're using sets, why not use str.toSet.size == str.size ?
@RomainG; Since distinct had been rejected, and "functional style" requested, I thought that a demonstration of early termination via recursion might be what the OP was looking for.
-3

You want to "learn scala way of doing it", by actually doing it in a way, that makes no sense to use in scala? Scala way of doing it str == str.distinct. If "you don't want to use distinct", then str.toSet.size == str.length. If you don't want toSet either, then str.groupBy(identity).values.map(_.size).forall(_ == 1). If you don't want .groupBy then str.sorted.sliding(2).forall(s => s.head != s.last)

Etc. ... At some point, "scala way" just stops being "scala way" and becomes a java program written in scala syntax.

1 Comment

I don't want to make it Java. I wanted to know how would you implement distinct method in Scala. I am sure its not implemented using Java or groupBy or sorting. Please also see the accepted answer above. (FYI, I didn't down vote your answer).

Your Answer

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.