ラベル groovy の投稿を表示しています。 すべての投稿を表示
ラベル groovy の投稿を表示しています。 すべての投稿を表示

2012年9月22日土曜日

GroovyのInheritConstructorsアノテーション

クラスにInheritConstructorsアノテーションを付加すると、親クラスが実装しているコンストラクタをコンパイル時に追加してくれます。

Fugaは、引数を2つうけるコンストラクタを持っていないが「InheritConstructors」を設定しているので、親クラスのHogeが実装しているコンストラクタが追加されていることがわかる。

import groovy.transform.InheritConstructors

class Hoge {

  def hoge1
  def hoge2

  Hoge(hoge1, hoge2) {
    println "Hoge.Hoge"
    this.hoge1 = hoge1
    this.hoge2 = hoge2
  }

  @Override
  public String toString() {
    return "Hoge{" +
            "hoge1=" + hoge1 +
            ", hoge2=" + hoge2 +
            '}';
  }
}

@InheritConstructors
class Fuga extends Hoge {
}

def fuga = new Fuga("hoge1", "hoge2")
println "fuga = ${fuga}"

GroovyのEqualsAndHashCodeアノテーション

equalsとhashCodeを生成してくれるアノテーション

EqualsAndHashCodeを付加してクラスを宣言します。

import groovy.transform.EqualsAndHashCode

@EqualsAndHashCode
class Person {

  String name
  String address
  Date birthDay
  String mailAddress

}

2012年9月16日日曜日

GroovyのTupleConstructorアノテーション

TupleConstructorを付加すると、属性(フィールド)値を引数に取るコンストラクタが追加されます。
コンストラクタの引数の順番は、フィールドの宣言の順番となります。

TupleConstructorを付加してクラスを宣言します。
import groovy.transform.TupleConstructor

@TupleConstructor
class Person {
  String name
  String address
  String email
  Date birthDay
}

使い方は、フィールドの宣言順に値を設定するだけ。
なお、Groovy2.0の新機能のTypeCheckedアノテーション(コンパイル時に型チェックをしてくれるやつ)を付加すると、ちゃんとコンパイルエラーになります。
class Hoge {

  @TypeChecked
  public static void main(String[] args) {

    def person = new Person('name', 'address', 'mail@mail.com', new Date())
  }
}

2012年9月14日金曜日

GroovyのToStringアノテーション

クラスに「ToString」アノテーションを付加すると、コンパイル時にtoStringメソッドが生成されます。

デフォルトでは、すべてのフィールドがtoStringメソッドで文字列変換されますが、アノテーションの属性を設定することで除外設定などもできます。

2012年7月22日日曜日

Project Euler-Problem22をgroovyで解いてみる

問題

http://odz.sakura.ne.jp/projecteuler/index.php?cmd=read&page=Problem%2022

問題を解いたプログラム

1行にすべての値が書かれているとは思わなかった・・・
def alphaRange = 'A'..'Z'
def index = 0
println new File('names.txt').readLines().join(",").split(",").sort().inject(0) {result, line ->
  result + line.split(",").sort().inject(0) {lineTotal, element ->
    lineTotal + (element.inject(0) {elementTotal, chr ->
      elementTotal + alphaRange.indexOf(chr) + 1
    } * (++index))
  }
}

2012年7月21日土曜日

Project Euler-Problem21をgroovyで解いてみる

問題

d(n)をnの真の約数の和と定義する。(真の約数とはn以外の約数のことである。)
もし、d(a) = b かつ d(b) = a (a ≠ b)を満たすとき、aとbは友愛数(親和数)であるという。

例えば、220の約数は1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110なのでd(220) = 284である。
また、284の約数は1, 2, 4, 71, 142なのでd(284) = 220である。

それでは10000未満の友愛数の合計を求めよ。

問題を解いたプログラム

def getSumAliquot(def num) {
  (1..(num / 2)).findAll {num % it == 0}.sum()
}

println((1..<10000).sum {
  def aliquot = getSumAliquot(it)
  it != aliquot && it == getSumAliquot(aliquot) ? aliquot : 0
})

2012年7月16日月曜日

