Multiplication Table [Groovy]

  • 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.

สวัสดีครับ สมาชิกใหม่ขอฝากเนื้อฝากตัวด้วยนะครับ
เริ่ม Post แรก ด้วย Groovy แก้ปัญหาสูตรคูณ

คำนวณอย่างเดียว

(a = 1..12).collect{a*.multiply(it)}

คำนวณและพิมพ์ด้วย

((a = 1..12).collect{a*.multiply(it)}.collect{(it*.toString()).collect{it.padLeft(4)}}).collect{it.join()}.each{println it}

ผลการพิมพ์

   1   2   3   4   5   6   7   8   9  10  11  12
   2   4   6   8  10  12  14  16  18  20  22  24
   3   6   9  12  15  18  21  24  27  30  33  36
   4   8  12  16  20  24  28  32  36  40  44  48
   5  10  15  20  25  30  35  40  45  50  55  60
   6  12  18  24  30  36  42  48  54  60  66  72
   7  14  21  28  35  42  49  56  63  70  77  84
   8  16  24  32  40  48  56  64  72  80  88  96
   9  18  27  36  45  54  63  72  81  90  99 108
  10  20  30  40  50  60  70  80  90 100 110 120
  11  22  33  44  55  66  77  88  99 110 121 132
  12  24  36  48  60  72  84  96 108 120 132 144

เพิ่งหัดเขียน Groovy นะครับ code เลยไม่แปลกเท่าไหร่ และคงไม่สั้นที่สุด
อยากให้คนใช้ Groovy ช่วยแก้ หรือเพิ่มให้ด้วยนะครับ

[แก้ไขเพิ่มเติม]
หลังจากกลับมาดู code ตัวเองอีกครั้งพบว่าตอนที่เขียนนั้น เพิ่ม collect ต่อไปเรื่อยๆ
เพื่อให้ได้ผลที่ต้องการในแต่ละขั้น วันนี้เลยลองกระจายแล้วยุบรวมขั้นตอนต่างๆได้เป็น

a = 1..12
a.collect{
  a*.multiply(it) // compute
}.each {
  println( (it*.toString()*.padLeft(4)).join()) // display as a table
}

อธิบายตรง a*.multiply(it) หน่อยสิครับ
* มันมีความหมายว่าอะไร


อย่าง collect มันมี parameter เดียว เลยใช้ it แทน parameter ได้
แล้วอย่างพวก inject หรือ sort ที่รับหลาย parameter
จะเขียนอย่างไรครับ

*. เป็น operator แบบกลุ่มครับ
ใช้ได้ทั่ง method และ property ของ object ในกลุ่ม
เช่น

class Person {
  String name
  Integer age
  def String toString() {
    "$name: $age"
  }
}
 
john = new Person(name:'John', age:30)
mary = new Person(name:'Mary', age:25)
assert ['John: 30','Mary: 25'] == [john,mary]*.toString()
assert [30,25] == [john,mary]*.age
assert [30,25] == [john,mary].age // ใช้ได้เฉพาะ property

เป็น syntax ที่น่าสนใจดีครับ

การ define Closure คล้ายกับภาษาอื่นครับ

a = {x,y -> x + y}
assert 2 == a(1,1)

กรณีมี parameter เดียว ใช้ it ได้เลย

veer's picture

พึ่งรู้ว่า anonymous block ใน groovy เรียกว่า closure

ย้าย Codenone

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

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