名古屋Scala練習場


名古屋Scala掲示板

サインインへ

年俸1000万の会社の試験問題

2011/09/28 17:34: yoshihiro503

4種類のアルファベット "A,C,G,T" から成るn文字の文字列のうち、"AAG"という並びが含まれる文字列を全て列挙するプログラムを書きなさい。ただし、nは3以上の整数とし、文字列内に同じアルファベットが出現しても構わないものとし、出力順序は問わないものとします。
... 適性検査に合格された方はその生産性を実現可能な方です。生産性に見合う初任給として年俸1000万円をご用意しております。
http://alpha.cgios.net/alpha/cgios
http://www.cgios.com/far1/recruit/prod/sp/wif

2011/09/28 17:35: yoshihiro503

Haskellだと4行。

permutation :: [a] -> Int -> [[a]]
permutation xs n = sequence $ take n $ repeat xs

solve :: Int -> [String]
solve n = filter (isInfixOf "AAG") $ permutation ['A', 'C', 'G', 'T'] n
実行例http://ideone.com/u2w0O

2011/10/15 22:02: yoshihiro503

上のScalaバージョン

object Main {
  def main(_args: Array[String]) = {
    solve(5) |> (s => println(s))
  }

  def repeat[A](x : A) : Stream[A] = x #:: repeat(x)

  def permutation[A](xs : List[A], n : Int) : List[List[A]] = {
    repeat(xs).take(n).toList |> ListMonad.sequence
  }

  def solve(n : Int) : List[String] = {
    permutation(List('A', 'C', 'G', 'T'), n).map(_.mkString).filter(_.contains("AAG"))
  }

  trait Monad[M[_]] {
    def mbind[A,B](m : M[A])(f : A => M[B]): M[B]
    def mret[A](x : A): M[A]
    def sequence[A](ms : List[M[A]]) : M[List[A]] =
      ms match {
        case Nil => mret(Nil)
        case m::ms =>
          mbind(m) {
            x => mbind(sequence(ms)) {
              xs => mret(x::xs)
            }
          }
      }
  }

  object ListMonad extends Monad[List] {
    override def mbind[A,B](m:List[A])(f: A => List[B]) = m.flatMap(f)
    override def mret[A](x : A) = List(x)
  }

  implicit def AofT[T](x: T) : {def |>[S](f:T=>S): S} = new { def |>[S] (f: T => S): S = f(x) }
}

2012/01/10 20:16: yoshihiro503

2012/01/13 14:50: deco.elb@gmail.com

PHPで普通に書くと17行でしたhttps://gist.github.com/1604840


名古屋Scala勉強会が立ち上げたScalaを練習するためのサイトです。 Powered by scala and lift .
ソースコードはこちら: https://bitbucket.org/yoshihiro503/nagoyascala/