problem 33

いまいち美しくない。

Prelude List> let f a b c d = ((a==c && (a*10+b)/(c*10+d)==b/d)||(a==d&&(a*10+b)/(c*10+d)==b/c)||(b==c&&(a*10+b)/(c*10+d)==a/d)||(b==d&&(a*10+b)/(c*10+d)==a/c))&&(b/=0&&d/=0)&&(a/=c&&b/=d) in  map product $ transpose [[x,y]|x<-[10..99],y<-[10..99], div x y<1,f (read [(show x)!!0]) (read [(show x)!!1]) (read [(show y)!!0]) (read [(show y)!!1])]
[387296,38729600]
it :: [Integer]
(0.20 secs, 124395232 bytes)

rubyの car,cdr もしくは haskellにおける head tail last init

rubyの car,cdr もしくは haskellにおける head tail last initについて

haskellにおける head tail lastはそれぞれ

>> [1, 2, 3, 4, 5].first
=> 1
>> [1, 2, 3, 4, 5].drop(1)
=> [2, 3, 4, 5]
>> [1, 2, 3, 4, 5].last
=> 5

だとおもう。でもなんかinit(最後の要素をのぞく)がmodule Enumerableになさそう。

>> module Enumerable ; def init ; self.take(self.size-1) ; end; end
=> nil
>> [1, 2, 3, 4, 5].init
=> [1, 2, 3, 4]

なんでないのかな。せめて drop_from_last(n)みたいなのでもあればいいのに…(last->behindかな?)

rubyのscanはブロック無のほうが便利

String.scan(re){ブロック}がstringを返すのでStringオブジェクトを拡張した。

class String
  def scanA(exp)                # scan(re)ブロック無しと同じ                                                             
    r=[]
    scan(exp){|i|r.push(yield i)}
    r
  end
end

そしたら。ブロックなしのscan(re)は返り値が配列だったorz

>> "abcde".scan(/../)
=> ["ab", "cd"]
>> "abcdefghi".scan(/(..)./)
=> [["ab"], ["de"], ["gh"]]
>> "abcdefghi".scan(/(..)(.)/)
=> [["ab", "c"], ["de", "f"], ["gh", "i"]]

terminalにて画像を表示する

terminalにて画像を表示する

カラーで表示

% sudo apt-get install caca-utils
% img2txt -W `tput cols` ubuntu_logo_blue.png

tputにてterminfoから端末の表示幅を取得している。
ちなみに 行数はlines

モノクロで表示

% sudo apt-get install imagemagick aview
% convert ubuntu_logo_blue.png pnm:- | aview

aviewはローカルで動かしたとき別窓が開く点が難点
コピーするかどうか判別するときいいかもしれない。

window版のemacs使ったほうがましという説もある。

rubyでuniq -c

rubyでuniq -cをやる

>> [1,2,2,1,2,3,4,2,1,2,4,3,1,3].inject(Hash.new(0)){|r,i|r[i]+=1;r}
=> {1=>4, 2=>5, 3=>3, 4=>2}

最後にrを評価するのではまった。

>> {1=>2}[1]+=1
=> 3

だもんな…

別解

>> [4,1,2,2,1,2,3,4,2,1,2,4,3,1,3].group_by{|i|i}.map{|k,v|[k,v.size]}
=> [[4, 3], [1, 4], [2, 5], [3, 3]]

injectの勝ち

追記 2011/06/18 00:18:57:

$ ruby18 -vlne '(h||=Hash.new(0))[$_]+=1;END{for k,v in h do print k," ",v end}' A
ruby 1.8.7 (2008-10-14 revision 18426) [i686-linux]
yahoo 2
google 1
goo 1
msn 2

以前にメーリングリストであったらしい。

 (h||=Hash.new(0))[$_]+=1

これはすごいな。||= の使い方わすれてた。