Project Euler-Problem19をgroovyで解いてみる

問題

次の情報が与えられている。

1900年1月1日は月曜日である。
9月、4月、6月、11月は30日まであり、2月を除く他の月は31日まである。
2月は28日まであるが、うるう年のときは29日である。
うるう年は西暦が4で割り切れる年に起こる。しかし、西暦が400で割り切れず100で割り切れる年はうるう年でない。
20世紀(1901年1月1日から2000年12月31日)で月の初めが日曜日になるのは何回あるか。

問題を解いたプログラム

def current = Calendar.getInstance()
current.set(1901, 1, 1)

def end = Calendar.getInstance()
end.set(2000, 12, 31)

int sundayCount = 0
while (current <= end) {
  if (current.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
    sundayCount++
  }
  current.set(Calendar.MONTH, current.get(Calendar.MONTH) + 1)
}
println "sundayCount = ${sundayCount}"

Project Euler-Problem20をgroovyで解いてみる

問題

n × (n - 1) × ... × 3 × 2 × 1 を n! と表す。

100! の各桁の数字の合計を求めよ。。

問題を解いたプログラム

Problem16と同じような構造です。
def ret = (new BigInteger(100)..new BigInteger(1)).inject(new BigInteger(1)) {num1, num2 ->
  num1.multiply(num2)
}.toString().collect{Integer.valueOf(it)}.sum()

println "ret = ${ret}"


解けない問題が増えてきた

2012年7月14日土曜日

Project Euler-Problem16をgroovyで解いてみる

問題

15 = 32768 であり、これの各数字の合計は 3 + 2 + 7 + 6 + 8 = 26 となる。

同様にして、21000 の各数字の合計を求めよ。

問題を解いたプログラム

クロージャがあるから簡単にかけてますが、JavaのAPIを使っているだけです。
import java.text.DecimalFormat

def format = new DecimalFormat("#")
println format.format(new BigInteger(2).pow(1000)).collect {Integer.valueOf(it)}.sum()

7/16:足し込むところを、collectionのsum関数を使うように変更。

2012年6月24日日曜日

Project Euler-Problem14をgroovyで解いてみる

問題

正の整数に以下の式で繰り返し生成する数列を定義する。

n → n/2 (n が偶数)

n → 3n + 1 (n が奇数)

13からはじめるとこの数列は以下のようになる。

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
13から1まで10個の項になる。 この数列はどのような数字からはじめても最終的には 1 になると考えられているが、まだそのことは証明されていない(コラッツ問題)

さて、100万未満の数字の中でどの数字からはじめれば一番長い数列を生成するか。

注意: 数列の途中で100万以上になってもよい

問題を解いたプログラム

最初何も考えずに作ったら終わる気配が全くなく・・・。次にListで生成した数列自体をキャッシュしたが、全く意味がなく。最後に、Hashに生成した数列のサイズをキャッシュするように。これでなんとか処理が終わるようになった。
result = [:]

def next(long num) {
  num % 2 == 0 ? num / 2 : num * 3 + 1
}

def makeNumSeq(long num) {
  def count = 0
  long temp = num
  while (temp > 1) {
    temp = next(temp)
    def cacheCount = result[temp]
    if (cacheCount) {
      count += cacheCount
      break
    }
    count++
  }
  result[num] = count
}

(999999..1).each {it
  makeNumSeq(it)
}

println result.max {it.value}

2012年6月17日日曜日

Project Euler-Problem13をgroovyで解いてみる

問題

以下の50桁の数字100個の総和の上位10桁を求めよ。

37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690

問題を解いたプログラム

ヒアドキュメントを入力として、改行で分割した値を足し込んだ結果の上位10桁を取得してます。
input = """37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690"""

println input.split(/\n/).inject(0.0) {n1, n2 -> n1.add(new BigDecimal(n2))}.toString().substring(0, 10)

2012年6月9日土曜日

Project Euler-Problem12をgroovyで解いてみる

問題

三角数の数列は自然数の和で表わされ、7番目の三角数は 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28 である。 三角数の最初の10項は

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
となる。

最初の7項について、その約数を列挙すると、以下のとおり。

 1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

