Ninety-Nine Scala Problems (P31)

S-99を解く。Int型にisPrimeっていう素数かどうかを判定するメソッドを組み込む問題。

implicit defをつかえばいい。

ProductName Scalaスケーラブルプログラミング第2版
Martin Odersky
インプレスジャパン / 4830円 ( 2011-09-27 )


class IntWrapper(n:Int){
 def isPrime():Boolean = (n != 1) &&
(List.range(2,math.sqrt(n).toInt+1) forall (i => n % i != 0))
}

implicit def int2IntWrapper(n:Int) = new IntWrapper(n)

for (n <- 1 to 10)
 println(n + ": " + n.isPrime)

ところで、解答見たらstream使った例が載ってたんだけどこれ動かないんだけどナニが悪いの?

/Users/kzfm/scala/p31.scala:3: error: not found: value primes
    (start > 1) && (primes takeWhile { _ <= Math.sqrt(start) } forall { start % _ != 0 })
                    ^
/Users/kzfm/scala/p31.scala:7: error: value isPrime is not a member of Int
  val primes = Stream.cons(2, Stream.from(3, 2) filter { _.isPrime })

コード

class S99Int(val start: Int) {
  def isPrime: Boolean =
    (start > 1) && (primes takeWhile { _ <= Math.sqrt(start) } forall { start % _ != 0 })
}

object S99Int {
  val primes = Stream.cons(2, Stream.from(3, 2) filter { _.isPrime })
}

shizudevつくる会#3をやります

静岡デベロッパーズつくる会は手を動かしてなにかをつくる会です。

  • やりたいことがあるけど、モチベーションが上がらなくてスイッチが入らない
  • なんかやりたいけど、取り組む対象がみつからない

なんて人は参加するといいかもしれません。みんな結構面白そうな取り組みをしているので、インスパイアされまくりです。

それからコミュニティfのいいところは

あたりかな。

飛び入りも歓迎なので、連休最終日に「暇だなー」と思ったら遊びに来てください。

Ninety-Nine Scala Problems (P21 - P28)

S-99を解く。P25から先がちょいむず。

P26

組み合わせを求めるというオーソドックスな問題。n個からr個を選ぶ組み合わせは再帰的に考えると

  • (取り出したものを加える場合)は n-1個からr-1個を選ぶ
  • (取り出したものを加えない場合)はn-1個からr個を選ぶ

上記2つのパターンの和になるので、これで再帰させる。

def flatten(ls: List[Any]): List[Any] = ls flatMap {
 case ms: List[_] => flatten(ms)
 case e => List(e)
}

def combinations(n:Int, ls:List[Any]): List[List[Any]] =
 if (n==0) List(Nil)
 else if (ls == Nil) List(Nil)
 else ((combinations(n-1,ls.tail) map ((e:List[Any]) => ls.head :: flatten(e))) ::: combinations(n,ls.tail))

println(combinations(3, List('a, 'b, 'c, 'd)) filter (l => l.length == 3))
println(combinations(3, List('a, 'b, 'c, 'd)))

結局r個以下の組み合わせを出力する関数になってしまった。しょうがないのでfilterかましてるけど。 あと、型がうまく決められなかったので、Anyとか使っちゃったけどあんまり良くない気がする。

ProductName Scalaスケーラブルプログラミング第2版
Martin Odersky
インプレスジャパン / 4830円 ( 2011-09-27 )


//21
def insertAt[A](e:A, n:Int, ls:List[A]): List[A] = {
  val v = ls.splitAt(n)
  v._1 ::: e :: v._2
}

