Emacs Lisp, Perl, Python: Building a Multiplication Table

So, i was reading Jon Snader (aka jcs)'s blog @ irreal.org, which lead me to watch a video of so-called VimGolf, but using emacs:

  • VimGolf in Emacs e003: Multiplication Table (2011-07) By Tim Visher. @ Source vimeo.com

The task is to generate a multiplication table like this:

1   2   3   4   5   6   7   8   9   10
2   4   6   8   10  12  14  16  18  20
3   6   9   12  15  18  21  24  27  30
4   8   12  16  20  24  28  32  36  40
5   10  15  20  25  30  35  40  45  50
6   12  18  24  30  36  42  48  54  60  
7   14  21  28  35  42  49  56  63  70
8   16  24  32  40  48  56  64  72  80
9   18  27  36  45  54  63  72  81  90
10  20  30  40  50  60  70  80  90  100

I thought this is interesting.

For this particular problem, i thought the most simple and practical way is just to use a programing language to spit it out. So i quickly wrote this:

(let (x i )
  (setq x 1 )
  (while (< x 10)
    (setq i 1 )
    (while (< i 10)
      (insert (format "%2d " (* x i)))
      (setq i (1+ i) )
      )
    (insert "\n")
    (setq x (1+ x) )
    )
  )

then just select the text and call “eval-region”. Or, with cursor at the end, call “eval-last-sexp” 【Ctrl+x Ctrl+e】.

the output is this:

 1  2  3  4  5  6  7  8  9 
 2  4  6  8 10 12 14 16 18 
 3  6  9 12 15 18 21 24 27 
 4  8 12 16 20 24 28 32 36 
 5 10 15 20 25 30 35 40 45 
 6 12 18 24 30 36 42 48 54 
 7 14 21 28 35 42 49 56 63 
 8 16 24 32 40 48 56 64 72 
 9 18 27 36 45 54 63 72 81 

Lisp is a bit verbose for this kinda thing due to the nested syntax. But you can write it in perl, python, ruby, bash, or any dynamic lang quickly, and press a button to have emacs call it and insert the result.

here's a python version:

for x in range(1,10):
    for i in range(1,10): 
        print "%(n)2d" % {"n":x*i},
    print "\n",

You can save this in a file, for example 〔temp.py〕. Then type 【Ctrl+u Alt+| python temp.py】, then it'll insert the output in your cursor position. (The 【Alt+|】 is the hotkey for “shell-command-on-region”. The 【Ctrl+u】 is “universal-argument”. When the command “shell-command-on-region” gets a empty argument, it'll insert output in buffer. Normally, it places output in the “*Messages*” buffer.)

Here's a perl version:

for $x (1..9) {
  for $i (1..9) {
    printf "%3d", $x*$i, " ";
  }
  print "\n";
}

Popular posts from this blog

11 Years of Writing About Emacs

does md5 creates more randomness?

Google Code shutting down, future of ErgoEmacs