โจทย์ สามเหลี่ยมปาสคาล

  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.
  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.

จาก http://www.codenone.com/node/151

เขียนโดยใช้ hash เข้ามาช่วย
จะได้ช่วย cache
ลดความโหดร้ายในการ recursive

hash ของ ruby มันมีดีอยู่อย่าง
ก็คือ สามารถกำหนด closure ที่จะ run
กรณีที่มีการอ้างถึง key ที่ไม่มีอยู่ใน hash ได้
เช่น

h = Hash.new do |hash, key|
 hash.key = 'hi'
end
 
h['xxxx']  # => 'hi'
h['anything'] # => 'hi'

ดังนั้นสามเหลี่ยม pascal ก็เลยเขียนแบบนี้

tri = Hash.new do |hash, key|
  col,row = key[0],key[1]
  if col == 1 || col == row
    hash[key] = 1
  elsif col > row
    hash[key] = 0
  else
    hash[key] = hash[[col, row-1]] + hash[[col-1, row-1]]
  end
end

ลอง print ผลลัพท์ดู

for i in 1..10
  for j in 1..10
    print "#{tri[[j,i]]} "
  end
  puts ""
end

:Note param ที่เป็น col,row มันฝึนความรุ้สึกนิดๆ
ชอบลำดับ row,col มากกว่า

หาเจอแล้ว วิธีนี้มีคนเขาเรียกกันว่า "Memoize"
(เมื่อวานหาตั้งนาน นึกว่าสะกด "Memorize")


Links
Cheap Ruby memoize using Hash default block
Using Hashes to Memoize

ข้างบน มีสะกดผิดนะ
hash.key = 'hi' => hash[key]

veer's picture

ท่า memorization ของ Ruby เจ๋งดี

veer ลองเขียน memoze ของ scheme ดูสิ
เจ๋งดีเหมือนกันนะ ใช้ function ครอบ (function return function)
ผมเห็นเขาเขียนกัน 10 กว่าบรรทัดเอง

ย้าย Codenone

ประกาศย้าย Codenone ไปใช้ Forum ของ Blognone แทนครับ ตามไปตั้งกระทู้ต่อได้ที่ Codenone Forum (รายละเอียดอ่านจากกระทู้ ย้าย Codenone ไปรวมกับ Blognone)

กระทู้เก่าๆ จะย้ายตามไปในภายหลัง ตอนนี้ปิดการโพสต์กระทู้ไว้ เหลือไว้เฉพาะอ้างอิงเท่านั้น