讀完《中國歷代政治得失》

| Comments

錢穆有文俠風,讀這本書,能看到這樣一個影子,上馬擊狂胡,下馬草軍書。他也是個民族主義者,提到元清,幾乎沒一句好話。所以要貫通國史,還得多讀讀別的書。總體來說,讀這本書時常感醍醐灌頂,為習國史者必讀。

讀完《中國史綱》

| Comments

自序中對治史的方法論讓我受益匪淺,本書語氣平和、娓娓道來,像講故事一樣講曆史,但又嚴謹、廣博、不膚淺,風格和其它史書大不一樣,我一直理想中的史書就是這樣,不要給曆史背太重的包袱,不要帶著一定要學點什麽的目的讀曆史。

本書的缺點是詳略失當。有些地方太簡略,比如匈奴的衰落,五單于爭立一筆帶過。有些地方太詳細,鴻門宴幾乎是史記的譯文。作爲一部通史,應該有大曆史觀,能站在較高的層面上把曆史的脈絡梳理清楚。

讀完《莊子今注今譯》

| Comments

很好的注本,有些字句的翻譯有點兒晦澀。莊子的思想超越了老子,想把莊子的思想理解透徹很難。

Project Euler Problem 25 Solved

| Comments

1000-digit Fibonacci number

The Fibonacci sequence is defined by the recurrence relation:

Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.

Hence the first 12 terms will be:

F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144

The 12th term, F12, is the first term to contain three digits.

What is the first term in the Fibonacci sequence to contain 1000 digits?

Solution

To be progmatic, take the brute-force approach.

Furthermore, here gives a formula which solves this problem, but it’s too mathematical.

讀完《國史大綱》

| Comments

錢穆先生主張以誠敬心審視國史和傳統文化,一生為故國招魂。抗戰流亡,筆耕不輟,雖然這本書只是一本歷史教科書,但是高屋建瓴的大歷史觀讓我受益匪淺,很多東西是讀史料不能學到的。《國史大綱》所思所言,堪稱國史良心。

使用lsyncd同步文件

| Comments

lsyncd全稱“Live Syncing Daemon”,是Linux下的文件自动同步工具,同时支持SSH、rsync的实现方式。相对于rsync+inotify,它速度更快,也更穩定。

對於SSH的方式,需要目標機器中已啟動SSHD,並把源機器上的公鑰加到目標機器root用戶的authorized_keys中,私鑰應放在源機器上運行lsyncd的用戶的.ssh目錄中,密鑰放錯了用戶,會導致無法同步。

然後就是在源機器上創建配置文件,lsyncd的配置文件是個lua腳本:

lsyncd.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
settings{
    pidfile = "/var/log/lsyncd/lsyncd.pid",
    logfile = "/var/log/lsyncd/lsyncd.log",
    statusFile = "/var/log/lsyncd/lsyncd-status.log",
    statusInterval = 1,
    maxDelays = 1,
    -- nodaemon = true,
}

sync{
    default.rsyncssh,
    source = "/home/monk/workspace",
    host = "192.168.1.3",
    targetdir = "/var/www/workspace",
    exclude={ ".*", "*.tmp" },
    rsync = {
        compress = false,
        _extra = {"--bwlimit=50000"},
    }
}

然後啟動lsyncd:

1
sudo lsyncd /etc/lsyncd.conf

Project Euler Problem 24 Solved

| Comments

Lexicographic permutations

A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:

012 021 102 120 201 210

What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?

Solution

p24.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/python2
# -*- coding: utf-8 -*-

from math import factorial


def get_perm(digits, number):
    if len(digits) == 0:
        return ''
    (perm, counter) = ('', factorial(len(digits) - 1))
    for digit in digits:
        if counter >= number:
            digits.remove(digit)
            perm += str(digit) + get_perm(digits, number)
            break
        number -= counter
    return perm


if __name__ == '__main__':
    import time
    startTime = time.time()
    perm = get_perm([d for d in range(10)], 1000000)
    print perm, '%sms' % ((time.time() - startTime) * 1000)
p24.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
function factorial($n) {
    $result = 1;
    for ($i = 2;$i <= $n;$i++) $result*= $i;
    return $result;
}