println("s21: "+ insertAt('new, 1, List('a, 'b, 'c, 'd)))

//22
def range(s:Int, e:Int): List[Int] = List.range(s,e+1)

println("s22: " + range(4, 9))

//23 Randomの使い方を知らなかった
def removeAt[A](n:Int, ls:List[A]): (List[A],A) = {
  val v = ls.splitAt(n)
  (v._1 ::: v._2.tail, v._2.head)
}

def randomSelect[A](n: Int, ls: List[A]): List[A] =
  if (n <= 0) Nil
  else {
    val (rest, e) = removeAt((new util.Random).nextInt(ls.length), ls)
    e :: randomSelect(n - 1, rest)
  }

println("s23: " + randomSelect(3, List('a, 'b, 'c, 'd, 'f, 'g, 'h)))

//24
def lotto(n: Int, r: Int): List[Int] = 
  if (n <=0) Nil
  else randomSelect(n, List.range(1,r+1))

println("s24: " + lotto(6, 49))

//25
def randomPermute[A](ls:List[A]): List[A] = lotto(ls.length,ls.length) map(e => ls(e-1))

println("s25: " + randomPermute(List('a, 'b, 'c, 'd, 'e, 'f)))

//26
//def combinations[A](n:Int, ls:List[A]): List[List[Any]] = 
//  if (n == 0) Nil
//  else if (ls == Nil) Nil
//  else ( ls.head :: combinations(n-1,ls.tail) ) :: combinations(n,ls.tail)

def flatMapSublists[A,B](ls: List[A])(f: (List[A]) => List[B]): List[B] = 
  ls match {
    case Nil => Nil
    case sublist@(_ :: tail) => f(sublist) ::: flatMapSublists(tail)(f)
  }

def combinations[A](n: Int, ls: List[A]): List[List[A]] =
  if (n == 0) List(Nil)
  else flatMapSublists(ls) { sl =>
    combinations(n - 1, sl.tail) map {sl.head :: _}
               }

println("s26: " + combinations(3, List('a, 'b, 'c, 'd, 'e, 'f)))

//27
//println("s27: " + )
//28
//println("s28: " + )

Javaデータ構造とアルゴリズム基礎講座

アルゴリズムの勉強のしかたに載っていて、java度の低い自分には丁度よいかもと思い即買いしたのだけど、自分にはちょっと基礎的すぎた(どういうライブラリがあるかとリングバッファの実装が役に立ったけど)。

ProductName Java データ構造とアルゴリズム基礎講座
長尾 和彦
技術評論社 / 2709円 ( 2008-12-26 )


アルゴリズムイントロダクションを買うべきだったな。

ところでperlでアルゴリズムを学ぶなら迷わずMAWPを選択するべきでしょう。

ProductName Mastering Algorithms With Perl
Jon Orwant
Oreilly & Associates Inc / 2553円 ( 1999-07 )


日本語版がでてもおかしくないくらいの良書だと思う。

パーフェクトJavaScriptが届いた

面白そうなんだけど、本が積まれてて読む暇がない。

ProductName パーフェクトJavaScript (PERFECT SERIES 4)
井上 誠一郎
技術評論社 / 3360円 ( 2011-09-23 )


どうしたもんか。

11.09.27 追記

とかいいつつ、ざざっと一気に読んでしまった。これは良書でした。理解が曖昧だったところとかがきっちり書いてあったので理解が深まった。後ろの方のコードは流し読みしてしまったので、あとでちゃんと手を動かす予定。

あとできちんと書く。

HTML5 CANVAS chapter 4

3章は画像の扱い方。アイコンをタイル型に並べた画像ファイルを用意しておいて、任意の部分を切り出してCanavasに貼り付けたりアニメーションさせたりと、動くものをができるのは結構楽しい。

が、この本のサンプル画像が用意されていないのでちょっと困った。

text

ProductName HTML5 Canvas: Native Interactivity and Animation for the Web
Steve Fulton
Oreilly & Associates Inc / 2922円 ( 2011-05-13 )


Express+jade+coffeeで書いたのはGitHubにあげている。

ドット絵ブームが来る予感がしてきた。

Ninety-Nine Scala Problems (P11 - P20)

S-99を解く。List.makeを使ったらdeprecation warningsがでたので、fillにしてみたんだけどこれでいいのだろうか?

scala> List.make(5,3)
warning: there were 1 deprecation warnings; re-run with -deprecation for details
res5: List[Int] = List(3, 3, 3, 3, 3)

pythonのenumerateはscalaではzipWithIndexでこれを使えばp16は

ls.zipWithIndex filter { v => (v._2 + 1) % n != 0 } map { _._1 }

splitAtメソッド使えばリストを2つに分割(P17)できるが、僕はtakeとdrop使ってた。

//11
def pack[A](ls:List[A]): List[List[A]] = ls match {
  case Nil => Nil
  case head::tail => ls.takeWhile(_ == head) :: pack(tail.dropWhile(_ == head))
}

def encodeModified[A](ls: List[A]): List[Any] = pack(ls) map {
  e => if (e.length == 1) e.head else (e.length, e.head)
}

println("s11: " + encodeModified(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)))

//12
//scala> List.make(5,3)
//warning: there were 1 deprecation warnings; re-run with -deprecation for details
//res5: List[Int] = List(3, 3, 3, 3, 3)

def decode[A](ls:List[(Int, A)]): List[A] = ls flatMap {e => List.fill(e._1)(e._2)}

println("s12: " + decode(List((4, 'a), (1, 'b), (2, 'c), (2, 'a), (1, 'd), (4, 'e))))

//13
def encodeDirect[A](ls:List[A]): List[(Int, A)] = ls match {
  case Nil => Nil
  case head::tail => (ls.takeWhile(_ == head).length, head) :: encodeDirect(tail.dropWhile(_ == head))
}

println("s13: " + encodeDirect(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)))

//14
def duplicate[A](ls:List[A]): List[A] = ls match {
  case Nil => Nil
  case h::t => h::h::duplicate(t)
}

println("s14: " + duplicate(List('a, 'b, 'c, 'c, 'd)))

//15
def duplicateN[A](n:Int, ls:List[A]): List[A] = ls flatMap {e => List.fill(n)(e) }

println("s15: " + duplicateN(3, List('a, 'b, 'c, 'c, 'd)))

//16
//  // Functional.
//  def dropFunctional[A](n: Int, ls: List[A]): List[A] = 
//    ls.zipWithIndex filter { v => (v._2 + 1) % n != 0 } map { _._1 }
//}

def drop[A](n:Int, ls:List[A]): List[A] = {
  def drop2[A](n:Int, ls:List[A]): List[A] = ls match {
    case Nil => Nil
    case _ => ls.take(n-1) ::: drop2(n, ls.drop(n))
  }
  drop2(n,ls)
}

println("s16: " + drop(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)))

//17
// Builtin.
//  def splitBuiltin[A](n: Int, ls: List[A]): (List[A], List[A]) = ls.splitAt(n)

def split[A](n:Int, ls:List[A]): (List[A],List[A]) = (ls.take(n), ls.drop(n))

println("s17: " + split(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)))

//18
def slice[A](s:Int, e:Int, ls:List[A]): List[A] = ls.take(e).drop(s)

println("s18: " + slice(3, 7, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)))

//19
def rotate[A](n:Int, ls:List[A]): List[A] = {
  if (n >= 0)  ls.drop(n) ::: ls.take(n)
  else ls.drop(ls.length + n) ::: ls.take(ls.length + n)
}

println("s19: " + rotate(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)))
println("s19: " + rotate(-2, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)))

//20
def removeAt[A](n:Int, ls:List[A]): (List[A],A) = {
  val v = ls.splitAt(n)
  (v._1 ::: v._2.tail, v._2.head)
}

println("s20: " + removeAt(1, List('a, 'b, 'c, 'd)))

GAMESSで励起状態の構造最適化をする

光異性化とかAMES予測とか代謝予測とか、量子化学計算が創薬シーンで果たす役割が大きくなっているのは、探索創薬自体が発見学というよりはメカニズムベースでモノを考えるようになってきているからかなぁと。それからFMOなんかも重要な技術ですね。

さて、ちょっと励起状態での構造最適化計算が必要になったので、pygamessでCIS計算できるようにしておきました。

test用にGAMESSのEXAM34のホルムアルデヒドの励起状態計算のサンプルを使っています。GAMESSで計算する場合にはpc-chem.infoのホルムアルデヒドの励起状態計算が参考になります。こういう良質なコンテンツもっと増えてくんないかな。

input用のmol

exam34_energy.log
 OpenBabel09231115413D

  4  3  0  0  0  0  0  0  0  0999 V2000
    0.0100   -0.8670    0.0000 O   0  0  0  0  0  0  0  0  0  0  0  0
    0.0000    0.3455    0.0000 C   0  0  0  0  0  0  0  0  0  0  0  0
   -0.0100    0.9296   -0.9377 H   0  0  0  0  0  0  0  0  0  0  0  0
   -0.0100    0.9296    0.9377 H   0  0  0  0  0  0  0  0  0  0  0  0
  1  2  2  0  0  0  0
  2  4  1  0  0  0  0
  3  2  1  0  0  0  0
M  END

計算用スクリプト

import pygamess
import openbabel as ob
g = pygamess.Gamess()
obc = ob.OBConversion()
obc.SetInAndOutFormats("mol","mol")
mol = ob.OBMol()
obc.ReadFile(mol, "h2co.mol")
g.contrl['cityp'] = 'cis'
g.run_type('optimize')
g.basis_type('631+gdp')
g.gamess_input(mol)
newmol = g.run(mol)
print newmol.GetEnergy()
obc.WriteFile(newmol,'h2co_singlet.mol')

励起状態のホルムアルデヒドの安定構造は若干ピラミッド型の構造を取るって知ってた?

h2co

ところで、光異性化のサンプルとして面白いのはやっぱスチルベンかなぁと思ったんだけど、HOMO-LUMOの2電子励起を考慮しないといけないらしいので、CISじゃ計算できないじゃんと。

もう少し面白いサンプルないかなぁ。

Ninety-Nine Scala Problems (P01 - P10)

S-99を解く。Scalaは基本は関数型で考えて、どうしようもないときにはOOPに逃げられるのがいいですね。

//1
def last[A](ls:List[A]): A = ls.last

println("s1: " + last(List(1, 1, 2, 3, 5, 8)))

//2
def penultimate[A](ls:List[A]): A = ls.init.last

println("s2: " + penultimate(List(1, 1, 2, 3, 5, 8)))

//3
def nth[A](n:Int, ls:List[A]): A = if (n == 0) ls.head else nth(n-1,ls.tail)

println("s3: " + nth(2, List(1, 1, 2, 3, 5, 8)))

//4
def length[A](ls:List[A]): Int = ls.length

println("s4: "+ length(List(1, 1, 2, 3, 5, 8)))

//5
def reverse[A](ls:List[A]): List[A] = {
  def reverse2[A](ls:List[A],ls2:List[A]): List[A] = ls match {
      case Nil => ls2 
      case (head::tail) => reverse2(tail,head::ls2)
    }
  reverse2(ls,Nil)
}
println("s5: " + reverse(List(1, 1, 2, 3, 5, 8)))

//6
def isPalindrome[A](ls:List[A]): Boolean = ls == reverse(ls)

println("s6: " +  isPalindrome(List(1, 2, 3, 2, 1)))

//7
def flatten(ls: List[Any]): List[Any] = ls flatMap {
  case ms:List[_] => flatten(ms)
  case e => List(e)
}

println("s7: " + flatten(List(List(1, 1), 2, List(3, List(5, 8)))))

//8
def compress[A](ls:List[A]): List[A] = ls match {
  case Nil    => ls
  case head::tail => head::compress(tail.dropWhile(_ == head))
}

println("s8: " + compress(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)))

//9
def pack[A](ls:List[A]): List[List[A]] = ls match {
  case Nil => Nil
  case head::tail => ls.takeWhile(_ == head) :: pack(tail.dropWhile(_ == head))
}

println("s9: " + pack(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)))

//10
def encode[A](ls: List[A]): List[(Int, A)] = pack(ls) map {e => (e.length, e.head)}

println("s10: " + encode(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)))

「はじめて読む486」を読んでいる

Linuxカーネル2.6解読室の流れで読み始めた。

ProductName はじめて読む486―32ビットコンピュータをやさしく語る
蒲地 輝尚
アスキー / 2548円 ( 1994-09 )


Linuxも色々勉強しておかないといけない。

ProductName Linuxカーネル2.6解読室
高橋浩和
ソフトバンククリエイティブ / 5670円 ( 2006-11-18 )


そしてこれはまだ読んでいない、積んである。