同じ数字でできている5組の3乗数をみつける問題。
これも全数アタック
Hashを使って分類する方法を採った。
3乗数を作って、含まれている数をリストにしてソートしたものをキーにして、Hashに入れる。
Hashに入れたときに、5つたまったらそれが答え。
- num 9
適当なところで9から始めた。 意味は無い。
- res-map
格納用Hash
- num-key
キー。 3乗して数字のリストにしてソートしたもの。
あとは、キーのところに望みの数-1個 ( いまのやつがあるから -1) になっているかどうか確認しながら、再帰で回す。
これも全数アタック
Hashを使って分類する方法を採った。
3乗数を作って、含まれている数をリストにしてソートしたものをキーにして、Hashに入れる。
Hashに入れたときに、5つたまったらそれが答え。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; Problem 62 : 2011/11/17 | |
;; "Elapsed time: 2139.92309 msecs" | |
(defn pe62 [tgt-count] | |
(loop [num 9 | |
res-map {}] | |
(let [cubed (* num num num) | |
num-key (sort (num-to-list cubed))] | |
(if (= (dec tgt-count) (count (res-map num-key))) | |
(cons num (res-map num-key)) | |
(recur | |
(inc num) | |
(assoc res-map num-key (cons num (res-map num-key)))))))) |
- num 9
適当なところで9から始めた。 意味は無い。
- res-map
格納用Hash
- num-key
キー。 3乗して数字のリストにしてソートしたもの。
あとは、キーのところに望みの数-1個 ( いまのやつがあるから -1) になっているかどうか確認しながら、再帰で回す。
0 コメント:
コメントを投稿