これから、7番目の三角数である28は、6個以上の約数をもつ最初の三角数であることが分る。
では、501 個以上の約数をもつ最初の三角数はいくらか。

問題を解いたプログラム

def getAliquot(def num) {
  def results = (1..Math.sqrt(num)).findResults {
    if (num % it == 0) {
      it
    }
  }
  results.size() * 2
}

def num = 1
def triangularNumbers = num
while (getAliquot(triangularNumbers) <= 500){
  num++
  triangularNumbers += num
}

println "num = ${triangularNumbers}"

2012年5月29日火曜日

Project Euler-Problem11をgroovyで解いてみる

問題

08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48

上の 20 × 20 の数字のなか、赤くマークされた数字の積は 26 × 63 × 78 × 14 = 1788696 となる。

上下左右斜めのいずれかの方向で連続する4つの数字の積のうち最大のものを求めよ。

問題を解いたプログラム

ベタベタな感じでしかとけません・・・。
def input = [
        [8, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 8],
        [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00],
        [81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65],
        [52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91],
        [22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
        [24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
        [32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
        [67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21],
        [24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
        [21, 36, 23, 9, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95],
        [78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 9, 53, 56, 92],
        [16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57],
        [86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
        [19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40],
        [04, 52, 8, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
        [88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
        [04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36],
        [20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16],
        [20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54],
        [01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48]]

def size = 20
def ret = (0..<size).findResults {row ->
  (0..<size).findResults {col ->
    [
            col < 17 ? (input[row][col..<col + 4]).inject(1) {n1, n2 -> n1 * n2} : 0,
            col < 17 && row < 17 ? [input[row][col], input[row + 1][col + 1], input[row + 2][col + 2], input[row + 3][col + 3]].inject(1) {n1, n2 -> n1 * n2} : 0,
            col >= 3 && row < 17 ? [input[row][col], input[row + 1][col - 1], input[row + 2][col - 2], input[row + 3][col - 3]].inject(1) {n1, n2 -> n1 * n2} : 0,
            row < 17 ? [input[row][col], input[row + 1][col], input[row + 2][col], input[row + 3][col]].inject(1) {n1, n2 -> n1 * n2} : 0
    ].max()
  }.max()
}.max()
println(ret)

2012年5月27日日曜日

Project Euler-Problem10をgroovyで解いてみる

問題

10以下の素数の和は2 + 3 + 5 + 7 = 17である.
200万以下の全ての素数の和を計算しなさい.

問題を解いたプログラム

処理時間はものすごくかかります。(3分弱かな)
import common.Prime

def prime = new Prime()
def sum = prime.primes(2000000).sum()
println "sum = ${sum}"

Primeクラスはのprimesはiteratorを返すようにしてます。
package common

class Prime {

  def primes(int max) {
    return new Iterator<Long>() {

      def primes = []

      boolean hasNext() {
        def start = primes ? primes.max() + 1 : 2
        def result = (start..max).findResult {
          if (isPriem(it)) {
            it
          }
        }
        if (result) {
          primes << result
          primes.last() < max
        } else {
          false
        }
      }

      Long next() {
        primes.last()
      }

      void remove() {
        throw new UnsupportedOperationException()
      }

      private def isPriem(int num) {
        if (num == 2) {
          true
        } else if (num % 2 == 0) {
          false
        } else {
          def sqrt = Math.sqrt(num).toInteger()
          primes.findResult(true) {
            if (it > sqrt) {
              true
            } else if (num % it == 0) {
              false
            }
          }
        }
      }
    };
  }
}

2012年5月13日日曜日

Project Euler-Problem9をgroovyで解いてみる

問題

ピタゴラスの三つ組(ピタゴラスの定理を満たす自然数)とはa<b<cで
a² + b² = c²
を満たす数の組である.

例えば, 3² + 4² = 9 + 16 = 25 = 5²である.

a + b + c = 1000となるピタゴラスの三つ組が一つだけ存在する. このa,b,cの積を計算しなさい.

問題を解いたプログラム

aとbをループでまわして、cは計算で求めてと単純な感じで。無駄にループしてない文そこまで遅くない。
def ret = (1..999).findResult { a->
  ((a + 1) .. 1000).findResult() {b ->
    def c = 1000 - a - b
    if (a * a + b * b == c * c) {
      a * b * c
    }
  }
}
println "ret = ${ret}"

[Groovy]booleanを返す式

Javaと比べて、オブジェクトの状態チェック(nullや空かなど)が簡単にできる。

//******************************************************************************
// 文字列
//******************************************************************************
assert !null      // nullはfalse
assert !''        // 空文字もfalse
assert 'a'        // 1文字以上あるとtrue
assert """
"""               // 改行があるからtrue

//******************************************************************************
// 数値
//******************************************************************************
assert !0         // 0はfalse
assert 0.1        // 非0はtrue
assert 1L         // 非0はtrue

//******************************************************************************
// コレクション系
//******************************************************************************
assert ![]        // 空のリストはfalse
assert ![:]       // 空のMapはfalse
assert [1]        // 要素があるのでtrue
assert [1:1]      // 要素があるのでtrue

//******************************************************************************
// オブジェクト
//******************************************************************************
assert new Object()           // null意外なのでtrue
assert !new Object() {        // asBooleanでfalseを返しているので、常にfalse
  boolean asBoolean() {false}
}

2012年5月12日土曜日

Project Euler-Problem8をgroovyで解いてみる

問題

以下の1000桁の数字から5つの連続する数字を取り出して その積を計算する。そのような積の中で最大のものの値はいくらか

73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450

EX 6桁の数123789なら、1*2*3*7*8と2*3*7*8*9の二通りとなり、後者の2*3*7*8*9=3024が最大の積となる。

問題を解いたプログラム

Iteratorで連続する5つの数字の積を返して、その最大値を求めてます。
String.metaClass.next = {int size ->
  def str = delegate.toString().replaceAll(/\r|\n/, "")
  if (size > str.size()) {
    return null
  }
  new Iterator<Integer>() {
    def result = []
    def pos = 0
    boolean hasNext() {
      pos < str.size()
    }
    Integer next() {
      if (result.isEmpty()) {
        (str[0..<size]).each {result << it.toInteger()}
        pos = 5
      } else {
        result.remove(0)
        pos <= str.size() ? result.add(str[pos++].toInteger()) : null
      }
      result.inject(1) {n1, n2 -> n1 * nn}
    }

    void remove() {
      throw new UnsupportedOperationException("unsupported remove.")
    }
  }
}
def input = """
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
"""

println(input.next(5).inject(0) {max, n -> Math.max(max, n)})

2012年5月5日土曜日

Project Euler-Problem7をgroovyで解いてみる

問題

素数を小さい方から6つ並べると 2, 3, 5, 7, 11, 13 であり、6番目の素数は 13 である。

10001 番目の素数を求めよ。

問題を解いたプログラム

なんのひねりもないコードですが・・・
def primes = []
def num = 2;
while (primes.size() < 10001) {
  if (!primes.find {num % it == 0}) {
      primes << num
  }
  num++
}
println primes.last()

2012年5月4日金曜日

Groovyでカリー化

クロージャのcurryメソッドを使うとカリー化ができる。
def sum = {n1, n2 -> n1 + n2}
def curry = sum.curry(100)  // 最初のパラメータを100で固定してカリー化
println curry(100)  // 200
println curry(200)  // 300

Project Euler-Problem6をgroovyで解いてみる

問題

最初の10個の自然数について、その和の二乗と、二乗数の和は以下の通り。

1² + 2² + ... + 10² = 385
(1 + 2 + ... + 10)² = 3025
これらの数の差は 3025 - 385 = 2640 となる。

同様にして、最初の100個の自然数について和の二乗と二乗の和の差を求めよ。

問題を解いたプログラム

ありきたりな感じに、1から100までの和の二乗と、1から100までのそれぞれの二乗の和を求めてから差をもとめてるだけ。
def ret = (long) Math.pow((1..100).sum(), 2) - (1..100).inject(0) {n1, n2 -> n1 + (int) Math.pow(n2, 2) }
println "ret = $ret"