Skip to content

Instantly share code, notes, and snippets.

@suzuki-kei
Created November 4, 2013 10:49
Show Gist options
  • Save suzuki-kei/7300966 to your computer and use it in GitHub Desktop.
Save suzuki-kei/7300966 to your computer and use it in GitHub Desktop.
vim script の習作です。 現在のカーソル位置にシェルピンスキーの三角形を挿入します。
"
" 現在のカーソル位置にシェルピンスキーの三角形を挿入する.
"
" MIT Lisence
"
" [使い方]
"
" 1. :source sierpinski.vim
" 2. :Sierpinski
"
function! s:main(...)
let l:width = s:nth_element(a:000, 0, 32)
let l:height = s:nth_element(a:000, 1, 32)
let l:field = s:create_field(l:width, l:height)
call s:render(l:field)
endfunction
function! s:render(field)
for y in range(len(a:field))
execute ":normal i" . a:field[y] . "\n"
endfor
endfunction
function! s:nth_element(xs, i, default)
return len(a:xs) <= a:i ? a:default : a:xs[a:i]
endfunction
function! s:create_field(width, height)
let l:field = []
for y in range(a:height)
let l:line = ""
for x in range(a:width)
if s:bitwise_xor(x, y) == 0
let l:line = l:line . "++"
else
let l:line = l:line . " "
endif
endfor
call add(l:field, l:line)
endfor
return l:field
endfunction
function! s:bitwise_xor(lhs, rhs)
let l:lhs_bits = s:integer_to_bits(a:lhs)
let l:rhs_bits = s:integer_to_bits(a:rhs)
let l:result_bits = []
for i in range(len(l:lhs_bits))
if l:lhs_bits[i] + l:rhs_bits[i] == 2
call add(l:result_bits, 0)
else
call add(l:result_bits, 1)
endif
endfor
return s:bits_to_integer(l:result_bits)
endfunction
function! s:integer_to_bits(x)
let l:x = a:x
let l:bits = []
for i in range(32)
call insert(l:bits, l:x % 2 == 1, 0)
let l:x = l:x / 2
endfor
return l:bits
endfunction
function! s:bits_to_integer(bits)
let l:value = 0
for i in range(len(a:bits))
let l:value = l:value * 2 + (a:bits[i] == 0)
endfor
return l:value
endfunction
command! -nargs=* Sierpinski :call s:main(<f-args>)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment