2012-07-17 215 views
2

有时我想要生成随机数字(以空格分隔的格式),但我希望能够指定行数和列数。使用vim生成基于整数的随机数表?

我看到一些动力从这里产生一个随机数的单个实例(使用红宝石派生): http://mo.morsi.org/blog/node/299

“在当前行的末尾生成随机数

function! s:Rand(max) 
y a   
redir @b  
ruby << EOF 
    rmax = VIM::evaluate("a:max") 
    rmax = nil if rmax == "" 
    printf rand(rmax).to_s 
EOF 
redir END 
let @a = strpart(@a, 0, strlen(@a) - 1) 
let @b = strpart(@b, 1, strlen(@b) - 1) 
let @c = @a . @b 
.s/.*/\[email protected]/g 
endfunction 

怎么可能我们平凡延伸这使得我能一方式

:兰特(6,6)

并从我的光标位置开始生成一个表格?

对于用户不知道,VIM需求+红宝石支持:Installing vim with ruby support (+ruby)

回答

3

循环通过x和y坐标,并提供随机数的最大值。

function! Rand(max) 
    redir @b 
ruby << EOF 
    rmax = VIM::evaluate("a:max") 
    rmax = nil if rmax == "" 
    printf rand(rmax).to_s 
EOF 
    redir END 
    let @a = strpart(@a, 0, strlen(@a) - 1) 
    let @b = strpart(@b, 1, strlen(@b) - 1) 
    let @c = @a . @b 
    return @c 
endfunction 

fun! RandTable(...) 
    for y in range(a:2) 
     for x in range(a:1) 
     if a:0 > 2 
      let rand = Rand(a:3) 
     else 
      let rand = Rand(10) 
     end 
     exe "norm i" . rand . " " 
     endfor 
     exe "norm Xi\<cr>" 
    endfor 
endfun 

command! -nargs=* Rand call RandTable(<f-args>) 

现在你可以使用:Rand 6 6:Rand 6 6 6其中第三个参数指定随机数的最大值。

4

我平时懒,只是这样做

od -iAn -w 12 /dev/urandom | head -n 30 

这将产生随机整数的3列线。当然你也可以拍一个命令到它,永远

fun! RTable(r,c) 
    exec 'r!od -iAn -w' . (4*a:c) . ' /dev/urandom | head -n ' . a:r 
endf 
command! -nargs=+ RTable call RTable(<f-args>) 

现在你可以在闲暇

RTable 5 5 
RTable 1 500 

+0

这是非常有效的,尤其是无需+红宝石支持,太糟糕了我不能有多个接受的答案! – 2012-07-18 05:50:50