HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Find anagrams in a list

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
listanagramsfind

Problem

Write a program that, given a word and a list of possible anagrams,
selects the correct sublist.


Given "listen" and a list of candidates like "enlists" "google" "inlets" "banana" the program should return a list containing "inlets".

Here is my solution:

class Anagram(word: String) {
  val sorted_word = word.toLowerCase.sorted
  val origin_word = word.toLowerCase

  def matches(words: Seq[String]) = {
    words.filter(w => w.toLowerCase.sorted == sorted_word && w.toLowerCase != origin_word)
  }

}


Here is the gist with specs.

Solution

Looks good! Just one little thing that I, personally would do to remove one .toLowerCase call per item: map it first. So, instead of calling .toLowerCase in the filter, you can do this:

words.map(w => w.toLowerCase)
     .filter(w => w.sorted == sorted_word && w != origin_word)


You've also got a random newline before the end of the class.

Aside from that little niggle, it looks good! There's... really not much I can say. It's short code.

Code Snippets

words.map(w => w.toLowerCase)
     .filter(w => w.sorted == sorted_word && w != origin_word)

Context

StackExchange Code Review Q#95422, answer score: 4

Revisions (0)

No revisions yet.