function get_perm($digits, $number) {
    $perm = "";
    $length = count($digits);
    $counter = factorial($length - 1);
    for ($i = 0;$i < $length;$i++) {
        if ($counter >= $number) {
            $segment = array_splice($digits, $i, 1);
            $perm = $segment[0] . get_perm($digits, $number);
            break;
        }
        $number-= $counter;
    }
    return $perm;
}

$startTime = microtime(true);
$digits = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
$perm = get_perm($digits, 1000000);
$costs = (microtime(true) - $startTime) * 1000;
echo "$perm ${costs}ms\n";
?>
p24.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main

import (
  "fmt"
  "strconv"
  "time"
)

func factorial(n int) int {
  result := 1
  for i := 2; i <= n; i++ {
      result *= i
  }
  return result
}

func get_perm(digits []int, number int) string {
  perm, length := "", len(digits)
  counter := factorial(length - 1)
  for i := 0; i < length; i++ {
      if counter >= number {
          digit := digits[i]
          digits = append(digits[:i], digits[i+1:]...)
          perm += strconv.Itoa(digit) + get_perm(digits, number)
          break
      }
      number -= counter
  }
  return perm
}

func main() {
  startTime := time.Now()
  digits := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  perm := get_perm(digits, 1000000)
  fmt.Println(perm, time.Now().Sub(startTime))
}

I’m the 57181st person to have solved this problem.

I’ve just advanced to Level 1. 61264 members (15.9%) have made it this far.

I have earned 1 new award:

The Journey Begins: Progress to Level 1 by solving twenty-five problems

Project Euler Problem 23 Solved

| Comments

Non-abundant sums

A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.

A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.

As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.

Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

Solution

Using sets instead of lists greatly improves performance in Python:

p23.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/python
# -*- coding: utf-8 -*-


def sum_proper_factors(n):
    (result, sqrt) = (1, n ** 0.5)

    (start, step) = n % 2 == 1 and (3, 2) or (2, 1)
    for i in range(start, int(sqrt) + 1, step):
        if n % i == 0:
            result += i + n / i

    if sqrt == int(sqrt):
        result -= sqrt

    return result


def main():
    (result, limit, abundants) = (0, 28124, set())

    for n in range(1, limit):
        if sum_proper_factors(n) > n:
            abundants.add(n)
        if not any(n - a in abundants for a in abundants):
            result += n

    print result


if __name__ == '__main__':
    import time
    startTime = time.time()
    main()
    print time.time() - startTime

Simulate sets using maps in Go:

p23.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main

import (
  "fmt"
  "math"
  "time"
)

func sum_proper_factors(n int) int {
  result, sqrt := 1, math.Sqrt(float64(n))

  start, step := 2, 1
  if n%2 == 1 {
      start, step = 3, 2
  }
  for i := start; i <= int(sqrt); i += step {
      if n%i == 0 {
          result += i + n/i
      }
  }

  if sqrt == float64(int(sqrt)) {
      result -= int(sqrt)
  }

  return result
}

func main() {
  result, limit, abundants, startTime := 0, 28124, make(map[int]bool), time.Now()

  for n := 1; n < limit; n++ {
      if sum_proper_factors(n) > n {
          abundants[n] = true
      }
      isSumOfTwoAbundants := false
      for k := range abundants {
          if abundants[n-k] == true {
              isSumOfTwoAbundants = true
              break
          }
      }
      if !isSumOfTwoAbundants {
          result += n
      }
  }

  fmt.Println(result, time.Now().Sub(startTime))
}

I’m the 49489th person to have solved this problem.

UltraBlog.vim v3.6.1: 文章分類自動補全

| Comments

春節期間收到兩個issue,一直拖到今天才有時間完成。

增加了一個功能,在文章編輯視圖的元數據中分類那行,使用熱鍵<C-X><C-U>自動完成文章的分類。在配置數組ub_blog中增加鍵值對“categories”,默認使用這一項的值實現自動完成,如下:

1
2
3
4
5
6
7
let ub_blog = {'login_name':'admin',
            \'password':'pass2011',
            \'url':'http://www.sample.com/',
            \'xmlrpc_uri':'xmlrpc.php',
            \'db':'$VIM/UltraBlog.db',
            \'categories': 'News|Computer|Image'
            \}

如果這一項不存在,將從博客中拉取分類數據。

自從遷移到Octopress,有兩年不用Wordpress了,沒想到居然還有人在用UltraBlog.vim