【问题标题】:Using vim to generate tables of integer-based random numbers?使用 vim 生成基于整数的随机数表?
【发布时间】:2012-07-17 20:04:48
【问题描述】:

有时我想生成随机数(以可用空格分隔的格式),但我希望能够指定行数和列数。

我从这里看到了一些生成随机数的单个实例的动机(源自使用 ruby​​): 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/.*/\=@c/g
endfunction

我们怎样才能将这种琐碎的事情扩展到我可以打字的方式

:兰德(6,6)

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

对于不知情的用户,vim 需要 +ruby 支持:Installing vim with ruby support (+ruby)

【问题讨论】:

    标签: ruby vim


    【解决方案1】:

    我通常很懒,只是做一些类似的事情

    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
    

    等等

    【讨论】:

    • 这非常有效,尤其是不需要 +ruby 支持,太糟糕了,我不能有多个接受的答案!
    【解决方案2】:

    循环通过 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,其中第三个参数指定随机数的最大值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-26
      • 2018-10-09
      • 2014-08-22
      • 2011-05-10
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      相关资源
      最近更新 更多