challenge バイナリクロック

 時刻を二進数相当の表現で出力する時計アプリケーションを書いてください。
 20:18の場合,例えば以下の様な出力をするイメージです。

出力例:
 ■□■□□
□■□□■□
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#! c:\ruby\bin\ruby.exe -Ks

String.class_eval do |string|
    def words
        self.split(//)
    end
    def fix_width(width, padding)
        (self.words.size > width) ? self : (padding * (width - self.words.size) + self)
    end
end

Fixnum.class_eval do |fixnum|
    alias :to_s_orig :to_s
    def to_s(base, width)
        binary = self.to_s_orig(base).fix_width(width, "0")
    end
end

class BinaryClock
    attr_accessor :now
    def initialize
        self.now = Time.now
    end
    def print
        output(self.now.hour.to_s(2, 5))
        output(self.now.min.to_s(2, 6))
    end
private
    def output(binary)
        puts binary.words.map { |f| f == "0" ? "□" : "■" }.join.fix_width(6, " ")
    end
end

BinaryClock.new.print

Posted feedbacks - Bash

しつこく強引な1liner

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
function toBIN { \
  v=$1; \
  s=""; \
  while [ $v -gt 0 ];do \
    let "x = v>>1"; \
    let "b = v ^ x<<1"; \
    s=$b$s; \
    v=$x; \
  done; \
  echo $s; \
}; \
d=`date '+%H %M %S'`; \
c=" "; \
for V in `echo ${d}`;do \
  V=`toBIN $V`; \
  while [ ${#V} -lt 6 ];do \
    V=${c}${V}; \
  done; \
  echo ${V}|sed s/0/□/g|sed s/1/■/g; \
  c="0"; \
done;

もう少し短くしてみました。

 Linuxのprintf(シェルビルトインのものと /usr/bin/printf)では
フラグ文字 0と変換指定子 sを組み合わせても意図した結果が得ら
れなかったので、 dで代用しました。そのため、bcの返す値の最上
位桁が 0にならないことに依存します。

# AIX 4.3.3.0, HP-UX B.11.00, Linux 2.4.2, SunOS 5.5.1で動作
# を確認。
1
for t in `date '+%H %M %S'`; do printf '%06d\n' `echo "obase=2; $t" | bc` | tr '01' '.*'; done

6桁固定、時分秒。
{0,1}を並べることで2進数の列が得られます。
$ echo {0,1}{0,1}
00 01 10 11
あとは配列に入れれば10進→2進変換のできあがり。
1
2
3
4
5
bins=({□,■}{□,■}{□,■}{□,■}{□,■}{□,■})
time=(`date "+%H %M %S"`)
for i in 0 1 2; do
  echo ${bins[time[i]]}
done

xbmで出力すればHHMMSSを16進にして流し込むだけで済むはず、との発想から。

xbmでは左から右に描くので、ビット左右反転をすべきなのですが ImageMagickで横着しています。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/bin/bash 

date=`date '+%H %M %S'`

echo -e "#define b_width 6\n\
#define b_height 3\n\
static char b_bits[] = {\n\
"`printf '0x%X,' $date`"\n\
};" \
|display -flop -sample 120x240 -

Index

Feed

Other

Link

Pathtraq

loading...