ある表記法に則った画像を回転する問題 - 第2回 オフラインリアルタイムどう書くの参考問題

問題

第2回 オフラインリアルタイムどう書くの参考問題 #勉強会 #どう書く #yhpg #Ruby #C - Qiita

ある表記法に則った2値画像データを時計回りに90度回転させてもとの表記に戻す問題。

解答

一行あたりの処理単位がめちゃくちゃだけど、スライシング多用でもともとわかりやすい処理じゃないので直さないキリッ。

def rotate_bit_image(notation):
    spseq = lambda seq, size: [seq[i:i+size] for i in range(0, len(seq), size)]
    x, d = notation.split(':')
    x = int(x)
    d = "".join(map(lambda x: bin(int(x, 16))[2:].zfill(4), d))
    b = d[x**2:]
    d = spseq(d[:x**2], x)
    d = "".join(map(lambda x: "".join(reversed(x)), zip(*d)))
    r = d+b
    return str(x)+":"+"".join(map(lambda x: hex(int(x, 2))[2:], spseq(r, len(r)/len(notation[2:]))))

適切な名前つける気力もなくなってきた。

配列をあるサイズで分割する方法はここを参考にした。
python 配列分割 - external storage

テスト

from nose.tools import eq_
import nose

def test_rotate_bit_image():
    eq_(rotate_bit_image('3:5b8'), '3:de0')
    eq_(rotate_bit_image('1:8'), '1:8')
    eq_(rotate_bit_image('2:8'), '2:4')
    eq_(rotate_bit_image('2:4'), '2:1')
    eq_(rotate_bit_image('2:1'), '2:2')
    eq_(rotate_bit_image('3:5d0'), '3:5d0')
    eq_(rotate_bit_image('4:1234'), '4:0865')
    eq_(rotate_bit_image('5:22a2a20'), '5:22a2a20')
    eq_(rotate_bit_image('5:1234567'), '5:25b0540')
    eq_(rotate_bit_image('6:123456789'), '6:09cc196a6')
    eq_(rotate_bit_image('7:123456789abcd'), '7:f1a206734b258')
    eq_(rotate_bit_image('7:fffffffffffff'), '7:ffffffffffff8')
    eq_(rotate_bit_image('7:fdfbf7efdfbf0'), '7:ffffffffffc00')
    eq_(rotate_bit_image('8:123456789abcdef1'), '8:f0ccaaff78665580')
    eq_(rotate_bit_image('9:112233445566778899aab'), '9:b23da9011d22daf005d40')

if __name__ == "__main__":
    nose.main()