Skip to content

Instantly share code, notes, and snippets.

@koji-k
Created July 18, 2012 07:16
Show Gist options
  • Save koji-k/3134754 to your computer and use it in GitHub Desktop.
Save koji-k/3134754 to your computer and use it in GitHub Desktop.
Scalaで文字列中の各文字をカウントする
object CharacterCount {
// scala.collection.mutableをインポートしておけば、mutable.Mapの宣言が短くできる
// インポート無 → cala.collection.mutable.Map[Char, Int]()
// インポート有 → mutableMap[Char, Int]()
import scala.collection.mutable
/**
* 指定された文字列中に出現する各文字をカウントし、Mapに格納する
* @param text 出現する文字をカウントしたい文字列
* @param limit 出現回数がlimit回以上の文字のみ返す
* @return text中、limit回以上出現した文字と出現回数を格納したMap
*/
def getMapWithLimit(text:String, limit:Int):mutable.Map[Char,Int] = {
count(text).filter( (kv) => kv._2 >= limit )
}
/**
* getMapWithLimitの部分適用
* getMapWithLimit(text, 1)と指定したのと同じ
* @param text 出現する文字をカウントしたい文字列
* @return text中、1回以上出現した文字と出現回数を格納したMap
*/
def getMap = getMapWithLimit(_:String, 1)
/**
* 部分適用したgetMapをオーバロードしたもの
* getMapWithLimitと全く同じ
* @param text 出現する文字をカウントしたい文字列
* @param limit 出現回数がlimit回以上の文字のみ返す
* @return text中、limit回以上出現した文字と出現回数を格納したMap
*/
def getMap(text:String, limit:Int):mutable.Map[Char,Int] = {
getMapWithLimit(text, limit)
}
/**
* 指定された文字列に出現する各文字をカウントし、Mapに格納して返す
* @param text 出現する文字をカウントしたい文字列
* @return text中の各文字と出現回数を格納したMap
*/
private def count(text:String):mutable.Map[Char, Int] = {
val map = mutable.Map[Char, Int]()
text.foreach ( (char) => {
val count = map.getOrElse( char, 0 )
map.update( char, count+1 )
})
map
}
// 関数の部分適用部分は、以下のようにしても結果は同じ
//def getMap(text:String) = { getMapWithLimit(text, 1) }
// 実際に実行してみる
def main(array:Array[String]):Unit = {
val string = "となりのきゃくはよくかきくうきゃくだ"
val resultMap1 = CharacterCount.getMap(string)
// 結果は以下
//Map(の -> 1, く -> 4, か -> 1, う -> 1, ゃ -> 2, と -> 1, き -> 3, な -> 1, は -> 1, よ -> 1, り -> 1, だ -> 1
val resultMap2 = CharacterCount.getMap(string, 3)
// 結果は以下
// Map(く -> 4, き -> 3)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment